DAY 76-100 DAYS MLCODE: YOLO Object Detection in Video
In the previous blog, we discussed regarding how to use the YOLO pre-trained model for object detection in the image, in this blog, we’ll discuss YOLO Object Detection in Video.
We’ll use the same code which we had developed for an object
- Use CV2.VideoCapture to get the video as source of image
- Use read() method to extract frame.
- Use the previous code to detect the object and draw the boxes.
- Use CV2.VideoWriter to write the image back to video
YOLO object detection in video
Let’s initialize the video writer and Video pointer for reading the video. Get the total number of frames.
video = cv2.VideoCapture(“Video.mp4”)
video_writer = None
(Weidth, Height) = (None, None)
prop = cv2.CAP_PROP_FRAME_COUNT
total = int(video.get(prop))
Below code will help to read the next from using. Read() method. IF found is not true that means there is no frame to extract any more and we can close the processing.
while True:
# read the next frame from the file
(found, img) = video.read()
# if the frame was not grabbed, then we have reached the end
# of the stream
if not found:
break
# if the frame dimensions are empty, grab them
if Weidth is None or Height is None:
(Height, Weidth) = img.shape[:2]
In the above code, we are extracting frame as an image and the rest of the logic is the same as a previous blog.
Now another piece of the code is to instead of displaying the image, we have to write the images back into video.
In the below code, we are checking whether videoWriter is initialized or not. If not, initialize the VideoWriter by passing the File Name, VideoWriter_fourcc as MJPG .
# check if the video writer is None
if video_writer is None:
# initialize our video video_writer
video_writer = cv2.VideoWriter(‘output.avi’,cv2.VideoWriter_fourcc(‘M’,’J’,’P’,’G’), 10, (img.shape[1], img.shape[0]), True)
# write the output frame to disk
video_writer.write(img)
# release the file pointers
Output :
In conclusion, the above code is exactly same as the Object detection in image except reading and loading the video file and then again writing back to drive. You can find the entire code here.