Breaking News

Capture Video from WebCam using cv2 in Python

We can capture video from webcam using cv2. cv2 is used for many other image operations also.
First of all import cv2

import cv2

Now we need to capture feed from our webcam. Usualy webcam is on number 0. So we can use it.

cap = cv2.VideoCapture(0)

It is capturing images. Now we can use it to display video

while True:
    ret, frame = cap.read()
    cv2.imshow("Video Feed", frame)

Now we have to define how to close window. We use 'q' button to close this window and destroy all windows and release camera.

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

Now loop is closed. we can release camera.

cap.release()
cv2.destroyAllWindows()

Complete Code

Complete code for showing video is here

import cv2
# pass 0 as arg to capture feed from default camera
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    cv2.imshow('Video Feed', frame)
 
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()

No comments