Convert Mp4 Video To Gif Animation In Python

Convert Mp4 Video To Gif Animation In Python

See the source image

Convert Mp4 Video To Gif Animation In Python You can use Python to convert MP4 videos to animated GIF images. Of course, off-the-shelf applications do an excellent job. However, creating your own converter with Python is an interesting and useful experience.

In this tutorial we will take a look at the following tasks:

Extracting frames from MP4 videos.

Converting frames to GIF animation.

Creating a user interface for the converter program.

Let’s get started.

What We Will Need

Python uses the OpenCV library to recognize MP4 videos, extract and convert frames to JPG format. Let’s install it using pip, the package management system:

python3 -m pip install opencv-python

In addition, to create GIF animations from frames saved as JPGs, we also need the Pillow library. It is installed with pip:

python3 -m pip install Pillow

In order to create a graphical user interface, we will use the PySimpleGUI package. Let’s install it with the following command:

python3 -m pip install PySimpleGUI

Users of the Anaconda development environment do not need to install OpenCV and Pillow – they are already included in the component set. For Anaconda, you need to additionally install only PySimpleGUI.

Extracting Frames From Mp4 Videos

Deep Learning God Yann LeCun

Firstly, in creating a GIF animation is to choose a video from which to extract the frames you want. Furthermore, in our case, we will use a video that demonstrates the process of installing the Flask framework, which is used for web development in Python.

Moreover, you need to write a special function to extract the individual frames. You should create a new file, name it mp4_converter and paste the following code into it:

import cv2

def convert_mp4_to_jpgs(path):

    video_capture = cv2.VideoCapture(path)

    still_reading, image = video_capture.read()

    frame_count = 0

    while still_reading:

        cv2.imwrite(f”output/frame_{frame_count:03d}.jpg”, image)

        # read next image

        still_reading, image = video_capture.read()

        frame_count += 1

if __name__ == “__main__”:

    convert_mp4_to_jpgs(“flask_demo.mp4”)

This function takes the path to the MP4 file. Then it opens the video using the cv2.VideoCapture(path) method. Secondly, you can use this method to save the whole video frame by frame if you want. Thridly, to save the extracted frames, use the cv2.imwrite() method.

Moreover, after executing the code, you’ll see that there are as many as 235 frames in the 7-second video. In addition, after the frames are saved, you can start creating an animated GIF image.

Creating A Gif Animation From Single Images

At this step, you’ll write code to create a GIF image based on the frames we’ve extracted from an MP4 video with OpenCV.

Here we need Pillow library – with its help you can turn a set of images in a specified directory into a GIF animation. Create a new file, name it gif_maker, and save the code below to it:

import glob

from PIL import Image

