将两个.AVI影片与OpenCV合并失败

balp4ylt  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(77)

我尝试使用OpenCV来合并两个.AVI视频,但收效甚微。我想要一个按顺序播放这两个视频的组合最终视频。
这两个输入视频是用Fiji的TrackMate算法创建的,大小分别为6.6和6.2 MB,每个都只有10秒,但是输出文件只有14 KB,并且根本不能在VLC Media Player中播放,所以我肯定是做错了什么。如何将两个.AVI视频合并成一个?
我的代码如下;它是从这个answer改编而来的,我认为是正确的FourCC:

import cv2

path = '/Volumes/GQA HD/GQA Experiments/2023_01_27/'
file1 = 'TrackMate capture of 1.avi'
file2 = 'TrackMate capture of 2.avi'

file_combined = 'TrackMate Combined captures of IMG_0240.avi'

# Paths of videos
videos = [path+file1, path+file2]

# Create new video
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
frameSize=(720,1280)
fps=30
video = cv2.VideoWriter(path+file_combined, fourcc, fps, frameSize)

# Write all frames sequentially to new video
for v in videos:
    curr_v = cv2.VideoCapture(v)
    while curr_v.isOpened():
        r, frame = curr_v.read()    # Get return value and curr frame of curr video
        if not r:
            break
        video.write(frame)          # Write the frame

video.release()                     # Save the video
z0qdvdin

z0qdvdin1#

frameSize可能应该是(1280, 720)而不是(720, 1280)
OpenCV大小约定是(widthheight),其中宽度是水平维度中的列数,高度是垂直维度中的行数。
在写之前,我们可以将frame的大小调整为(width, height),以防万一:

if frame.shape[0] != height or frame.shape[1] != width:
    frame = cv2.resize(frame, (width, height))

video.write(frame)

完整代码示例:

import cv2

do_create_sample_video_files = False

if do_create_sample_video_files:
    # Create sample video files for testing (use FFmpeg CLI for creating synthetic video files).
    import subprocess as sp
    import shlex
    sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=1280x720:rate=1:duration=300 -vcodec libx264 sample1.avi'))
    sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=640x360:rate=1:duration=300 -vcodec libx264 sample2.avi'))  # Use other resolution for testing

path = './'
file1 = 'sample1.avi'
file2 = 'sample2.avi'

file_combined = 'CombinedSample1Sample2.avi'

# Paths of videos
videos = [path+file1, path+file2]

# Create new video
width, height = 1280, 720
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
frameSize = (width, height) #(720,1280)  <-- Probably supposed to be (1280, 720).
fps=30
video = cv2.VideoWriter(path+file_combined, fourcc, fps, frameSize)

# Write all frames sequentially to new video
for v in videos:
    curr_v = cv2.VideoCapture(v)

    while curr_v.isOpened():
        r, frame = curr_v.read()    # Get return value and curr frame of curr video
        if not r:
            break

        if frame.shape[0] != height or frame.shape[1] != width:
            # Resize frame to the resolution of the destination video if required.
            frame = cv2.resize(frame, (width, height))

        video.write(frame)          # Write the frame

video.release()

相关问题