Nafeem Haque

Software Engineer

20 Feb 2023

Reading Webcam Feed Using Python OpenCV

Reading webcam feed is very easy using python. We are going to introduce reading webcam using opencv in this post. We will explore more about opencv on later posts.

Lets jump right into the task.

First you are going to need to install opencv in your environment/virtual environment. we are going to run pip install opencv-python to fetch the dependency.

Now follow the steps as mentioned:

  • Create a python file, I will use main.py
  • Lets begin by importing the opencv librart
import cv2
  • We are going to now create a VideoCapture object as following
import cv2

vid = cv2.VideoCapture(0)

notice we are passing 0 as a parameter. this is because your default webcam can be access through this index. if you have multiple webcams,there can be other values as well. there are ways on how we can determine the index. we will take a look at those methds in the future posts (because this can vary depending on the operating system you are using).

  • Now we need to create a forever loop and try to read through the webcam and wait for user to exit out
import cv2  
  
vid = cv2.VideoCapture(0)
  
while(True):      
    ret, frame = vid.read()
    print(ret)
  
    cv2.imshow('frame', frame)
      
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
  
vid.release()
cv2.destroyAllWindows()

In the loop, the following line ret,frame = vid.read() reads the frame at this point in time, vid.read() returns two values one is a boolean which states whether it was successfull when reading the frame, other return value is image(more on this in future). we need to pass this value in cv2.imshow

The first value in cv2,imshow is the window name, where we will show the feed. the second parameter is the image that we collected by reading vid

The loop will run forever and keep showing the feed. To stop this program and give the user control of stopping it, we have written:

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

This will wait/listen for user key press. If the user presses q the loop will break.

After breaking out of the loop we need to release our vid object so that it releases the webcam. Also, we have created a gui window to show the webcam feed. Hence we need to destroy the windows. This is why we have added following lines:

vid.release()
cv2.destroyAllWindows()

Hopefully, you have learned something. We will explore more with open-cv in the future. Till then, Happy Coding!