Video basics

To capture a live stream from your machine’s camera.

Often, we have to capture live stream with camera. OpenCV provides a very simple interface to this. Let’s capture a video from the camera (I am using the in-built webcam of my laptop), convert it into gray-scale video and display it. Just a simple task to get started.

#to capture a live stream from camera
import cv2
cap=cv2.VideoCapture(0)
while(cap.isOpened()): 
    ret,frame=cap.read()
    print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    cv2.imshow('frame',frame)
    if cv2.waitKey(1)==ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

Functions used:

VideoCapture():

To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. Device index is just the number to specify which camera. Normally one camera will be connected (as in my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on. After that, you can capture frame-by-frame. But at the end, don’t forget to release the capture.

isOpened():

Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it is initialized or not by the method cap.isOpened().

What is ret and frame?

ret -is bool data type that returns true if python is able to read videoCapture object

frame -is a numpyarray , it represents the first image that the video capture

print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) ,

print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))

The above two lines of code returns us the frame height and the frame width respectively.These were used only to demonstrate various other functionality of cap .

At the end we release the videocapture object and destroy the created windows.

One Comment

Leave a Reply