如何使用来自python的请求使用opencv从url打开图像

2024-09-29 23:17:12 发布

您现在位置: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\...

如果我没有错的话,这些是url图像的像素值,对吗?在

我的问题是:如何使用OpenCV实现同样的功能?在

我试过了:

^{pr2}$

我得到一个错误:

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/


Tags: https图像imagecomurl目标列表read
2条回答

@{a1}的回答解决了你的问题。以下是从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()

你刚才忘了stream=True和{}在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()

回答你的问题

.raw意味着您希望以字节流的形式检索响应,而响应不会通过任何度量来计算或转换(因此它不会解码gzip并压缩传输编码),但是使用^{gzip和deflate传输编码是自动进行的为您解码。在

在您的例子中,最好使用.content而不是{}

请求包文档中的以下注释

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.

参考文献:

https://2.python-requests.org/en/master/user/quickstart/#raw-response-content

https://2.python-requests.org/en/master/user/quickstart/#binary-response-content

相关问题 更多 >

    热门问题