【问题标题】:How to read gif from url using opencv (python)如何使用opencv(python)从url读取gif
【发布时间】:2018-01-09 07:50:03
【问题描述】:

我可以使用 cv2 as 读取 jpg 文件

import cv2
import numpy as np
import urllib
url = r'http://www.mywebsite.com/abc.jpg'
req = urllib.request.urlopen(url)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr,-1)
cv2.imshow('abc',img)

但是,当我使用 gif 文件执行此操作时,它会返回错误:

error: (-215) size.width>0 && size.height>0 in function cv::imshow

如何解决这个问题?

【问题讨论】:

  • 据我所知,OpenCV 不支持 GIF 文件...尝试使用 PIL(枕头)加载它,然后将其传递给 OpenCV。 Here 您还有一个关于如何使用 PIL 和 this one 获取图像以转换为 OpenCV 的问题
  • 非常感谢,api55。

标签: python opencv


【解决方案1】:

步骤:

  1. 使用urllib从网络读取gif,
  2. 使用 imageio.mimread 将 gif 加载到 nump.ndarray(s)。
  3. 通过numpyOpenCV 更改频道顺序。
  4. 使用OpenCV 进行其他图像处理

代码示例:

import imageio
import urllib.request

url = "https://i.stack.imgur.com/lui1A.gif"
fname = "tmp.gif"

## Read the gif from the web, save to the disk
imdata = urllib.request.urlopen(url).read()
imbytes = bytearray(imdata)
open(fname,"wb+").write(imdata)

## Read the gif from disk to `RGB`s using `imageio.miread` 
gif = imageio.mimread(fname)
nums = len(gif)
print("Total {} frames in the gif!".format(nums))

# convert form RGB to BGR 
imgs = [cv2.cvtColor(img, cv2.COLOR_RGB2BGR) for img in gif]

## Display the gif
i = 0

while True:
    cv2.imshow("gif", imgs[i])
    if cv2.waitKey(100)&0xFF == 27:
        break
    i = (i+1)%nums
cv2.destroyAllWindows()

注意。 我在另一个答案中使用了 gif。 Video Stabilization with OpenCV

结果:

>>> Total 76 frames!

显示的 gif 帧之一:

【讨论】:

  • 你也可以使用库 gif2numpy。您可以在github.com/bunkahle/gif2numpy 找到它
  • @bunkus 我检查了你的图书馆gif2numpy。这是一个基于kaitaistruct 二进制结构描述符的好库。如果支持多帧gif就更好了。干得好!
  • 现在它还支持多帧。试一试,让我知道它是否适合你
  • @bunkus 我尝试使用git2numpy 读取多帧gif(例如Images/Rotating_earth.gif),它成功读取了44帧。好的。虽然存在一个问题,但我会对该项目发表评论。谢谢你的工作。
  • gif2numpy 已在 1.2 版中修复。图像现在出来没有丢失像素,github上的最新版本:github.com/bunkahle/gif2numpy
猜你喜欢
  • 1970-01-01
  • 2013-04-23
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 2020-08-11
  • 2021-05-15
相关资源
最近更新 更多