Python: Convert GIF To video(mp4) - python

I am trying to find some way for converting GIF to mp4 using Python or library. I didn't found any solution for it. I found a library for generating gifs from videos but not the other way round.
Can anyone please give me some information on how to do it.

Try MoviePy:
import moviepy.editor as mp
clip = mp.VideoFileClip("mygif.gif")
clip.write_videofile("myvideo.mp4")
If you don't have MoviePY installed then first install it:
pip install MoviePy

There are many ways to do this. Relatively simple way is to use ffmpeg. There are many python bindings. ffmpy is one of them. Please check here for the documentation. Basic example:
Installation:
pip install ffmpy
Usage:
>>> import ffmpy
>>> ff = ffmpy.FFmpeg(
... inputs={'input.gif': None},
... outputs={'output.mp4': None}
... )
>>> ff.run()
Again, there are many other ways to do this. Please find the related references here:
https://unix.stackexchange.com/questions/40638/how-to-do-i-convert-an-animated-gif-to-an-mp4-or-mv4-on-the-command-line
https://sonnguyen.ws/convert-gif-to-mp4-ubuntu/
How to Convert animated .gif into .webm format in Python?

from moviepy.editor import *
clip = (VideoFileClip("VIDEO.mp4")
.subclip((1,22.65),(1,23.2))
.resize(0.3))
clip.write_gif("nAME_OF_gif_FILE.gif")
You can download Video with this command if you have Youtube-dl installed:

Related

MoviePy RuntimeError: imageio.ffmpeg.download() has been deprecated

I try to run a simple script in Google Colab to determine a length of a video:
!pip install moviepy
from moviepy.editor import *
# Change directory:
os.chdir(r'/content/my_data')
clip = VideoFileClip("my_video.mp4")
print(clip.duration)
However, I obtain an error:
imageio.ffmpeg.download() has been deprecated. Use 'pip install imageio-ffmpeg' instead.'
After quick search I found that imageio needs to be downgraded by doing this:
!pip install imageio==2.4.1
So I changed the scrip to following:
!pip install moviepy
!pip install imageio==2.4.1
from moviepy.editor import *
# Change directory:
os.chdir(r'/content/my_data')
clip = VideoFileClip("my_video.mp4")
print(clip.duration)
I am still getting the same error.
Any idea how to fix it?
Thank you.
As moviepy is not in great shape nowadays I would recommend just using imageio's V2 API for the time being. It is really easy to get the metadata from a video file using it. Basically,
import imageio
path = "path/to/videofile.mp4"
video = imageio.get_reader(path)
print(video._meta)
Using the meta attribute you can access the number of frames, codec, size, etc. If you only want to get the duration (in seconds) you can just simply call for:
print(video._meta["duration"])
#Mr K.'s answer is correct; however, in modern versions of ImageIO you can use this alternative, which may be simpler:
import imageio.v3 as iio
location = "path/to/videofile.mp4"
duration = iio.immeta(location)["duration"]
print(duration)
(immeta reads the metadata of an image or video.)

Implementing skvideo.io.FFmpegReader in Python

Here is my code:
import numpy as np
import matplotlib.pyplot as plt
import skvideo
skvideo.setFFmpegPath("C:/Users/User/PycharmProjects/MachineLearning/venv/lib/site-packages/skvideo/io")
import skvideo.io
input_parameters ={}
output_parameters ={}
reader=skvideo.io.FFmpegReader("Cool_Kids.mp4",inputdict=input_parameters,outputdict=output_parameters)
num_frames,height,width,num_channels =reader.getShape()
print(num_frames, height, width, num_channels)
For analyzing Cool_Kids.mp4 video using skvideo library, before I would use
skvideo.setFFmpegPath("C:/Users/User/PycharmProjects/MachineLearning/venv/lib/site-packages/skvideo/io")
I was getting following error:
AssertionError: Cannot find installation of real FFmpeg (which comes with ffprobe).
Then after researching a bit I found this setFFmpegPath command, but got the same error. What part am I missing? There is this link
Cannot find installation of real FFmpeg (which comes with ffprobe), but I can't do more. What should I do?
You have to install FFmpeg command line tool.
It looks like have to install FFmpeg in your system outside of Python (I can't find a way to download ffmpeg.exe and ffprobe.exe using pip install command).
[Note: Installing FFmpeg in Windows, is different from the way described in your link].
You may also take a look at my answer to the following post.
Recommended solution:
Download FFmpeg (include FFprobe) executable for Windows (download the statically linked version).
Place ffmpeg.exe and ffprobe.exe in the same folder.
For example at: c:/FFmpeg/bin
Set setFFmpegPath to the above folder:
import skvideo
skvideo.setFFmpegPath("C:/FFmpeg/bin")
import skvideo.io
...
Note:
You may choose to place ffmpeg.exe and ffprobe.exe in the folder:
C:/Users/User/PycharmProjects/MachineLearning/venv/lib/site-packages/skvideo/io.

How to convert video on python to .mp4 without ffmpeg?

I need to convert videos to .mp4 format I used to ffmpeg but it converts for too long. Is there are a way to convert video to .mp4 in python without ffmpeg?
UPD moviepy depends on ffmpeg too (
==
Zulko/moviepy
pip install MoviePy
import moviepy.editor as moviepy
clip = moviepy.VideoFileClip("myvideo.avi")
clip.write_videofile("myvideo.mp4")
As per MoviePy documentation, there is no ffmpeg dependencies:
MoviePy depends on the Python modules Numpy, imageio, Decorator, and tqdm, which will be automatically installed during MoviePy's installation.
ImageMagick is not strictly required, but needed if you want to incorporate texts. It can also be used as a backend for GIFs, though you can also create GIFs with MoviePy without ImageMagick.
PyGame is needed for video and sound previews (not relevant if you intend to work with MoviePy on a server but essential for advanced video editing by hand).
For advanced image processing, you will need one or several of the following packages:
The Python Imaging Library (PIL) or, even better, its branch Pillow.
Scipy (for tracking, segmenting, etc.) can be used to resize video clips if PIL and OpenCV are not installed.
Scikit Image may be needed for some advanced image manipulation.
OpenCV 2.4.6 or a more recent version (one that provides the package cv2) may be needed for some advanced image manipulation.
Matplotlib
I wrote a quick program that will convert all video files of a particular type in a directory to another type and put them in another directory.
I had to install moviepy using Homebrew for it to work rather than rely on PyCharm's package installation.
import moviepy.editor as moviepy
import os
FROM_EXT = "mkv"
TO_EXT = "mp4"
SOURCE_DIR = "/Volumes/Seagate Media/Movies/MKVs"
DEST_DIR = "/Volumes/Seagate Media/Movies/MP4s"
for file in os.listdir(SOURCE_DIR):
if file.lower().endswith(FROM_EXT.lower()):
from_path = os.path.join(SOURCE_DIR, file)
to_path = os.path.join(DEST_DIR, file.rsplit('.', 1)[0]) + '.' + TO_EXT
print(f"Converting {from_path} to {to_path}")
clip = moviepy.VideoFileClip(from_path)
clip.write_videofile(to_path)

Rotating a video with Python 3.4

I am using moviepy to try resize a video clip but every time I try I get this error. Can anyone explain how I can fix it? Thanks
My python code
Import everything needed to edit video clips
from moviepy.editor import *
# Load video clip
myclip = VideoFileClip("dog.mov")
myclip.resize( (460,720) ) # New resolution: (460,720)
myclip.write_videofile("resized_clip.mp4") #write new video file
The error
File "/usr/local/lib/python3.4/dist-packages/PIL/Image.py", line 699, in tostring
"Please call tobytes() instead.")
Exception: tostring() has been removed. Please call tobytes() instead.
Looks like you are using PIL, I would try using Pillow, a support fork that is maintained. MoviePY recommends you use Pillow in lieu of Pil in it's docs:
http://zulko.github.io/moviepy/install.html
For advanced image processing you will need one or several of these
packages. For instance using the method clip.resize requires that at
least one of Scipy, PIL, Pillow or OpenCV are installed.
The Python Imaging Library (PIL) or, better, its branch Pillow .

Recording video with webcam using VideoCapture

I want to record a video with python (using my webcam) and I came across VideoCapture which was easy to install on windows. I know there is OpenCV out there, but that was too much for me.
So far I can create every 0.04 seconds a .jpg with this code:
from VideoCapture import Device
import time
cam = Device(devnum=0) #uses the first webcame which is found
x = 0
while True:
cam.saveSnapshot(str(x)+'.jpg', timestamp=3, boldfont=1) #########################
x += 1
time.sleep(0.04)
0.04 seconds * 25 = 1. So what I am planning to do is an animated gif, that has 25 frames/sec. If somebody of you knows how to produce a real video file like .mp4, I really would prefer the .mp4 rather than .gif. However if thats not possible, the next thing I need to do is, to concatenate all .jpg files (0.jpg, 1.jpg, 2.jpg ...) but as you can imagine with increasing recording time I get A LOT of files. So I was wondering if it would be possible to write the .jpg files (the frames) to one .gif file consecutively. If thats not possible in python, how would you concatenate the jpg files to get an animated gif in the end?
OpenCV will make it more easy. You will find more problem in your method. To use opencv you have to install 1 more package known as numpy (numerical python). It's easy to install. If you want to install it automatically:
Install
Install pip manually
After that go to your cmd>python folder>Lib>site-packages and type pip install numpy *but for using pip you have to be in internet access.
After installation of numpy just type pip intall opencv.
Now you can import all the packages. If numpy somehow fails, maunually downlaod numpy 1.8.0 and install it.

Categories