openCV:视频无法正确保存

问题描述 投票:0回答:1

输出视频只有1kB,无法打开。怎么了? 这是我的代码:

import cv2
import numpy as np

file_name = "Touhou - Bad Apple.mp4"
output_file_name = "Touhou - Bad Apple difference flip.mp4"

# Open the video file
video = cv2.VideoCapture(file_name)

# Get the dimensions of the video
frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_rate = video.get(cv2.CAP_PROP_FPS)


# Create a VideoWriter object to write the new video file
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Codec for .mp4 files
new_video = cv2.VideoWriter(output_file_name, fourcc, frame_rate, (frame_width, frame_height))

# Create first frame
new_frame = np.random.randint(0, 256, (frame_height, frame_width), dtype=np.uint8)
new_video.write(new_frame)

# Read and write the remaining frames
success, current_video_frame = video.read()
while True:
    success, next_video_frame = video.read()
    if not success:
        break

    difference = cv2.absdiff(current_video_frame, next_video_frame)
    difference = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY)
    
    new_frame = new_frame + difference
    new_video.write(new_frame)
    
    current_video_frame = next_video_frame

    cv2.imshow('Difference', new_frame)
    if cv2.waitKey(1) == ord('q'):
        break


# Release the video objects
video.release()
new_video.release()
cv2.destroyAllWindows()

随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。 随机文本,以便堆栈溢出让我可以发布它。

python opencv video
1个回答
0
投票

输出视频只有1kB,无法打开。怎么了?

问题可以解决。

将第 17 行的编解码器从 *mp4 修改为 *'h264'。

更改此:

fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Codec for .mp4 files

至:

fourcc = cv2.VideoWriter_fourcc(*'h264')  # Codec for .mp4 files

输出播放视频:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.