[英]How to open an image from an url with opencv using requests from python
我正在尝试在python上使用OpenCV打开大量图像,因为我以后需要使用它们。
实际上,我可以像这样用枕头来实现这个目标:
url = r'https://i.imgur.com/DrjBucJ.png'
response = requests.get(url, stream=True).raw
guess = Image.open(response).resize(size)
我正在使用来自python的库requests
。
response
如下所示: b'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01\\xdb\\...
如果我没看错,那是网址图片中像素的值,对吗?
我的问题是:我该如何使用OpenCV?
我已经尝试过了
resp = requests.get(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
我得到这个错误:
image = np.asarray(bytearray(resp.read()), dtype="uint8")
AttributeError: 'Response' object has no attribute 'read'
我从以下网站获得了代码: https : //www.pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/
您只是在requests.get
忘记了stream=True
和.raw
resp = request.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()
回答你的问题
.raw
表示您希望以字节流的形式检索响应,并且响应不会通过任何方式进行评估或转换 (因此,它将不会解码gzip和deflate传输编码),而是使用.content
和deflate传输编码会自动为您解码 。
在您的情况下,最好使用.content
不是.raw
请求包文档中的以下说明
注意关于使用Response.iter_content与Response.raw的重要说明。 Response.iter_content将自动解码gzip并缩小传输编码。 Response.raw是原始的字节流-它不会转换响应内容。 如果您确实需要访问返回的字节,请使用Response.raw。
参考文献:
https://2.python-requests.org/en/master/user/quickstart/#raw-response-content
https://2.python-requests.org/en/master/user/quickstart/#binary-response-content
@ Mohamed Saeed的答案解决了您的问题。 以下是从网址获取图片的替代解决方案:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.