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 newRequest
object.params
: (optional) Dictionary, list of tuples or bytes to send in the query string for theRequest
.**kwargs
: Optional arguments thatrequest
takes.
Returns:
Response
object
urllib
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
Parameters:
url
: either a string or aRequest
object.data
: must be an object specifying additional data to be sent to the server, orNone
if no such data is needed. SeeRequest
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 assl.SSLContext
instance describing the various SSL options. SeeHTTPSConnection
for more details.cafile
,capath
,cadefault
: Deprecated since version 3.6:cafile
,capath
andcadefault
are deprecated in favor of context. Please usessl.SSLContext.load_cert_chain()
instead, or letssl.create_default_context()
select the system’s trusted CA certificates for you.
Returns:
- An object which can work as a context manager and has the properties
url
,headers
, andstatus
. Seeurllib.response.addinfourl
for more detail on these properties.