Python: How to read video by imageio

As we know. There are two methods to read video in python. One is openCV, which is very popular, but it is not easy to install it. if you just need to some simple thing in Python, you can use the other method imageio. It’s easy to use imageio, but as for a novice, I also met some problems, so I decide to write it down.

I found some codes from internet like this.

import pylab
import imageio
	
filename = '/path/to/your/video.mp4'
	
vid = imageio.get_reader(filename,  'ffmpeg')
for num in enumerate(vid):
    image = vid.get_data(num)
    fig = pylab.figure()
    fig.suptitle('image #{}'.format(num), fontsize=20)
    pylab.imshow(image)
pylab.show()

An error occurred when I ran it. The error code is “IndexError: Reached end of video”. After I analyzed, maybe there was something wrong in enumerate. So I found the enumerate example from internet.

list1 = ["This", "is", "a", "test"]
for index, item in enumerate(list1):
    print index, item

It can run correctly. Output:

0 This
1 is
2 a
3 test

So I try to change print to get the image.

import pylab
import imageio
	
filename = '/path/to/your/video.mp4'
	
vid = imageio.get_reader(filename,  'ffmpeg')
for num , im in enumerate(vid):
    image = vid.get_data(num)

It can run correctly. So I find the difference between the error code and correct code. for num in enumerate(vid): VS for num , im in enumerate(vid):. The correct code has im variable. If you don’t need this variable. You can replace it with ‘_’.

Have fun and have a nice day.

Share this article to your social media
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Dev
Guest
Dev
3 years ago

A great article but the audio does not play with the video – how is this resolved?