Parvathy Sarat
Parvathy Sarat

Reputation: 393

How to avoid Video lag when writing using OpenCV2?

When I try to simply read and write a video with OpenCV2, it is introducing a 1.033x lag in the video - for eg, an original video of 3:17min becomes 3:24min in the output video, 19:00min becomes 19:38min. Is there something I am doing wrong here?

The FPS (29) and frame count stays the same in input and output videos. (I am trying to do facial recognition but I am trying to figure out the lag first)

input_movie = cv2.VideoCapture(video_under_analysis)
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
width, height = (
        int(input_movie.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(input_movie.get(cv2.CAP_PROP_FRAME_HEIGHT))
    )
fps = int(input_movie.get(cv2.CAP_PROP_FPS))
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
output_movie = cv2.VideoWriter()
output_file_name = "output.mp4"

# Define the codec and create VideoWriter object
output_movie.open(output_file_name, fourcc, fps, (width, height), True)
frame_number = 0
FRAME_LIMIT = length
while True:
    ret, frame = input_movie.read()
    frame_number += 1
    
    if not ret or frame_number > FRAME_LIMIT:
        break
    
    if frame is not None:
      output_movie.write(frame)

update_progress(1)
output_movie.release()
input_movie.release()

cv2.destroyAllWindows()

Upvotes: 1

Views: 990

Answers (1)

mibrahimy
mibrahimy

Reputation: 732

I think the issue might be in this line

fps = int(input_movie.get(cv2.CAP_PROP_FPS))

You are converting the float value to int. Your input video's fps might be some float like 29.9 which is converted to 29. Hence, the constant lag.

Upvotes: 3

Related Questions