Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read gif from url using opencv (python)

Tags:

python

opencv

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?

like image 617
Chan Avatar asked Jan 09 '18 07:01

Chan


People also ask

Can OpenCV read GIF?

Project description. Python library to convert single oder multiple frame gif images to numpy images or to OpenCV without PIL or pillow. OpenCV does not support gif images.

What format is the image read in using OpenCV in Python?

As I mentioned earlier, OpenCV reads the image in BGR format by default.


1 Answers

Steps:

  1. Use urllib to read the gif from web,
  2. Use imageio.mimread to load the gif to nump.ndarray(s).
  3. Change the channels orders by numpy or OpenCV.
  4. 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:

enter image description here

like image 162
Kinght 金 Avatar answered Oct 29 '22 07:10

Kinght 金