Friday, August 11, 2023

OpenCV basics continued...Load and Display Videos

We were able to load and display an image, now we are going to work with videos, and see how OpenCV can process videos.

Open the ShowVideo.py file in PyCharm. If you are not using the Github project, then create a new Python file, and make sure you have a video file available. There is an mp4 video file called “Sample Videos from Windows.mp4” in the Github project, it will be loaded and displayed in this example. Below is the code-

1 #

2 # Show a video from local file

3 #

4 import cv2

5

6 cap = cv2.VideoCapture("../res/Sample Videos from Windows.mp4")

7

8 success, img = cap.read()

9 while success:

10 cv2.imshow("Video", img)

11 # Press ESC key to break the loop

12 if cv2.waitKey(15) & 0xFF == 27:

13 break

14 success, img = cap.read()

15 cap.release()

16 cv2.destroyWindow("Video")

Line 6 Use cv2.VideoCapture() to load a video stream, the function returns a video capture object.

Line 8 Read the first frame from the video capture object, the frame image is stored in img variable, and the result is stored in success variable indicating True or False.

Line 9-14 Loop frame by frame until all frames in the video object are read, within the loop the image frames are processed one by one throughout the video.

Line 10 Use cv2.imshow() to display a frame. Each frame is an image.

Line 12-13 Wait for 15 milliseconds and accept a keystroke, if ESC key (keycode is 27) is pressed then break the loop. Changing the cv2.waitKey() parameter will change the speed of playing the video.

Line 14 Same as Line 8, load subsequent frames from the video capture object.

Line 15 Release the video capture object to release the memory.

Line 16 Close the Video window

Execute the codes, it will load the video and play it in a window called Video. It will play until either the end of the video or ESC key is pressed.

In Line 12 the cv2.waitKey(15) will wait for 15 milliseconds between each frame, changing the parameter value will change the speed of playing the video. If the parameter value is smaller then the play speed is faster, larger then slower.

Inside the loop from Line 9 to 14 you can process each image before showing it, for example you can convert each image to grayscale and display it, you will play the video in grayscale.

Replace the above Line 10 and 11 with the following two lines, it will convert the image from color to grayscale for every image frame inside the video, as a result, the video will be played in grayscale.

10 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

11 cv2.imshow("Video", gray)

Similarly, you can do other image processing inside the loop, for example recognize

the people or faces and highlight them in the video.

Share:

0 comments:

Post a Comment