I am experiencing a conflict between the cv.write() to record the video captioning. The fps method works fine when I am not using cv.write to store each frame as a video file. However when I try save each frame using cv.write to a video file then the fps counter is stuck at zero. How could I resolve this ? I am letting an object detector predict bounding boxes on each frame of a downloaded YouTube video to illustrate its performance. I would like to store the predictions made on each frame in a video, including the frames per second. Please find the code snipped below:
video_path = 'video/yolo_video_1.mp4'
cap = cv.VideoCapture(video_path)
fps = 0
fps_start = 0
prev = 0
video_rec = cv.VideoWriter('yolov1_watches_youtube_2.avi',
cv.VideoWriter_fourcc(*'MJPG'),
30, (448, 448))
while(cap.isOpened()):
ret, frame = cap.read()
if not ret:
break
frame = np.array(frame)
frame = cv.resize(frame, (448, 448))
fps_end = time.time()
time_diff = fps_end - fps_start
fps = int(1 / (time_diff - prev))
prev = fps_end
height, width = frame.shape[:2]
fps_txt = "FPS: {}".format(fps)
frame = cv.putText(frame, fps_txt, (width - 80, 40), cv.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)
frame = transform(frame)
frame = frame.unsqueeze(0)
preds = model(frame)
get_bboxes = cellboxes_to_boxes(preds)
frame = frame.squeeze(0)
frame = frame.permute(1, 2, 0).numpy() * 255
bboxes = non_max_suppression(get_bboxes[0], iou_threshold = 0.5, threshold = 0.4, boxformat = "midpoints")
frame = draw_bounding_box(frame, bboxes, test = True)
cv.imshow('Video', frame)
video_rec.write(frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
video_rec.release()
cap.release()
cv.destroyAllWindows()