简体   繁体   English

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

[英]How to read gif from url using opencv (python)

I can read jpg file using cv2 as我可以使用 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)

However, when I do it with gif file, it returns an error:但是,当我使用 gif 文件执行此操作时,它返回一个错误:

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

How to solve this problem?如何解决这个问题?

Steps:步骤:

  1. Use urllib to read the gif from web,使用urllib从网络读取 gif,
  2. Use imageio.mimread to load the gif to nump.ndarray (s).使用imageio.mimread将 gif 加载到nump.ndarray (s)。
  3. Change the channels orders by numpy or OpenCV .通过numpyOpenCV更改频道顺序。
  4. Do other image-processing using OpenCV使用OpenCV其他图像处理

Code example:代码示例:

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()

Note.注意。 I use the gif in my another answer.我在另一个答案中使用了 gif。 Video Stabilization with OpenCV 使用 OpenCV 进行视频稳定

The result:结果:

>>> Total 76 frames!

One of the gif-frames displayed:显示的 gif 帧之一:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM