Search code examples
imageextractframeopencvpython

How to extract an image per minute from video with a predefined starting frame in cv2 VideoCapture


I would like to extract one image per minute from an mp4 video recording and I have a code for that already, however, I also would like to add a starting frame from where the extraction should start and either set an ending frame or the number of images that should be extracted. This is because I would like to avoid trimming the videos as it takes a very long time.

My existing code to extract the images is the following:

cap = cv2.VideoCapture(r'C:my_folder/my_video.mp4') 
i = 1
while (cap.isOpened()):
ret, frame = cap.read()

if ret == False:
    break
if i % 1800 == 0: 
    cv2.imwrite(r'C:/my_folder/pictures/' + str(i) + '.jpg', frame) 
                                                                                                    
i += 1
cap.release()
cv2.destroyAllWindows()

Let's say I would like to start the extraction from frame 2700 and from that every 1800th frame until I have 30 frames.

Is there a way to do this? Every help would be much appreciated!


Solution

  • Change the if condition to the following:

    if i > 2700 and i % 1800 == 0: