Difference between revisions of "Basic GUI feature in OpenCV- Video"

From Lofaro Lab Wiki
Jump to: navigation, search
(GUI feature in OpenCV- Video)
(GUI feature in OpenCV- Video)
 
Line 15: Line 15:
 
         break
 
         break
  
# When everything done, release the capture
+
When everything done, release the capture
  
 
  cap.release()
 
  cap.release()

Latest revision as of 02:52, 20 October 2014

Whenever you are done with doing the image thing. You must want to go for some video capturing things. Video capturing can be done in two ways. We can capture video from a camera or we can take a video file to read the video. You need to create a VideoCapture object of OpenCV class which will help you to capture a video.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
   # Capture frame-by-frame
   ret, frame = cap.read()
   # Our operations on the frame come here
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
   # Display the resulting frame
   cv2.imshow('frame',gray)
   if cv2.waitKey(0):
       break

When everything done, release the capture

cap.release()
cv2.destroyAllWindows()


This is a sample code for capturing a video. You can see that we are passing 0 through the VideoCapture object, this is the reason why we want the object to capture video from only one camera which is attached with the laptop. For a second camera you can pass 1. This is how you can capture videos from multiple cameras. If you want to capture video from a video file you need simply to pass the video file instead of camera index number. For example if you want to read a video file named vtest.avi you should only change the argument of the object which will be like

cap = cv2.VideoCapture('vtest.avi')

The other codes will be same. You will see a grayscale video other than your original BGR image as we have used the method

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

To convert the BGR image to Gray image. If we want to save the video that we have seen through camera or video file we need to create a VideoWriter object.

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
# After reading the frame 
out.write(frame)


All other code will be same. These are the simple ways of capturing a video file from camera, showing it and saving for future use.