如何使用OpenCV从URL读取gif(Python) [英] How to read gif from url using opencv (python)
本文介绍了如何使用OpenCV从URL读取gif(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用cv2读取jpg文件
I can read jpg file using cv2 as
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文件时,它会返回错误:
However, when I do it with gif file, it returns an error:
error: (-215) size.width>0 && size.height>0 in function cv::imshow
如何解决这个问题?
推荐答案
步骤:
- 使用
urllib
从网络上读取gif - 使用
imageio.mimread
将gif加载到nump.ndarray
. - 通过
numpy
或OpenCV
更改频道顺序. - 使用
OpenCV
进行其他图像处理
- Use
urllib
to read the gif from web, - Use
imageio.mimread
to load the gif tonump.ndarray
(s). - Change the channels orders by
numpy
orOpenCV
. - Do other image-processing using
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. 使用OpenCV进行视频稳定
Note. I use the gif in my another answer. Video Stabilization with OpenCV
结果:
>>> Total 76 frames!
显示的gif框架之一:
One of the gif-frames displayed:
这篇关于如何使用OpenCV从URL读取gif(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文