def make_gif(frame_folder):

    images = glob.glob(f”{frame_folder}/*.jpg”)

    images.sort()

    frame_one = frames[0]

See the source image

    frames = [Image.open(image) for image in images]

    frame_one.save(“flask_demo.gif”, format=“GIF“, append_images=frames,

                   save_all=True, duration=50, loop=0)

if __name__ == “__main__”:

    make_gif(“output”)

Firstly, in this code snippet, Python uses the glob module to search for JPG files. After that, the frames are sorted in the right order, and in the final step, the JPG images are saved in GIF format.

Now we are ready to create the user interface of our converter.

Interface For An Application That Converts Mp4 To Gif

Firstly, PySimpleGUI is a cross-platform framework: it works on Linux, Mac OS, and Windows. Furthermore, this package includes several libraries for UI development, including Tkinter, wxPython, and PyQt. So when you installinstalled PySimpleGUI in the first step, you have Tkinter at your disposal by default.

Secondly, create a new file in the development environment, name it mp4_converter_gui, save the code below to it:

# mp4_converter_gui.py

import cv2

import glob

import os

import shutil

Johns Hopkins’ Jim Liew on Bitcoin’s Price in 2030, Ethereum & Zoom vs The “in class” Experience.

import PySimpleGUI as sg

from PIL import Image

file_types = [(“MP4 (*.mp4)”, “*.mp4”), (“All files (*.*)”, “*.*”)]

def convert_mp4_to_jpgs(path):

    video_capture = cv2.VideoCapture(path)

    still_reading, image = video_capture.read()

    frame_count = 0

    if os.path.exists(“output”):

        # remove previous GIF frame files

        shutil.rmtree(“output”)

    try:

        os.mkdir(“output”)

    except IOError:

        sg.popup(“Error occurred creating output folder”)

        return

    while still_reading:

        cv2.imwrite(f”output/frame_{frame_count:05d}.jpg”, image)

        # read next image

        still_reading, image = video_capture.read()

        frame_count += 1

def make_gif(gif_path, frame_folder=“output”):

    images = glob.glob(f”{frame_folder}/*.jpg”)

    images.sort()

    frames = [Image.open(image) for image in images]

    frame_one = frames[0]

    frame_one.save(gif_path, format=“GIF”, append_images=frames,

                   save_all=True, duration=50, loop=0)

def main():

    layout = [

        [

            sg.Text(“MP4 File”),

            sg.Input(size=(25, 1), key=“-FILENAME-“, disabled=True),

            sg.FileBrowse(file_types=file_types),

        ],

        [

            sg.Text(“GIF File Save Location”),

            sg.Input(size=(25, 1), key=“-OUTPUTFILE-“, disabled=True),

            sg.SaveAs(file_types=file_types),

        ],

        [sg.Button(“Convert to GIF”)],

    ]

    window = sg.Window(“MP4 to GIF Converter”, layout)

    while True:

        event, values = window.read()

        mp4_path = values[“-FILENAME-“]

        gif_path = values[“-OUTPUTFILE-“]

        if event == “Exit” or event == sg.WIN_CLOSED:

            break

        if event in [“Convert to GIF”]:

            if mp4_path and gif_path:

                convert_mp4_to_jpgs(mp4_path)

                make_gif(gif_path)

                sg.popup(f”GIF created: {gif_path}“)

    window.close()

if __name__ == “__main__”:

    main()

The code is quite long. Moreover, to make it easier to understand, let’s look at each step separately.

At the very beginning is the module import section:

# mp4_converter_gui.py

import cv2

import glob

Dr. Igor Halperin on Reinforecement Learning & IRL For Investing & The Dangers of Deep Learning.

import os

import shutil

import PySimpleGUI as sg

from PIL import Image

file_types = [(“MP4 (*.mp4)”, “*.mp4”), (“All files (*.*)”, “*.*”)]

This snippet imports into the application all the modules and packages needed to create the GUI, the graphical user interface. OpenCV (cv2), Pillow Image class, and PySimpleGUI, as well as several modules from the standard Python set, are involved in this process. Also, at this point, a variable is declared to which all allowable file formats are passed in the tuple list.

Let’s move on to the first function of the program:

def convert_mp4_to_jpgs(path):

    video_capture = cv2.VideoCapture(path)

    still_reading, image = video_capture.read()

    frame_count = 0

    if os.path.exists(“output”):

        # remove previous GIF frame files

        shutil.rmtree(“output”)

    try:

        os.mkdir(“output”)

    except IOError:

        sg.popup(“Error occurred creating output folder”)

        return

    while still_reading:

        cv2.imwrite(f”output/frame_{frame_count:05d}.jpg”, image)

        # read next image

        still_reading, image = video_capture.read()

        frame_count += 1

Firstly, this is a slightly modified version of the feature we created in the first step. As in the original version, we used the VideoCapture() method here to capture frames from MP4 videos and then save them as separate images.

However, this time we added a check for the existence and deletion of the output folder – in order to avoid accidentally saving frames from two MP4 files in the same directory: such a mixed set would make a very strange gif.

The next code snippet creates the output folder after deleting the existing one or generates an error message in case of a malfunction. In conclusion, the rest of the code is unchanged.

Let’s move on to the next function:

def make_gif(gif_path, frame_folder=“output”):

    images = glob.glob(f”{frame_folder}/*.jpg”)

    images.sort()

    frames = [Image.open(image) for image in images]

    frame_one = frames[0]

    frame_one.save(gif_path, format=“GIF”, append_images=frames,

                   save_all=True, duration=50, loop=0)

Here we use the make_gif() method to create a GIF file. The code is almost the same as in the original version, except here we pass the path to the GIF file so that each animation is saved with a new name.

Python For Trading : The Benefits

In conclusion, the final part of the code describes the window parameters and the application interface:

def main():

    layout = [

        [

            sg.Text(“MP4 File”),

            sg.Input(size=(25, 1), key=“-FILENAME-“, disabled=True),

            sg.FileBrowse(file_types=file_types),

        ],

        [

            sg.Text(“GIF File Save Location”),

            sg.Input(size=(25, 1), key=“-OUTPUTFILE-“, disabled=True),

            sg.SaveAs(file_types=file_types),

        ],

        [sg.Button(“Convert to GIF”)],

    ]

    window = sg.Window(“MP4 to GIF Converter”, layout)

    while True:

        event, values = window.read()

        mp4_path = values[“-FILENAME-“]

        gif_path = values[“-OUTPUTFILE-“]

        if event == “Exit” or event == sg.WIN_CLOSED:

            break

        if event in [“Convert to GIF”]:

            if mp4_path and gif_path:

                convert_mp4_to_jpgs(mp4_path)

                make_gif(gif_path)

                sg.popup(f”GIF created: {gif_path}“)

    window.close()

if __name__ == “__main__”:

    main()

When using the PySimpleGUI framework, the Elements interface elements are included in the layout list. For example, in our project, the Elements list includes the following UI elements:

Text – two objects that are used as the names of text input fields.

Input – also in duplicate. Moreover, one input field contains the path to the MP4 file, the other displays the path to the saved GIF file.

FileBrowse – button to open the “Find File” dialog box.

SaveAs – the “Save File” button to write the GIF file with the desired name.

Button – for starting the conversion process.

The next step is to pass the list of interface elements to the sg.Window object, which is responsible for displaying the application window. In addition, the window has a name, buttons to minimize, maximize and exit the program.

To handle events in the application window we create a while loop and read the events of the Window object. In this way, we get the values from the two objects sg.Input() which contains the paths to the MP4 and GIF files.

When the user clicks the “Convert to GIF” button, the program intercepts the event and calls first convert_mp4_to_jpgs() and then make_gif(). Moreover, if the conversion process completes successfully, a pop-up window will notify the user that the GIF file was created and show the path to it.

Run the execution of the code. You will see a window like this:

Not bad, right?

Let Us Summarize

Now you have all the code you need to convert MP4 videos to GIF animation. You can improve some things in our program – try for example to add error handling to functions in order not to accidentally overwrite old GIF files with new ones.

Moreover, you can also provide for reducing the size of frames, this reduces the final size of the GIF animation. Another way to reduce GIF files is to compress JPG frames before creating the animation.

In conclusion, there are other ways to improve and augment the code discussed in this guide. In addition, think about what other functionality this application is missing, and add it.

Convert Mp4 Video To Gif Animation In Python

Effie J Franks specializes in writing articles on such topics as Web Design and Python. She likes sharing her experience and tips in the form of articles and also works at professional CV services to help people to find their dream job. In addition, in her free time, Effie enjoys playing video games, reading, and camping.

Convert Mp4 Video To Gif Animation In Python