Welcome to this exciting tutorial where you’ll learn how to convert videos into GIFs using Python! GIFs, or Graphics Interchange Format, are a popular way to share short, looping videos without sound. They are widely used across social media platforms for entertainment, educational content, and more.
Python, with its simplicity and vast array of libraries, makes it an ideal programming language for beginners and professionals alike. In this tutorial, we’ll specifically explore how to harness Python’s power to transform video files into GIFs in a few easy steps.
This process not only introduces you to working with media files in Python but also encourages you to explore other possibilities for automating and customizing your content creation workflow.
Before we dive in, let me reassure you that this tutorial is designed with Python beginners in mind. By the end of this tutorial, you’ll not only have a cool GIF to share but also a solid understanding of working with videos in Python, setting a strong foundation for your future projects.
My approach to turning a video clip into a GIF
Before we discuss the coding part, let me give you an overview of how to turn a video into an animated GIF.
- I would like the user to first load the video using Python and find out the number of frames in the video.
- Based on the count of frames in the video, the user would then specify the number of frames to be included in the final GIF.
- Then those frames will be merged to create the GIF. These frames would have equal intervals of time in-between.
I will be using the following video as input and try to convert it into an animated GIF.
Now let’s see how we can use Python to build a free video to GIF converter.
Import Python libraries and modules
I will use the Moviepy library to perform video-to-GIF conversion. Other major Python libraries that will be used are Pillow and Numpy. So make sure all these libraries are installed in your system.
from moviepy.editor import VideoFileClip
import numpy as np
from PIL import Image
Function to count number of frames in video
As discussed above, the first step is to find the number of frames in the input video. For that, the following Python function will be used.
This function only needs the path of the video file and then it will find the count of frames in the video.
def count_frames(video_path):
"""
Count and return the number of frames in the input video.
Parameters:
- video_path: Path to the input video file.
"""
clip = VideoFileClip(video_path)
fps = clip.fps # Frames per second
total_frames = int(clip.fps * clip.duration)
return total_frames
Let’s say the video file’s name is “running_clip.mp4” and it is present in the current working directory.
# count the frames in the input video
count_frames("running_clip.mp4")
Output: 150
So, there are 150 frames in the input video.
Function to find timestamp of each frame
This is an intermediate function that will used by another function and not directly by the user.
This function will generate a list of timestamps from where to grab frames. It will also ensure the first and last frames of the video are included along with evenly spaced frames in between.
def get_frame_times(total_duration, num_frames):
"""
Parameters:
- total_duration: Total duration of the video in seconds.
- num_frames: Desired number of frames for the GIF including the first and last frames.
Returns:
- A list of times (in seconds) from which frames should be extracted.
"""
if num_frames <= 2:
return [0, total_duration]
# Evenly space frame times, including start and end
frame_times = np.linspace(0, total_duration, num_frames)
return frame_times
Function to convert video to GIF
This function will make a GIF from a video clip given the path to the video, the output path for the GIF, and the number of frames to include in the GIF.
def make_gif_from_video(video_path, output_gif_path, num_frames_to_include):
"""
Parameters:
- video_path: Path to the input video file.
- output_gif_path: Path where the output GIF should be saved.
- num_frames_to_include: The number of frames to include in the GIF.
"""
# Load the video file
clip = VideoFileClip(video_path)
# Calculate frame times
frame_times = get_frame_times(clip.duration, num_frames_to_include)
# Generate GIF
gif_clip = clip.subclip(0, clip.duration).to_gif(output_gif_path,
program='ffmpeg',
fps=max(1, num_frames_to_include/clip.duration),
opt='nq',
verbose=False,
dispose=True)
Turn a video into a GIF
Now I will call the make_gif_from_video()
function by passing the path of the video file, the path for the GIF file that will be generated, and the no. of frames to sample from the video to make the GIF.
video_path = "running_clip.mp4"
output_gif_path = "output.gif"
no_of_frames = 30
make_gif_from_video(video_path, output_gif_path, no_of_frames)
If you specify a high number of frames, then the GIF will be smoother but the file size will also be large. If you use a very small number of frames, then the size of the GIF file will be smaller but the quality of the GIF could worsen.
So, try different values for the number of frames and see which one is working best for your video.
Count the number of frames in the GIF file
Just in case you want to verify what are the number of frames used in the GIF, then run the following function.
def count_gif_frames(gif_path):
with Image.open(gif_path) as img:
frame_count = 0
# Attempt to move to the next frame.
try:
while True:
frame_count += 1
img.seek(img.tell() + 1)
except EOFError:
# End of sequence
pass
return frame_count
I will use the same GIF file and use the above function to find the number of frames.
count_gif_frames("output.gif")
Output: 30
The GIF contains 30 frames which is equal to the number of frames specified earlier while creating the GIF.