Python cv2 VideoCapture: How to Capture Video in Python
To capture a video in Python, use the cv2 VideoCapture class, and then create an object of VideoCapture. VideoCapture has the device index or the name of a video file. The device index is just an integer to define a which Camera. If we pass 0, then it is for the first or primary camera, 1 for the second camera so on. We capture the video frame by frame.
OpenCV (Open Source Computer Vision) is the computer vision library that contains various methods to perform operations on Images or videos.
OpenCV library can be used to perform multiple operations on videos. Python OpenCV library provides a cv2 VideoCapture class. Let’s understand this better.
OpenCV provides the cv2 VideoCapture class that is used to work with the Camera. We can do the following task:
- Read video, display video, and save the Video.
- Capture from the Camera and display it.
How to Capture Video from Camera in Python
OpenCV allows a candid interface to capture live stream with the Camera (webcam).
We need to create an object of VideoCapture class to capture a video. It accepts either a device index or the name of a video file.
A number which is specifying to the Camera is called device index. We can select a Camera bypassing the O or 1 as an argument. After that, we can capture the video frame-by-frame.
See the following code.
# app.py import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Now, go to the terminal and run the Python file by the following command.
It will ask for camera permission, and when you permit them, the webcam will be opened, and in the Python window, you will see yourself.
In this example, first, we have imported the cv2 module.
Then we have created an object of VideoCapture class. To obtain Video from the camera, we have to create an object of class VideoCapture. As an input, the constructor of the VideoCapture class receives an index of the device we want to use.
If we just have a single camera connected to the computer, we can simply pass a value 0.
You can pass one of the following values based on your requirements.
cv2.VideoCapture(0): Means first camera or webcam. cv2.VideoCapture(1): Means second camera or webcam. cv2.VideoCapture("file name.mp4"): Means video file
After this, we can start reading a Video from the camera frame by frame. We do this by calling the read method on the VideoCapture object.
This method takes no arguments and returns a tuple. The first returned value is a Boolean indicating if a frame was read correctly (True) or not (False).
We can use this value for error checking if we want to confirm no problem occurred while reading the frame. But for this tutorial demo, we will assume everything went well, so we are not going to look into this value.
In the next step, we have used a while loop.
Inside the while loop, we are reading the video frame by frame and pass to the cv2.imshow() function.
The cv2.imshow() method is used to display a video or image in a window. The window automatically fits the Video or image size.
Until we press the q key or 1 key, it will keep opening a web camera and capture the Video.
Load video in Grayscale mode
To load webcam video in Grayscale mode, we can use cv2.cvtColor() function. We just have to pass the cv2.COLOR_BGR2GRAY property to turn the Video into Gray. See the following code.
import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
The cap.read() returns the boolean value(True/False).It will return True, if the frame is read correctly.
How to Play Video from a file in Python
To play the video from a file, you have to provide the video path in the VideoCapture() method. It is similar to capturing from the Camera by changing the camera index with the file name.
The time must be appropriate for cv2.waitKey() function, and if time is high, the Video will be slow. If the time is too less, then the Video will be very fast.
import cv2 cap = cv2.VideoCapture('friends.mp4') while(cap.isOpened()): ret, frame = cap.read() cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
In this example, at the time of creating of VideoCapture object, we pass the Video called friends.mp4.
Then we read frame by frame show it to the Python window.
To show grayscale video, use cv2.cvtColor() method to convert video into Grayscale.
import cv2 cap = cv2.VideoCapture('friends.mp4') while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
This code will open the grayscale Video.
How to Save a Video in Python
To save a video using the cv2 library in Python, use cv2.VideoWriter_fourcc() method.
cv2.VideoWriter(filename, fourcc, fps, frameSize)
- filename: Input video file.
- fourcc: 4-character code of codec used to compress the frames.
- fps: framerate of the video stream.
- framesize: Height and width of the frame.
import cv2 # Create an object to read # from camera video = cv2.VideoCapture(0) # We need to check if camera # is opened previously or not if (video.isOpened() == False): print("Error reading video file") # We need to set resolutions. # so, convert them from float to integer. frame_width = int(video.get(3)) frame_height = int(video.get(4)) size = (frame_width, frame_height) # Below VideoWriter object will create # a frame of above defined The output # is stored in 'output.avi' file. result = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 10, size) while(True): ret, frame = video.read() if ret == True: # Write the frame into the # file 'output.avi' result.write(frame) # Display the frame # saved in the file cv2.imshow('Frame', frame) # Press S on keyboard # to stop the process if cv2.waitKey('q') & 0xFF == ord(1): break # Break the loop else: break # When everything done, release # the video capture and video # write objects video.release() result.release() # Closes all the frames cv2.destroyAllWindows() print("The video was successfully saved")
In this example, first, created an object of VideoCapture class.
Then we got the resolutions of the video object and converted it into an integer.
Then we call the cv2.VideoWriter() method and pass the name of the output video file, size, codec.
Then we write one by one frame in the output.avi file.
The waitKey() function returns the pressed key as a number. We will assume that we want to finish the program. So, if we press q key, then it will close the python window, and Video is saved in the filesystem.
The Video is stored in your current project folder because we have not specified the file path.
So, that is how you load and save the Video in Python using the OpenCV library.