在 python opencv 中从变量而不是文件打开下载的图像

问题描述 投票:0回答:1

我想将我下载的图像加载到opencv。我想避免将其保存到文件中。我可以完美下载图片:

page_html = requests.get("http://my_web_page.com")

image_src = parse.search('<img id="my_image" src="{}"', page_html.content.decode('utf-8'))[0]
if image_src:
    image = requests.get("http://my_web_age.com" + image_src).content

我可以将其保存到文件中并使用我的文件资源管理器进行检查:

with open('main_image.png', 'wb') as file:
    file.write(image.content)

但是如果我尝试直接从变量的内容加载图像,则不起作用:

cv2_image = cv2.imread(image.content, cv2.IMREAD_COLOR)

我得到:

SystemError: <built-in function imread> returned NULL without setting an error

从文件中读取仍然可以,但是可以跳过这一步吗?数据已经在变量中,所以应该是可以的。

python opencv
1个回答
2
投票

您可以使用numpy的frombuffer将数据转换为整数。 imdecode 然后将其转换为与 opencv 一起使用的图像数组。

工作示例:

import cv2
import numpy as np
import requests

# perform request
response =  requests.get('https://opencv-python-tutroals.readthedocs.io/en/latest/_images/messiup.jpg').content
# convert to array of ints
nparr = np.frombuffer(response, np.uint8)
# convert to image array
img = cv2.imdecode(nparr,cv2.IMREAD_UNCHANGED)

# showimage
cv2.imshow("Res", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
© www.soinside.com 2019 - 2024. All rights reserved.