Reputation: 15
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()
Upvotes: 0
Views: 667
Reputation: 216
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:
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')
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)
Upvotes: 1