Working with video files
Using videos in OpenCV is very simple; in fact, every frame is an image and can be manipulated with the methods that we have already analyzed.
To open a video in OpenCV, you need to call the VideoCapture()
method:
cap = cv2.VideoCapture("video.mp4")
After that, you can call read()
, typically in a loop, to retrieve a single frame. The method returns a tuple with two values:
- A Boolean value that is false when the video is finished
- The next frame:
ret, frame = cap.read()
To save a video, there is the VideoWriter
object; its constructor accepts four parameters:
- The filename
- A FOURCC (four-character code) of the video code
- The number of frames per second
- The resolution
Take the following example:
mp4 = cv2.VideoWriter_fourcc(*'MP4V')writer = cv2.VideoWriter('video-out.mp4', mp4, 15, (640, 480))
Once VideoWriter
has been created, the write()
method can be used to add a frame to the video file:
writer.write(image)
When you have finished using the VideoCapture
and VideoWriter
objects, you should call their release method:
cap.release() writer.release()
Working with webcams
Webcams are handled similarly to a video in OpenCV; you just need to provide a different parameter to VideoCapture
, which is the 0-based index identifying the webcam:
cap = cv2.VideoCapture(0)
The previous code opens the first webcam; if you need to use a different one, you can specify a different index.
Now, let's try manipulating some images.