56

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

This Stack Overflow answer,

import cv2.cv as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil
url="some_url"

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

is not good because Python reported to me:

TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
postgres
  • 2,242
  • 5
  • 34
  • 50

7 Answers7

61

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('http://answers.opencv.org/upfiles/logo_2.png')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'

cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
berak
  • 39,159
  • 9
  • 91
  • 89
  • 2
    ok it works, but after that, i use also scikit image library: imgbnbin = mh.morph.dilate(gray, disk7) and i get: ValueError: morph.get_structuring_elem: Bc does not have the correct number of dimensions. Using local images i do not get this error, why now? – postgres Jan 11 '14 at 12:41
  • Using a local image my script works fine both with cv2 and scikit image libraries. Using url images and the code above my script is blocked when i start to work with scikit image: imgbnbin = mh.morph.dilate(gray, disk7) by a ValueError. I add only your code and used a "url image", so i do not figure out the Value Error. maybe url image is treated in a different way that scikit does not undestand? – postgres Jan 11 '14 at 12:53
  • oh, sorry. understand your problem, but no idea. – berak Jan 11 '14 at 12:56
  • maybe, i think by "url version" generate a 3d numpy array and i need a 2D numpy array! – postgres Jan 13 '14 at 11:29
  • 2
    it's a 3d array becaus of the color channels. if you want it 2d(grayscale), do : cv2.imdecode(arr,0) # load as grayscale – berak Jan 13 '14 at 11:53
  • 24
    In Python 3, the `urllib.urlopen` does not work, says that `urllib has no method named urlopen`. It should be `urllib.request.urlopen()`. – Puspam Jul 12 '20 at 17:49
  • if you want 3D array, change `img` to this `img = cv2.imdecode(arr, cv2.IMREAD_COLOR)` – Sabzaliev Shukur Mar 01 '22 at 17:13
  • 1
    For *Python3* you would need to open URL as such import urllib.request req = urllib.request.urlopen(url) – sanster9292 May 03 '22 at 00:32
  • This is outdated for Python 2. For Python 3, use this https://stackoverflow.com/a/76118995/5848041 – Anthony Mooz Apr 27 '23 at 09:47
49

The following reads the image directly into a NumPy array:

from skimage import io

image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tony S Yu
  • 3,003
  • 30
  • 40
20

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(resp.read()), 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
imutils.url_to_image(url)
Kelvin Wang
  • 627
  • 5
  • 21
  • 1
    readFlag=cv2.IMREAD_COLOR is essential when trying to compare between a remote and a local images that were the same. With -1 shapes of images were different. Thanks a lot! – LaintalAy Nov 14 '19 at 12:56
1

Updated Answer

import urllib
import cv2 as cv2
import numpy as np

url = "https://pyimagesearch.com/wp-content/uploads/2015/01/opencv_logo.png"
url_response = urllib.request.urlopen(url)
img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, -1)
cv2.imshow('URL Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Ajay Mall
  • 59
  • 2
  • 5
1

For Python 3:

import cv2
from urllib.request import urlopen

image_url = "IMAGE-URL-GOES-HERE"
resp = urlopen(image_url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR) # The image object

# Optional: For testing & viewing the image
cv2.imshow('image',image)

For Python 3 using Google Colab:

import cv2
from google.colab.patches import cv2_imshow
from urllib.request import urlopen

image_url = "IMAGE-URL-GOES-HERE"
resp = urlopen(image_url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR) # The image object

# Optional: For testing & viewing the image
cv2_imshow(image)
Anthony Mooz
  • 3,553
  • 1
  • 10
  • 10
1

I used @berak's code as a foundation. If you have a URL that requires authentication (username and password), you can use this method:

import cv2
import numpy as np
import requests


resp = requests.get('http://1.2.3.4/media/cam0/still.jpg?res=max',auth = requests.auth.HTTPDigestAuth("my_username","my_password"))
arr = np.asarray(bytearray(resp.content), dtype=np.uint8)
img = cv2.imdecode(arr, -1)

cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()
Soheil
  • 31
  • 3
0

Using requests:

def url_to_numpy(url):                     
  img = Image.open(BytesIO(requests.get(url).content))                                 
  return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)