![]() |
VOOZH | about |
OpenCV is an open-source and popular computer vision library that contains several computer vision algorithms. You can read, display, write and do lots of other operations on images and videos using OpenCV. The OpenCV module is generally used in popular programming languages like C++, Python, and Java. To save a video in OpenCV cv.VideoWriter() method is used.
In this article, we will try to save key event video clips with OpenCV in Python.
The only things you need to decide are the following:
Required Modules
pip install opencv-python
pip install numpy
Deciding the Key Event
The key events can be anything ranging from the appearance of any particular object on the screen to the appearance of any particular person on the camera. You can get creative with that.
For the sake of this tutorial, I'll keep it simple and take the first case as my key event with slight modifications to it.
Main key event: The appearance of any red-coloured object on my camera
The code starts by importing the necessary libraries: cv2 for computer vision operations and Numpy for array manipulations.
The code initializes the video capture by creating a VideoCapture object. It can either capture frames from the default webcam (set as 0) or an external webcam (set as 1).
This section initializes the video writer to save the processed frames as a video file. It defines the video codec (fourcc) as 'XVID', frames per second (fps) as 20.0, and frame size as (640, 480).
The lower and upper limits of the red color range are defined using Numpy arrays. These values represent the minimum and maximum HSV values for the red color.
If a bounding box is found, the frame with the drawn rectangle is written to the output video file using the out.write() method.
A mask is created by applying the lower and upper limits to the HSV frame. The mask contains white pixels for regions that fall within the specified colour range and black pixels for the remaining regions.
A bounding box (bbox) is obtained by applying the cv2.boundingRect() function to the mask. This function identifies the minimum enclosing rectangle for the non-zero regions in the mask.
If a bounding box is obtained (i.e., red objects are detected), a rectangle is drawn on the frame using cv2.rectangle(). The rectangle is drawn around the bounding box coordinates with a green colour and a thickness of 2.
If a bounding box is found, the frame with the drawn rectangle is written to the output video file using the out.write() method.
Code:
Output :
If you run the above block of code with all the necessary dependencies/packages installed on your system then the output will be a video file as shown in the above image. The whole run is shown in the following video:
Video Example 1:
Video Example 2 :