OpenCV MP4 创建

5 python video opencv ffmpeg

我一直在尝试在 python 中使用 OpenCV 编写 MP4 视频文件。

AVI 创建工作正常,无论是在 linux 还是 windows 上,当我同时使用两者时:

out = cv2.VideoWriter('x.avi', 0, 30, (640, 480))
Run Code Online (Sandbox Code Playgroud)

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x.avi', fourcc, 30, (640, 480))
Run Code Online (Sandbox Code Playgroud)

乃至

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x', fourcc, 30, (640, 480))
Run Code Online (Sandbox Code Playgroud)

.

当我尝试保存 MP4 时,没有任何保存 - 使用:

fourcc = cv2.VideoWriter_fourcc(*"H264")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
Run Code Online (Sandbox Code Playgroud)

fourcc = cv2.VideoWriter_fourcc(*"AVC1")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
Run Code Online (Sandbox Code Playgroud)

没有错误发生,只是没有保存。

在过去的几天里,我已经尝试了一切,尽一切努力避免创建 AVI,然后使用 ffmpeg 将其转换为 MP4,因为我发现这是一种可怕的做法。

小智 -3

给出框架的高度和宽度的正确值:

import cv2

print ('Press [ESC] to quit demo')
# Read from the input video file
# input_file = 'Your path to input video file'
# camera = cv2.VideoCapture(input_file)

# Or read from your computer camera
camera = cv2.VideoCapture(0)

# Output video file may be with another extension, but I didn't try
# output_file = 'Your path to output video file' + '.avi'
output_file = "out.avi"

# 4-byte code of the video codec may be another, but I did not try
fourcc = cv2.VideoWriter_fourcc(*'DIVX')

is_begin = True
while camera.isOpened():
    _, frame = camera.read()
    if frame is None:
        break

    # Your code
    processed = frame

    if is_begin:
        # Right values of high and width
        h, w, _ = processed.shape
        out = cv2.VideoWriter(output_file, fourcc, 30, (w, h), True)
        print(out.isOpened()) # To check that you opened VideoWriter
        is_begin = False

    out.write(processed)
    cv2.imshow('', processed)
    choice = cv2.waitKey(1)
    if choice == 27:
        break

camera.release()
out.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

这段代码对我有用。