Python Program to Capture Video from Camera using OpenCV

Python OpenCV – Capture Video from Camera

You can record a video from Camera in Python using OpenCV Library.

In this tutorial, we shall learn how to record or capture a video

Steps to Record Video from Camera

To capture video from Camera using OpenCV cv2 library, follow these steps:

  1. Import cv2 library.
  2. Get Video Capture object for a camera using cv2.VideoCapture(). You can pass the camera index if there are multiple cameras connected to the computer.
  3. Set up a infinite while loop.
  4. In the while loop, read a frame from video capture object using its read() method.
  5. Show the frame in a window with cv2.imshow().
  6. You can setup to break the loop when user clicks in a specific key.
  7. At the end of your video capture, release the camera and destroy all the windows generated by cv2.imshow().


1. Capture Video using Python OpenCV cv2 library from Webcam

In the following example, we have passed index as 0 to VideoCapture class. This will bring up the primary and only camera connected to this computer, i.e., webcam.

Python Program

import cv2

# capture frames from a camera with device index=0
cap = cv2.VideoCapture(0)

# loop runs if capturing has been initialized 

	# reads frame from a camera 
	ret, frame = 

	# Display the frame
	# Wait for 25ms
	if cv2.waitKey(1) & 0xFF == ord('q'):
# release the camera from video capture

# De-allocate any associated memory usage 

I just captured my phone from the webcam.


In this OpenCV Tutorial, we learned how to use webcam to capture an image using OpenCV, with the help of example programs.

⫷ Previous tutorialNext tutorial ⫸