Convert a Video to MP4 Using python-opencv
¶
The code below converts a MOV vidoe file to a MP4 vidoe file using OpenCV in Python.
In [ ]:
import cv2
def video_to_mp4(
input, output, fps: int = 0, frame_size: tuple = (), fourcc: str = "H264"
):
vidcap = cv2.VideoCapture(input)
if not fps:
fps = round(vidcap.get(cv2.CAP_PROP_FPS))
success, arr = vidcap.read()
if not frame_size:
height, width, _ = arr.shape
frame_size = width, height
writer = cv2.VideoWriter(
output,
apiPreference=0,
fourcc=cv2.VideoWriter_fourcc(*fourcc),
fps=fps,
frameSize=frame_size,
)
while True:
if not success:
break
writer.write(arr)
success, arr = vidcap.read()
writer.release()
vidcap.release()
In [ ]:
video_to_mp4("in.mov", output="out.mov")
The above code might fail to work if your OpenCV is compiled with H264
encoding support.
In that case,
you can use MPV4
or AVC1
instead.
Convert a Video to MP4 Using moviepy
¶
moviepy
is even a better alternative
for converting format of videos.
For more details,
please refer to
Manipulate Videos Using MoviePy in Python
.
In [ ]: