Tag Archives: create gif from video opencv

Creating gif from video using OpenCV and imageio

In this blog, we will learn how to create gif from videos using OpenCV and imageio library. To install imageio library, simply do pip install imageio. So, let’s get started.

Steps

  • Open the video file using cv2.VideoCapture()
  • Read the frames one by one using the cap.read() method
  • Convert each frame to RGB. This is required because imageio accepts images in RGB format.
  • Save the frames in a list and close the video file
  • Convert the frames list to gif using the imageio.mimsave() method. Set the frame per second (fps) according to your application.

Below is the code for this

This is how you convert video to gif. Now, let’s see how to convert a specific part of a video to gif.

Converting a specific part of a video to gif

There might be a case where instead of converting the entire video to a gif, you only want to convert a specific part of the video to a gif. There are several ways you can do this.

Approach 1

Using the fps of the video, we can easily calculate the starting and ending frame number and then extract all the frames lying between these two. Once the specific frames are extracted, we can easily convert them to gifs using imageio as discussed above. Below is the code for this where the frames are extracted from 20 seconds to 25 seconds.

Approach 2

You can also save the frames manually by pressing some keys. For instance, you can start saving frames when key ‘s’ is pressed and stop saving when key ‘q’ is pressed. Once the specific frames are extracted, we can easily convert them to gifs using imageio as discussed above. Below is the code for this.

Approach 3

This approach is comparatively more tedious. In this, you go over each frame one by one and if you want to include that frame in gif you press the key ‘a’. To exit, you press the key ‘q’. Once the specific frames are extracted, we can easily convert them to gifs using imageio as discussed above. Below is the code for this.

This is how you can convert specific part of a video to gif. Hope you enjoy reading.

If you have any doubts/suggestions, please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.