Aza*_*zel 6 python opencv python-requests
我正在尝试在 python 上使用 OpenCV 打开大量图像,因为我需要在后面使用它们。
实际上,我可以用这样的枕头来实现这个目标:
url = r'https://i.imgur.com/DrjBucJ.png'
response = requests.get(url, stream=True).raw
guess = Image.open(response).resize(size)
Run Code Online (Sandbox Code Playgroud)
我正在使用requestspython库。
该response如下所示:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\xdb\...
如果我没有错,这些是来自 url 图像的像素值,对吗?
我的问题是:我如何用 OpenCV 做同样的事情?
我试过这样:
resp = requests.get(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
Run Code Online (Sandbox Code Playgroud)
我得到这个错误:
image = np.asarray(bytearray(resp.read()), dtype="uint8")
AttributeError: 'Response' object has no attribute 'read'
Run Code Online (Sandbox Code Playgroud)
我从这个网站得到了代码:https : //www.pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/
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()
Run Code Online (Sandbox Code Playgroud)
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
| 归档时间: |
|
| 查看次数: |
6189 次 |
| 最近记录: |