Saturday 20 September 2014

Capture Video from Camera

Capture Video from Camera


This example helps to capture a video using python & openCV.

Example:
-------------------------

import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

#release the capture
cap.release()
cv2.destroyAllWindows()
-------------------------

You can capture a video from a web camera connected to a system or using the built-in  webcam of a laptop. I am using my own built-in laptop camera .

We use cv2.VideoCapture( ) to capture a video.

cv2.VideoCapture()

cv2.VideoCapture(argument) ->  <VideoCapture Object>

So we create a VideoCapture Object by passing an argument into it.The argument can be the device index (to specify to use which camera) or the name of the file name. I have one built-in camera connected. so I simply pass 0( or -1). We can also pass 1 for the secondary camera.

for e.g.-  cap=cv2.VideoCapture(0)

cap.read( )

cap.read([,image]) ->  retval,image

for e.g.-  ret, frame = cap.read( )
It returns True if frame is read correctly, otherwise it returns false.

We can access some of the properties of the video using cap.get(propld). where propld is a number from 0 to 18. each no. indicating a different property of the video.

propId – Property identifier. It can be one of the following:
  • 0- Current position of the video file in milliseconds or video capture timestamp.
  • 1-based index of the frame to be decoded/captured next.
  • 2- Relative position of the video file: 0 - start of the film, 1 - end of the film.
  • 3- Width of the frames in the video stream.
  • 4- Height of the frames in the video stream.
  • 5- Frame rate.
  • 6-character code of codec.
  • 7- Number of frames in the video file.
  • 8- Format of the Mat objects returned by retrieve() .
  • 9- Backend-specific value indicating the current capture mode.
  • 10-Brightness of the image (only for cameras).
  • 11- Contrast of the image (only for cameras).
  • 12- Saturation of the image (only for cameras).
  • 13- Hue of the image (only for cameras).
  • 14- Gain of the image (only for cameras).
  • 15- Exposure (only for cameras).
  • 16- Boolean flags indicating whether images should be converted to RGB.
  • 17- Currently not supported
  • 18- Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
For e.g. :- To check the frame's height and width I can use cap.get(3) and cap.get(4) respectively.
Note:- We can also modify the properties as :- cap.set(propld,value)  
            where value-new value you want 
            For e.g:- To modify the height and width to 640x480, I use
                           ret=cap.set(3,640) &
                           ret=cap.set(4,480).
cap.release( )

It releases the capture.

No comments:

Post a Comment