Read Image From URL | OpenCV vs Pillow | Python

This tutorial will show you how to read/open an image from a URL using OpenCV (cv2) and Pillow (PIL). Also, we will show you how to read the image from a URL with request headers.

If you want to read them into Base64, you may read Image & Base64.

1. Read From a URL

OpenCV

import urllib.request

res = urllib.request.urlopen(url)
arr = np.asarray(bytearray(res.read()), dtype=np.uint8)
cv2_img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)

Pillow

import requests

pil_img = Image.open(requests.get(url, stream=True).raw)

2. Read From a URL (With Headers)

Sometimes you need to insert some request headers to get the results successfully. You can insert them as follows.

OpenCV

import urllib.request

headers = {'referer': 'https://www.google.com'}
req = urllib.request.Request(url, headers=headers)
res = urllib.request.urlopen(req)
arr = np.asarray(bytearray(res.read()), dtype=np.uint8)
cv2_img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)

Pillow

import requests

headers = {'referer': 'https://www.google.com'}
pil_img = Image.open(requests.get(url, headers=headers, stream=True).raw)

Syntax

Python requests

requests.get(url, params=None, **kwargs)

Parameters:

  • url: URL for the new Request object.
  • params: (optional) Dictionary, list of tuples or bytes to send in the query string for the Request.
  • **kwargs: Optional arguments that request takes.

Returns:

urllib

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

Parameters:

  • url: either a string or a Request object.
  • data: must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details.
  • timeout: (optional) a parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS, and FTP connections.
  • context: (optional) it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details.
  • cafilecapath, cadefault: Deprecated since version 3.6: cafilecapath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

Returns:

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.