首页 > 解决方案 > 如何在 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"))

标签: pythonimage-processingweb-scraping

解决方案


问题是您从中获得url['image_url']但您将其视为图像。

您必须再次requests.get()使用urlfrom['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"))

推荐阅读