hackerman90219
hackerman90219

Reputation: 81

OpenCV - VideoWriter FPS

I'm building a script to overlay bounding boxes onto my video via a CSV file. Each frame has n number of bounding boxes, and so I am just iterating over the bounding boxes in each frame and drawing a cv2.rectangle on the frame. As a result, I am writing to a frame many times, for all frames.

While my VideoWriter constructor takes in 23.97 FPS as a parameter, the resulting FPS is much lower. Is there an algorithm or a way in which I can set a proper FPS to compensate for the FPS drop after writing to the video?

Below is my code-snippet:

avg_fws = counter_written/float(total_frames-1)
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('data/bounding_videos/%s.avi' % video_file, fourcc, fps * avg_fws, (width,height))
counter = 1
print (counter_written)
while (video.isOpened()):
    ret, frame = video.read()
    if ret == True:
        if len(frames_dict) != 0:
            for i in frames_dict[counter].keys():
                box_dim = frames_dict[counter][i]
                x, y, w, h = box_dim
                cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 255, 255), 3)
                out.write(frame)
        else:   
            out.write(frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):                                                                           
            break                                                                                                       
    else:                                                                                                               
        break                                                                                                           
    counter += 1                                                                                                        
video.release()                                                                                                         
out.release()                                                                                                           
cv2.destroyAllWindows()                            

The counters are just for me to keep track / access the frames, and avg_fws is the average frames written per second which basically is total_num_of_frames_written / total_num_of_frames_in_video.

Upvotes: 0

Views: 1451

Answers (1)

ZdaR
ZdaR

Reputation: 22954

The problem with your code is that, you are writing multiple frames in your for loop for each rectangle drawn. What you need to do is draw all rectangles at once on a frame and write it only for a single time. It can be done by moving out.write(frame) out of your for loop.

Upvotes: 1

Related Questions