簡體   English   中英

如何使用python的請求通過opencv從URL打開圖像

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM