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...