Search code examples
pythonvideo-captureopencv

I want to save the frames of video at certain time intervals using python opencv module


I want to save the frames of video at certain time intervals using python opencv module.

I have to divide the video file into 40 images. But I do not think of algorithms.

My Idea is:

  1. Input Video File.
  2. Counts the number of frames and fps in a video.
  3. Returns the spacing between frames. (length / 40)
  4. Run while

The way of Counting the num of frames, fps and jump interval:

length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)

After Counting the number of frame, fps and jump(Example):

D:\UCF-101\ApplyEyeMakeup\v_ApplyEyeMakeup_g01_c01.avi's FPS :  25.0
D:\UCF-101\ApplyEyeMakeup\v_ApplyEyeMakeup_g01_c01.avi's Length :  164
D:\UCF-101\ApplyEyeMakeup\v_ApplyEyeMakeup_g01_c01.avi's Running time :  6.56
D:\UCF-101\ApplyEyeMakeup\v_ApplyEyeMakeup_g01_c01.avi's jump :  4 ( 4.1 )

and here is while loop:

while count < length and save < 40:
    print("Count : ", count)
    success, frame = cap.read()
    cv2.imshow('Window', frame)
    if count % jump == 0:
        cv2.imwrite(save_path + LabelList[LabelNumber] + "\\" + FileList[FileNumber] + "_" + str(count) + ".jpg", frame)
        save = save + 1
        print("Saved! : ", save)
    cv2.waitKey(1)
    count = count + 1

And I faced two problems:

  1. A video with a total length of less than 30 frames
  2. There is not frame like 3.25 frame(there is just 3 frame, not float number)

Anyway, If you are interested in my problem, I will teach you in detail. I do not know what to say.

The important thing is that I want to save 40 images at regular intervals regardless of the length of the image.

Please help me bro...


Solution

  • There is not frame like 3.25 frame(there is just 3 frame, not float number)

    If you make jump a float, then just change your condition to count % jump < 1. You will get uneven spacings between the frames, but should end up with 40 frames in each case.

    A video with a total length of less than 30 frames.

    Just set jump to 1 if the number of frames is <= 40, and you will get all available frames.