我正在构建一个图像webscraper,并试图在屏幕上显示图像。我见过将图像保存到文件中的方法,但是,我想知道是否有一种方法可以在不将图像保存在文件中的情况下做到这一点。
这是我迄今为止的代码:
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = requests.get(url)
image = np.asarray(bytearray(res.json()['data'][0]['card_images'][0]['image_url'].encode()))
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
print(url_to_image("https://db.ygoprodeck.com/api_internal/v7/cardinfo.php?&num=5000&offset=0&view=List&misc=yes"))
问题是从['image_url']
获得url
,但将其视为图像。
您必须再次使用requests.get()
和url
才能从['image_url']
获得图像。
import requests
import numpy as np
import cv2
def url_to_image(url):
response = requests.get(url)
data = response.json()
image_url = data['data'][0]['card_images'][0]['image_url']
print('image_url:', image_url)
response = requests.get(image_url)
data = np.asarray(bytearray(response.content), dtype="uint8")
image = cv2.imdecode(data, cv2.IMREAD_COLOR)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return image
print(url_to_image("https://db.ygoprodeck.com/api_internal/v7/cardinfo.php?&num=5000&offset=0&view=List&misc=yes"))