First of all you need to install python and OpenCV on your computer. As editor I will use IDLE.

(of cause you no that, do you?)

Now let’s start programming. Open IDLE and take a new file.

Import opencv library

import cv2

 

Then we use a camera (I used the webcam of my computer)

cap = cv2.VideoCapture(0)

 

We use a suitable codec. If you are not familiar with codecs I suggest you to google for some information.

We assign a variable fourcc, and this part (‘m’,’p’,’4′,’v’) indicate that it is a mp4 video. If you want to xvid video then use,  fourcc = cv2.cv.CV_FOURCC(*’XVID’).

fourcc = cv2.cv.CV_FOURCC(‘m’,’p’,’4′,’v’)

 

Now we set up the writer.

output = cv2.VideoWriter(‘output.avi’,fourcc, 20.0, (640,480))

Here, the output.avi is the output file. The 20.0 value indicates the frame rate and (640,480) is the frame width and height in pixels.

 

Now we start looping.

while(cap.isOpened):

We read frame by frame and write them to create the video file output.avi
_, frame = cap.read()
output.write(frame)

simultaneously we can watch whats going on in video.
cv2.imshow(‘Image’,frame)

While writing the video file we can break it in any point with the press of ESC key .

k = cv2.waitKey(5) & 0xFF
if k == 27:
break

Finally make sure to release all.

cap.release()
output.release()
cv2.destroyAllWindows()

 

Save the file Run —> Run Module Or hit F5. Download the python file Here.

Record a video with OpenCV and python

Leave a Reply

Your email address will not be published. Required fields are marked *