问题
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/
回答1:
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
回答2:
@Mohamed Saeed's answer solved your problem. Below is an alternative solution to fetch image from a url:
import cv2
import numpy as np
from urllib.request import urlopen
req = urlopen('https://i.imgur.com/DrjBucJ.png')
image = np.asarray(bytearray(req.read()), dtype=np.uint8)
image = cv2.imdecode(image, -1)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
来源:https://stackoverflow.com/questions/57539233/how-to-open-an-image-from-an-url-with-opencv-using-requests-from-python