Creating OpenCV MP4

I am trying to write MP4 video files using OpenCV in python.

Creating AVI works great on both linux and windows when I use both:

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

and

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

and even

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

.

When I try to save MP4 but save nothing - using:

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

and

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

Errors do not occur, only does not save anything.

I tried everything in the last few days, doing everything so as not to create AVI, and then convert it to MP4 using ffmpeg, because I think this is a terrible practice.

+4
source share
1 answer

Specify the correct frame heights and widths:

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

This code works for me.

-3
source

Source: https://habr.com/ru/post/1650407/


All Articles