How can I read an image from an Internet URL in Python cv2, scikit image and mahotas?


How can I read an image from an Internet URL in Python cv2?

This Stack Overflow answer,

import as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil

img_file = urllib2.urlopen(url)
im = StringIO(

is not good because Python reported to me:

TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__
Asked By: postgres



Since a cv2 image is not a string (save a Unicode one, yucc), but a NumPy array, – use cv2 and NumPy to achieve it:

import cv2
import urllib
import numpy as np

req = urllib.urlopen('')
arr = np.asarray(bytearray(, dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'

cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()
Answered By: berak

The following reads the image directly into a NumPy array:

from skimage import io

image = io.imread('')
Answered By: Tony S Yu

in python3:

from urllib.request import urlopen
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urlopen(url)
    image = np.asarray(bytearray(, dtype="uint8")
    image = cv2.imdecode(image, readFlag)

    # return the image
    return image

this is the implementation of url_to_image in imutils, so you can just call

import imutils
Answered By: Kelvin Wang

If you’re using requests, you can use this

import requests
import numpy as np
from io import BytesIO
from PIL import Image

def url_to_img(url, save_as=''):
  img =
  if save_as:
  return np.array(img)

img = url_to_img('https://xxxxxxxxxxxxxxxxxx')
img = url_to_img('https://xxxxxxxxxxxxxxxxxx', 'sample.jpg')

Answered By: rish_hyun

Using requests:

def url_to_numpy(url):                     
  img =                                 
  return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
Answered By: GeneralJMan Xjjice

Updated Answer

import urllib
import cv2 as cv2
import numpy as np

url = ""
url_response = urllib.request.urlopen(url)
img_array = np.array(bytearray(, dtype=np.uint8)
img = cv2.imdecode(img_array, -1)
cv2.imshow('URL Image', img)
Answered By: Ajay Mall