Solve the problem that opencv save video cannot be opened

Problem Description

        I use opencv to save the recorded video, but the saved video cannot be opened. I found a lot of information on the Internet, and later found that the size of the saved video and the recorded video are different. The original code is as follows

import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
videoWrite = cv2.VideoWriter(r'../videos/test.mp4', fourcc, 30, (640, 480))

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    videoWrite.write(frame)
    cv2.imshow('frame', frame)

    if cv2.waitKey(33) & 0xFF == ord('q'):
        break
        
videoWrite.release()
cap.release()
cv2.destroyAllWindows()

Solution

        The solution is very simple, just unify the size and use the code to get the width and height of the recorded video.

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

The complete code after the solution is as follows

import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
videoWrite = cv2.VideoWriter(r'../videos/test.mp4', fourcc, 30, (width,height))

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    videoWrite.write(frame)
    cv2.imshow('frame', frame)

    if cv2.waitKey(33) & 0xFF == ord('q'):
        break
        
videoWrite.release()
cap.release()
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/m0_51545690/article/details/123927912