To capture video in Python using cv2, you can “use the cv2.VideoCapture() function.” This function creates an object of the VideoCapture class and accepts either a device index or the name of a video file. You can select a camera by passing 0 or 1 as an argument and then capture the video frame-by-frame.
Steps to capture a video
- Use the “cv2.VideoCapture()” method to get a video capture object for the camera.
- Set up an infinite while loop and use the “read()” method to read the frames using the above-created object.
- Use the “cv2.imshow()” method to show the frames in the Video.
- Breaks the “loop” when the user clicks a specific key.
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()
Go to the terminal and run the Python file using the following command.
It will ask for camera permission, and when you permit it, the webcam will be opened, and in the Python window, you will see yourself.
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.