opencv-python reads webcam and saves it as a video file

In fact, some projects need to use cv2 (opencv-python) when they visualize the demo. Every time this part is written, it is a meal to find a blog, so write it yourself here, so that you can reuse it in the future:

import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:\\Users\\26254\\Desktop\\save_webcam_video.avi', fourcc, 20.0, (640,  480))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # write frame
    out.write(frame)
    cv2.imshow('webcam', frame)
    # press key 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Saved video

Guess you like

Origin blog.csdn.net/laizi_laizi/article/details/106284574