如何使用opencv(python)从url读取gif

Cha*_*han 6 python opencv

我可以使用cv2读取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)
Run Code Online (Sandbox Code Playgroud)

但是,当我使用gif文件时,它会返回一个错误:

error: (-215) size.width>0 && size.height>0 in function cv::imshow
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题呢?

Kin*_*t 金 12

脚步:

  1. 用于urllib从网上阅读gif,
  2. 用于imageio.mimread将gif加载到nump.ndarray(s).
  3. 通过numpy或更改渠道订单OpenCV.
  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()
Run Code Online (Sandbox Code Playgroud)

注意.我在另一个答案中使用了gif.使用OpenCV进行视频稳定

结果:

>>> Total 76 frames!
Run Code Online (Sandbox Code Playgroud)

其中一个显示的gif框架:

在此输入图像描述