Python OpenCV | Capturing Video From Camera














































Python OpenCV | Capturing Video From Camera



Capturing Video From Camera


Often, we have to capture live stream with camera. OpenCV provides a very simple interface to this. Le us capture a video from the camera (I am using the in-built webcam of my laptop), display it.  

To capture a video, we 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 we simply pass 0 (or -1). We can select the second camera by passing 1 and so on. After that, we can capture frame-by-frame. But at the end, don't forget to release the capture.

Code :

import cv2
import numpy as np

class Capture_Video:

   
def __init__(self, camera_key):
        self.camera_key = camera_key 

   
def OpenCamera(self):
        self.cap = cv2.VideoCapture(self.camera_key)

       
while (self.cap.isOpened()):

           
# Capture frame-by-frame
            self.ret, self.frame = self.cap.read()
            self.frame = cv2.flip(self.frame,
180)


           
#Display the resulting frame
            cv2.imshow(
"Window", self.frame)
           
if cv2.waitKey(1) & 0xFF == ord('q'):
               
break
               
        self.cap.release()
        cv2.destroyAllWindows()

def main():
    obj = Capture_Video(
0)
    obj.OpenCamera()

if __name__ == "__main__":
    main()


Comments