Reading an image from a file is fairly straightforward in OpenCV-Python. But a lot of times, we would like to read an image from a URL and process it in OpenCV. One way to do it is to download the image, save it as a jpeg file, and then read it in OpenCV. But that’s too tedious! Who wants to do manual labor? Not me! Another way would be to automatically download the image as a jpeg file using wget and then reading it in OpenCV. This is slightly better, but it’s again a roundabout way of doing it because there is an intermediate step of saving the image on disk. How do we circumvent this and directly load an image from a URL into OpenCV-Python?
To do this, let’s create a new python file called “read_image_from_url.py” and add the following lines to it. The first step is to import the required packages:
import urllib import cv2 import numpy as np
We need the urllib package to process a URL. Let’s consider a random URL pointing to an image:
url = "http://s0.geograph.org.uk/photos/40/57/405725_b17937da.jpg"
The next step is to extract the contents of the URL:
url_response = urllib.urlopen(url)
Once we have the response, we need to convert it into a numpy array:
img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)
We are now ready to decode the image:
img = cv2.imdecode(img_array, -1)
Let’s see what img looks like. Add the following lines to the same python file:
cv2.imshow('URL Image', img) cv2.waitKey()
Let’s run the code:
$ python read_image_from_url.py
You should get the following output:
Another way to do it would be through the skimage package:
from skimage import io img = io.imread(url)
The “imread” function reads the images in RGB format. Since OpenCV uses BGR format, we need to convert the image format before it’s ready to be used:
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
Let’s see what it looks like:
cv2.imshow('URL Image', img) cv2.waitKey()
If you run the code, you will get the same output. We are all set!
———————————-——————————————————————————–
This method leads to blocking by website that are monitoring bots, so better used PIL library