简体   繁体   中英

Unable to save video using OpenCV python

I am new to Computer Vision, I started my journey of Image Processing by using Pillow and Skimage Library than I tried with opencv but when I am using opencv for video processing I am unable to save my video captured by system camera.

import cv2
import numpy as np
cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_write = cv2.VideoWriter('saved_out.avi', fourcc, 20.0, (640, 480))
while True:
    ret, frame = cam.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    video_write.write(frame)
    cv2.imshow('frame',frame)
    cv2.imshow('gray', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cam.release()
video_write.release()
cv2.destroyAllWindows()

Have you tried mp4v instead of xvid? The following works for me (windows):

writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20, shape)

If this doesn't work you can also try:

  1. Don't hard code the video dimensions, use frame.shape instead to make sure the dimension match. If they don't the writer cannot write the frame.

    ret, frame = video.read() height, width = frame.shape[:2] shape = (width, height) video_write = cv2.VideoWriter('saved_out.avi', fourcc, 20.0, shape)

IMPORTANT: if you are creating a frame from a np array, remember that width and height are inverted. I lost 2 hours on a Saturday debugging this on my code.

newFrame = np.zeros((height, width), dtype='uint8')
  1. The frame needs to be in BGR format (3 channels). If grayscale image is used, you must pass the flag False for color when instantiating your writer object, like so:

    writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20, shape, False)

Docs: VideoWriter(filename, fourcc, fps, size, is_color)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM