python导入gif_如何使用OpenCV从URL读取gif(Python)

本文介绍了如何使用Python从网络上读取GIF文件,并通过imageio和OpenCV进行处理和显示。当使用cv2.imshow()显示GIF时遇到错误,可以改用imageio.mimread()加载GIF,然后转换通道顺序,最后通过循环显示每一帧。
摘要由CSDN通过智能技术生成

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)

However, when I do it with gif file, it returns an error:

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

How to solve this problem?

解决方案

Steps:

Use urllib to read the gif from web,

Use imageio.mimread to load the gif to nump.ndarray(s).

Change the channels orders by numpy or OpenCV.

Do other image-processing using 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. Video Stabilization with OpenCV

The result:

>>> Total 76 frames!

One of the gif-frames displayed:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值