DEV Community

wimdenherder
wimdenherder

Posted on

How to record webcam with python to a file

This is a good example how as a programmer you have to keep searching before you get the right solution.

I started with this script from this site

import cv2
#Capture video from webcam
vid_capture = cv2.VideoCapture(0)
vid_cod = cv2.VideoWriter_fourcc(*'XVID')
output = cv2.VideoWriter("videos/cam_video.mp4", vid_cod, 20.0, (640,480))
while(True):
     # Capture each frame of webcam video
     ret,frame = vid_capture.read()
     cv2.imshow("My cam video", frame)
     output.write(frame)
     # Close and break the loop after pressing "x" key
     if cv2.waitKey(1) &0XFF == ord('x'):
         break
# close the already opened camera
vid_capture.release()
# close the already opened file
output.release()
# close the window and de-allocate any associated memory usage
cv2.destroyAllWindows()
Enter fullscreen mode Exit fullscreen mode

There are two errors in this script. First I got this response:

at 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Enter fullscreen mode Exit fullscreen mode

So I google a bit, and you have to create the folder videos first to make it work.

The second bug was that the size of the webcam input should match the output size, in this script (640,480). So I executed this script to get the resolution:

import cv2

#Capture video from webcam
vid_capture = cv2.VideoCapture(0)
width  = vid_capture.get(3)  # float `width`
height = vid_capture.get(4)  # float `height`
print(width)
print(height)
Enter fullscreen mode Exit fullscreen mode

It gave me 1280 x 720, then I updated the original script to these sizes and now it worked! Here is the complete script:

import cv2

#Capture video from webcam
vid_capture = cv2.VideoCapture(0)
vid_cod = cv2.VideoWriter_fourcc(*'XVID')
output = cv2.VideoWriter("videos/cam_video.mp4", vid_cod, 20.0, (1280,720))

while(True):
     # Capture each frame of webcam video
     ret,frame = vid_capture.read()
     cv2.imshow("My cam video", frame)
     output.write(frame)
     # Close and break the loop after pressing "x" key
     if cv2.waitKey(1) &0XFF == ord('x'):
         break

# close the already opened camera
vid_capture.release()
# close the already opened file
output.release()
# close the window and de-allocate any associated memory usage
cv2.destroyAllWindows()
Enter fullscreen mode Exit fullscreen mode

And now it worked! How is your experience with using scripts online and finding solutions for bugs in it?

Top comments (0)