【问题标题】:Storing images from web into variable in Python将来自网络的图像存储到 Python 中的变量中
【发布时间】:2022-01-22 07:02:22
【问题描述】:

我有很多图片的URL存储在网络上,一个URL的例子如下:

https://m.media-amazon.com/images/M/MV5BOWE4M2UwNWEtODFjOS00M2JiLTlhOGQtNTljZjI5ZTZlM2MzXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_QL75_UX190_CR0

我想从上述类似的 URL 加载图像,然后对该图像执行一些操作,然后返回结果图像。

这是我的代码:

def get_image_from_url(url, path):
    try: 
        # downloading image from url
        img = requests.get(url)
        with open(path, 'wb') as f:
            f.write(img.content)

        # reading image, str(path) since path is object of Pathlib's path class
        img = cv2.imread(str(path), cv2.IMREAD_COLOR)

        # some operations 
        
        # deleting that downloaded image since it is of no use now   
        if os.path.exists(path):
            os.remove(path)

        return resulting_image
    except Exception as e:
        return np.zeros((224, 224, 3), np.uint8)

但是这个过程花费了太多时间,所以我想而不是下载和删除图像,我会直接将 URL 上的图像加载到变量中。

类似这样的:

def store_image_from_url(url):
    image = get_image_from_url(url) # without downloading it into my computer 

    # do some operations 

    return resulting_image

有没有办法做到这一点?

谢谢

【问题讨论】:

  • 虽然可以实现您的要求,但您是否真正了解了通过网络下载图像所花费的时间与将图像写入磁盘所花费的时间?
  • @frippe 对于某些图像大约需要一分钟左右,而对于某些图像大约需要 2-3 秒

标签: python image


【解决方案1】:

作为How can I read an image from an Internet URL in Python cv2, scikit image and mahotas?,它可以是这样的:

import cv2
import urllib
import numpy as np

def get_image_from_url(url):
    req = urllib.urlopen(url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr, -1)
    return img

【讨论】:

  • 谢谢,它工作正常,但我们需要import urlib.request 而不是urlib.urlopen,它应该是urlib.request.urlopen
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多