Home > OS >  Python openCV video recording not in true time
Python openCV video recording not in true time

Time:03-02

Trying to record "time true" video with openCV. When recording video footage it seems to be slightly sped up. If I hold a timer up to the webcam and then play it back saved footage is 3 - 5 seconds too fast per minute of saved footage.

How can I get the saved video to be exactly 1 minute if I record 1 minute from my webcam? Or 2 minutes of recording to be an exported 2-minute video?

import cv2
 
cap = cv2.VideoCapture(0)

fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH)   # float `width`
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float `height`

fourcc = cv2.VideoWriter_fourcc(*'XVID')
videoWriter = cv2.VideoWriter('MYPATH\\video.avi', fourcc, fps, (int(width),int(height)))
 
while (True):
    ret, frame = cap.read()
    if ret:
        cv2.imshow('video', frame)
        videoWriter.write(frame)
 
    if cv2.waitKey(1) == 27:
        break
 
cap.release()
videoWriter.release()
cv2.destroyAllWindows()

CodePudding user response:

Your program may write additional frames because True sentence at line 16 in your while loop, then change that value to check as conditional ret, by:

...
ret, frame = cap.read()
while (ret):    
    cv2.imshow('video', frame)
    videoWriter.write(frame)
 
    ret, frame = cap.read()

    if cv2.waitKey(1) == 27:
        break

cap.release()
videoWriter.release()
cv2.destroyAllWindows()    

CodePudding user response:

I have no idea why this fixed it... but changing the forcc to fourcc = cv2.VideoWriter_fourcc(*'MP4V') and then changing the output file from .avi to .mp4 fixed the problem.

  • Related