In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to convert MP4 video into GIF animation through Python. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
Operation environment
You need to install the OpenCV binding to read the MP4 file and convert every frame in the video into a JPG file. Installation tutorial:
Python3-m pip install opencv-python
You also need Pillow to create an animated GIF from the JPG you extracted from the video. You can also install with pip:
Python3-m pip install Pillow
To create a GUI, I'll use PySimpleGUI here. To install the library, use the following command:
Python3-m pip install PySimpleGUI
If you are using Anaconda, include opencv-python and Pillow. You only need to install PySimpleGUI separately.
How to extract frames from MP4 Video
The first step in extracting frames from MP4 video is to find the video you want to convert to GIF.
To extract a single frame from the video above, you need to write some Python. Create a new file and name it mp4_converter.py. Then enter the following code:
Import cv2def 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 + = 1if _ _ name__ = = "_ main__": convert_mp4_to_jpgs ("flask_demo.mp4")
This code takes the path of the MP4 video file. Then use cv2.VideoCapture (path) to open the video. You can use this method to read through the entire video and extract each frame. When you extract a frame, you can write it out using cv2.imwrite ().
When you run this code, you will find that this 7-second video produces 235 frames!
Now you are ready to shoot these frames and convert them to animated GIF.
Change a frame to GIF
The next step in this process is to convert the frames extracted from the MP4 file using OpenCV to animated GIF.
This is the opportunity for the Pillow package to display its talents. You can use it to receive images folders and create your GIF. Open a new file and name it gif_maker.py. Then enter the following code:
Import globfrom PIL import Imagedef make_gif (frame_folder): images= glob.glob (f "{frame_folder} / * .jpg") images.sort () frames = [Image.open (image) for image in images] frame_one = frames [0] frame_one.save ("flask_demo.gif", format= "GIF", append_images=frames, save_all=True, duration=50 Loop=0) if _ _ name__ = "_ _ main__": make_gif ("output")
Here, you use Python's glob module to search for JPG files in the output folder. Then sort the frames so that they are in the correct order. Finally, you save them as GIF.
Create MP4 to GIF GUI
PySimpleGUI is a cross-platform GUI framework that runs on Linux, Mac, and Windows. It encapsulates Tkinter, wxPython, PyQt, and several other GUI toolkits, providing them with a common interface.
When you installed PySimpleGUI earlier in this article, you installed the default version of the wrapped Tkinter.
Open a new Python file and name it mp4_converter_gui.py. Then add this code to your file:
# mp4_converter_gui.pyimport cv2import globimport osimport shutilimport PySimpleGUI as sgfrom PIL import Imagefile_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 + = 1def 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 ()
This is a fairly long piece of code. Let's do a paragraph-by-paragraph analysis.
To get started, check the import section:
# mp4_converter_gui.pyimport cv2import globimport osimport shutilimport PySimpleGUI as sgfrom PIL import Imagefile_types = [("MP4 (* .mp4)", "* .mp4"), ("All files (*. *)", "*. *")]
Here, you import all the modules and packages needed to create the GUI application. This includes OpenCV (cv2), Pillow's Image clas and PySimpleGUI, and many of Python's own modules.
You also create a variable to hold the file types that can be loaded into GUI. This is a list of tuples.
Now is the time to turn your attention to the first function in 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
This is a modified version of the MP4 converter code you created earlier. In this version, you still use VideoCapture () to read the MP4 file and convert it into a separate frame.
However, you have added some additional code to delete the output folder (if it exists). This prevents you from accidentally merging two MP4 files into one output file, which can lead to GIF confusion.
You also added some code to try to create an "output" folder after deletion. If an error occurs while creating a folder, an error dialog box is displayed.
The rest of the code is the same as before.
Now you are ready to look at 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)
You can use make_gif () to convert frame folders to GIF files. This code is almost the same as the original code, except that you pass in the path to the GIF file to make it unique.
The last piece of code is your GUI code:
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 ()
In PySimpleGUI, you can add items to the Python list when you want to "layout" elements in the user interface. For this example, you add the following elements:
Sg.Text-there are two instances of this element. They are used as labels for input (text boxes)
Sg.Input-there are two instances of this element, which is a text box type element. A location to save the MP4 file, a location where you want to save the GIF
Sg.FileBrowse-Button to open the file browse dialog box
Sg.SaveAs-Button to open the save file as a dialog box
Sg.Button-A button that can do whatever you want
Next, you take the list of elements and pass it to sg.Window, which represents the window that contains all the other elements. Your window also has an exit button, a minimize button and a title bar.
To start the GUI event loop, you need to create a while loop and read the data from the Window object. This allows you to extract the values of two sg.Input () objects that contain the paths to the MP4 and GIF files.
When the user presses the button labeled "convert to GIF", you capture the event and call convert_mp4_to_jpgs () and make_gif (). If all goes well, the video will be converted and you will see a pop-up dialog showing where the newly created GIF will be saved.
Try running this code. You should see the following:
Now you have everything you need to convert MP4 video files to GIF. You can take many different steps to improve your code. For example, you can add more error handling to your code to avoid accidentally overwriting GIF.
You can also add some new UI elements to tell your code to resize each frame to help reduce the GIF. Another option is to change the compression of each individual JPG, which will also reduce the size of the GIF.
There are many other interesting ways to make this code better. Think about it, you will come up with some new features on your own!
This is the end of this article on "how to convert MP4 video into GIF animation through Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.