The Wayback Machine - https://web.archive.org/web/20250304011146/https://www.geeksforgeeks.org/python-opencv-capture-video-from-camera/
Open In App

Python OpenCV: Capture Video from Camera

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Python provides various libraries for image and video processing. One of them is OpenCV. OpenCV is a vast library that helps in providing various functions for image and video operations. With OpenCV, we can capture a video from the camera. It lets you create a video capture object which is helpful to capture videos through webcam and then you may perform desired operations on that video.

Steps to capture a video:

  • Use cv2.VideoCapture() to create a video capture object for the camera.
  • Create a VideoWriter object to save captured frames as a video in the computer.
  • Set up an infinite while loop and use the read() method to read the frames using the above created object.
  • Use cv2.imshow() method to show the frames in the video.
  • Breaks the loop when the user clicks a specific key.

Below is the implementation.

Python
import cv2

# Open the default camera
cam = cv2.VideoCapture(0)

# Get the default frame width and height
frame_width = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (frame_width, frame_height))

while True:
    ret, frame = cam.read()

    # Write the frame to the output file
    out.write(frame)

    # Display the captured frame
    cv2.imshow('Camera', frame)

    # Press 'q' to exit the loop
    if cv2.waitKey(1) == ord('q'):
        break

# Release the capture and writer objects
cam.release()
out.release()
cv2.destroyAllWindows()

Explanation:

First, we import the OpenCV library for python i.e. cv2. We use the VideoCapture() class of OpenCV to create the camera object which is used to capture photos or videos. The constructor of this class takes an integer argument which denotes the hardware camera index. Suppose the devices has two cameras, then we can capture photos from first camera by using VideoCapture(0) and if we want to use second camera, we should use VideoCapture(1).

The dimensions of the frame and the recorded video must be specified. For this purpose, we use the camera object method which is cam.get() to get cv2.CAP_PROP_FRAME_WIDTH and cv2.CAP_PROP_FRAME_HEIGHT which are the fields of cv2 package. The default values of these fields depend upon the actual hardware camera and drivers which are used.

We are creating a VideoWriter object to write the captured frames to a video file which is stored in the local machine. The constructor of this class takes the following parameters:

  • Filepath/Filename: The file would be saved by specified name and at the specified path. If we mention only the file name, then the video file would be saved at the same folder where the python script for capturing video is running.
  • Four Character Code: A four-letter word to denote the specific encoding and decoding technique or format which must be used in order to create the video. Some popular codecs include ‘MJPG’ = Motion JPEG codec, ‘X264’ = H.264 codec, ‘MP4V’ = MPEG-4 video codec
  • Frame rate: Frame rate determines the number of frames or individual images which are shown in a second. Higher frame rates produce smoother video, but it will also take more storage space as compared to lower frame rates.
  • Video Dimension: The height and width of the video which are passed as a tuple.

Inside an infinite while loop, we use the read() method of the camera object which returns two values, the first value is boolean and describes whether the frame was successfully captured or not. The second value is a 3D numpy array which represents the actual photo capture. In order to represent an image, we need two-dimensional data structure and for representing color information, we must add another dimension to it making it three dimensional.

Then, we are writing the individual frames to the video file using the VideoWriter object which was previously created using the write() method which takes the captured frame as the argument. To display the captured frame, we are using cv2.imshow() function, which takes window name and the captured frame as arguments. This process is repeated infinitely to produce continuous video stream which consists of these frames.

In order to exit the application, we have break out of this infinite while loop. Hence we are assigning a key which can be used to quit the application. Here the cv2.waitKey() function takes and integer argument which denotes the number of milliseconds the program waits for to check whether the user has pressed any button. We can use this function to adjust the frame rate of the captured video by providing certain delay. We have assigned “q” as the quit button and we are checking every millisecond whether it is pressed in order to break out of the while loop. The ord() function returns the ASCII value of the character which is passed to it as an argument.

Output:



Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Set Countdown timer to Capture Image using Python-OpenCV
Prerequisites: Introduction to OpenCV Most of us have already captured image using countdown timer with our phones. We can do the same thing on our computer with the help of OpenCV. But here we can specify the countdown timer instead of choosing one of the specified countdown and whenever the particular key will be pressed (let’s say q) the countd
3 min read
Add image to a live camera feed using OpenCV-Python
In this article, we are going to learn how to insert an image in your live camera feed using OpenCV in Python. Stepwise ImplementationStep 1: Importing the libraries CV reads and stores all the images as a NumPy array. We need the NumPy library to manipulate the image and as expected we need the cv2 module. Python3 # importing libraries import cv
4 min read
Check if the camera is opened or not using OpenCV-Python
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. While writing code in Python using OpenCV, we may not be sure whether at the remote end camera is opened and working properly or not. The ca
2 min read
Camera Calibration with Python - OpenCV
Prerequisites: OpenCV A camera is an integral part of several domains like robotics, space exploration, etc camera is playing a major role. It helps to capture each and every moment and helpful for many analyses. In order to use the camera as a visual sensor, we should know the parameters of the camera. Camera Calibration is nothing but estimating
4 min read
Connect your android phone camera to OpenCV - Python
Prerequisites: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. Many a time, while doing Computer Vision or Ima
2 min read
Taking a Snapshot from System Camera using OpenCV in Java
The OpenCV library in Java contains a class named 'VideoCapture' which provides a method called read (which is predefined) to scan pictures from the webcam. Mat object is passed as a parameter in the read method. Concept: The 'javax.swing' PackageThe Abstract Window Toolkit (AWT) Let's discuss them briefly before diving into the procedure and impl
4 min read
How to capture a image from webcam in Python?
In this article, we will discuss how to capture an image from the webcam using Python. We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to capture an image. Method 1: Using OpenCV OpenCV library
3 min read
How to capture SIGINT in Python?
The signal module performs a specific action on receiving signals. Even it has the ability to capture the interruption performed by the user through the keyboard by use of SIGINT. This article will discuss SIGINT only, how to capture it, and what to do after it has been captured. Modules Required: Signal: The technique through which a program can r
3 min read
How to Capture udp Packets in Python
Capturing UDP (User Datagram Protocol) packets is a fundamental skill for network programmers and security enthusiasts. Python, being a versatile and powerful programming language, offers various libraries and tools to facilitate packet capture. In this article, we'll explore how to capture UDP packets using Python, specifically focusing on the pop
3 min read