简体   繁体   中英

Convert single png file to mp4

I'm trying to find a way to convert a single png image to an mp4 file with a specified length. Solutions I have found are slow and unreliable when trying to make videos with longer lengths (multiple hours).

Here is my current solution in Python 3:

import os
import cv2

video_name = 'video.avi'
frame = cv2.imread('image.png')
height, width, layers = frame.shape

time = 300
    
video = cv2.VideoWriter(video_name, 0, 1 / 10, (width,height))

for i in range(int(time / 10)):
    video.write(cv2.imread(os.path.join('.', 'image.png')))

video.write(cv2.imread('image.png'))

cv2.destroyAllWindows()
video.release()

Basically the same image is appended multiple times to make up the video, and I found that it was very taxing to merge so therefore the fps is set to 0.1 seconds.

This feels like the wrong approach so any solutions are appreciated

you'll like PyAV. it's a proper wrapper around ffmpeg's libraries, not the usual subprocess kludges you find in random python packages.

it has a sample where frames are written with custom Presentation Timestamps instead of a fixed frame rate. the math/usage is a little nebulous thanks to ffmpeg not making those things clear in their own documentation.

basically you set av.VideoFrame.pts and that's it.

https://github.com/PyAV-Org/PyAV/blob/main/examples/numpy/generate_video_with_pts.py

do understand that video with unusually long times between frames may be a challenge for some video players, at least when trying to seek instead of playing sequentially.

OpenCV is not a media library. its video I/O functions are intended and designed to be convenient and not flexible.

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