简体   繁体   中英

How to append an image to a video using OpenCV or FFMPEG or Moviepy or other libraries?

Do you know a library in Python to add a frame image to an existing video? The result video must have the same quality as the image.

I tried to use OpenCV to add google image: https://www.google.com/search?q=google&sxsrf=ALiCzsZhrdoHnOTmg0We4dxtguCqzma5Jg:1657603343101&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiTh8bTzfL4AhWhplYBHfXNAKwQ_AUoAXoECAIQAw&biw=1492&bih=739&dpr=1.25#imgrc=PRtenhDnrVrfOM

But the quality decreases when the video elongates.

Here is the final result video : https://drive.google.com/file/d/1ArDvoX-kN9H_oLbACk3kU1Cid93SMczC/view?usp=sharing

Here is my code using OpenCV:

        image = cv2.imread(path_image)
        height, width, dimensions = image.shape
            
        video = cv2.VideoCapture(path_video)
        
        
        frames = []
        while(True):
            
            ret, frame = video.read()
            
            if ret == True: 
                frames.append(frame)
                # frame = frame.resize(frame, (width, height), fx=0, fy=0, interpolation = cv2.INTER_CUBIC)
                
                # Press S on keyboard 
                # to stop the process
                if cv2.waitKey(1) & 0xFF == ord('s'):
                    break
            # Break the loop
            else:
                break
            
        video2 = cv2.VideoWriter(path_video,cv2.VideoWriter_fourcc('M','J','P','G'), 30, (width, height))
        for frame in frames:
            video2.write(frame)
        video2.write(image)
        video2.release()  # releasing the video generated     
        print("Added {}".format(image_name))

I hope to improve the quality of this video.

I guess a simple way to achieve that using moviepy would be the following:

from moviepy.editor import *
from PIL import Image
import numpy as np

maxsize = (target_width, target_height)
jpg_image = Image.open(path_to_the_image)
# modify the image's resolution to be the target one
jpg_image.thumbnail(maxsize, Image.ANTIALIAS)
jpg_image = np.array(jpg_image)
image = ImageClip(jpg_image).set_duration(target_duration)

clip = VideoFileClip(path_to_the_video)
video = concatenate([image, clip], method="compose")
video.write_videofile("output_example.mp4", fps=target_fps)

As long as you set the target resolution of the image to match the video's one you are set with just that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM