I am trying to open a large list of images using OpenCV on python, because I need to work with them latter.
Actually, I can achieve this goal with pillow like this:
url = r'https://i.imgur.com/DrjBucJ.png'
response = requests.get(url, stream=True).raw
guess = Image.open(response).resize(size)
I am using the library requests
from python.
The response
looks like this: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\xdb\...
And if I am not wrong, those are the values of the pixels from the image of the url, correct?
My question is: how can I do the same with OpenCV?
I have tried it like:
resp = requests.get(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
And I get this error:
image = np.asarray(bytearray(resp.read()), dtype="uint8")
AttributeError: 'Response' object has no attribute 'read'
I got the code from this web: https://www.pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/
Run the command python -m SimpleHTTPServer (python2) or python -m http. server (python3) to turn a folder to a web application. The folder is where you leave your images. You could retrieve any images under this folder as any URL based resources.
cv2. imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix. Syntax: cv2.imread(path, flag)
You just forgot stream=True
and .raw
in requests.get
resp = requests.get(url,
stream=True
).raw
import cv2
import numpy as np
import requests
url = r'https://i.imgur.com/DrjBucJ.png'
resp = requests.get(url, stream=True).raw
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# for testing
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
To answer your question
.raw
mean that you want to retrieve the response as a stream of bytes and the response will not evaluated or transformed by any measure (so it will not decode gzip and deflate transfer-encodings) but with .content
The gzip and deflate transfer-encodings are automatically decoded for you.
In your case it will be better to use .content
over .raw
the following note from Requests package documentation
Note An important note about using Response.iter_content versus Response.raw. Response.iter_content will automatically decode the gzip and deflate transfer-encodings. Response.raw is a raw stream of bytes – it does not transform the response content. If you really need access to the bytes as they were returned, use Response.raw.
References:
https://2.python-requests.org/en/master/user/quickstart/#raw-response-content
https://2.python-requests.org/en/master/user/quickstart/#binary-response-content
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With