How to capture video using webcam in opencv python

Yashod Perera
2 min readAug 24, 2023
Photo by Chris Montgomery on Unsplash

It is just few lines of code. If you don’t know how to set up opencv for python please follow the following tutorial which will take 2mins.

VideoCapturemethod in openCV capture the video from a file or a connected camera.

Using the inbuilt camera.

Inbuilt camera can be access using 0 as follows and the video stream will quit on Esc key press.

import cv2 as opencvvideo = opencv.VideoCapture(0) #read inbuilt camerawhile True:
isTrue, frame = video.read()
opencv.imshow('Webcam', frame)
key = opencv.waitKey(5) if key%256 == 27:
break
video.release()
opencv.destroyAllWindows()

Using connected webcam

Connected webcams can be access using integer 1 — number of cameras connected.

import cv2 as opencvvideo = opencv.VideoCapture(1) #First connected camerawhile True:
isTrue, frame = video.read()
opencv.imshow('Webcam', frame)
key = opencv.waitKey(5)if key%256 == 27:
break
video.release()
opencv.destroyAllWindows()

Important — If you don’t have any inbuilt camera then the connected webcam can be access using 0 as follows.

video = opencv.VideoCapture(0) #First connected camera

Following link is for setting up virtual environment using pipenv.

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor