OpenCV MP4 Creation



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

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

out = cv2.VideoWriter('x.avi', 0, 30, (640, 480))

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x.avi', fourcc, 30, (640, 480))

甚至

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x', fourcc, 30, (640, 480))

当我试图保存一个MP4,但从来没有保存任何东西-使用:

fourcc = cv2.VideoWriter_fourcc(*"H264")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))

fourcc = cv2.VideoWriter_fourcc(*"AVC1")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))

没有发生任何错误,只是没有保存任何内容。

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

cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))
while(True):
    ret, frame = cap.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    c = cv2.waitKey(1)
    if c & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()

给出帧的高和宽的正确值:

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()

这段代码适用于我。

相关内容

  • 没有找到相关文章

最新更新