'Is there a way to add an image at the beginning of the video using Python?

I wanted to ask, is there a way to add an image at the beginning of a video using Python? I heard that OpenCV library adds a group of images to produce a video but dunno a way to actually add an image to an existing video.



Solution 1:[1]

For anyone who is experiencing the same thing, I managed to do it by creating a video of the image I had and then, merge/concatenate the original video with my video that has the image in. The code;

import cv2
import os
from moviepy.editor import VideoFileClip, concatenate_videoclips

image_path = '.../1.jpg'
video_path = '.../1.mp4'
image_video_path = '.../2.mp4'
frame = cv2.imread(image_path)
height, width, layers = frame.shape
video = cv2.VideoWriter(image_video_path, 0x00000021, 1, (width, height))
for i in range(2):
    video.write(frame)
video.release()

image_clip = VideoFileClip(image_video_path)
orig_video_clip = VideoFileClip(video_path)
final_clip = concatenate_videoclips([image_clip, orig_video_clip], method="compose")
final_clip.write_videofile('../final_video.mp4')

There could be improvements to be done, it's just an example to start with. I hope I helped.

Solution 2:[2]

Try moviepy! Looks like it does what you want https://github.com/Zulko/moviepy

Solution 3:[3]

Only using the moviepy library incase anyone need it:

from moviepy.editor import *

clip = VideoFileClip("video.mp4")
image = ImageClip("image.jpg").set_duration(1)


def crop(clip):
    clip = clip.crop(x1=420, width=1080)
    return clip


image = image.subclip(0, image.end).fx(vfx.fadeout, .5, final_color=[87, 87, 87])
clip = clip.subclip(0, clip.end).fx(vfx.fadein, .5, initial_color=[87, 87, 87])

combine = concatenate_videoclips([image, crop(clip)])

combine.write_videofile('output.mp4')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Felipe Rando
Solution 3 Nahidujjaman Hridoy