python - 如何在 python 中从网络抓取的 URL 打印图像
问题描述
我正在构建一个图像网络抓取工具,并试图在屏幕上显示图像。我见过将图像保存到文件的方法,但是,我想知道是否有一种方法可以在不将图像保存到文件的情况下做到这一点。
这是我到目前为止的代码:
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"))
解决方案
问题是您从中获得url
,['image_url']
但您将其视为图像。
您必须再次requests.get()
使用url
from['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"))
推荐阅读
- python-3.x - 我无法在 python 生成器中回调
- python - 我正在学习python,但我无法弄清楚这段代码有什么问题?
- android - 我正在尝试使用片段创建 BottomNavigationView,并且我想在主布局中使用片段
- c# - 在上传到 S3 的对象上设置“Content-Disposition”?
- javascript - 如何在两个不同的角度应用程序之间传递数据
- sql - 在 SQL 中,FROM 前面的逗号分隔列表是什么意思?
- angular - Angular:两个输入,一种方式镜像
- javascript - 打字稿/角度:过滤对象数组
- smartcard - 是否可以通过 PKCS#11 开发 baseCSP 卡微型驱动程序?
- php - 未从 codeigniter 中的 s3 存储桶获取图像