pythonloopsopencvffmpegframes

Extracting frames every second of all videos in folder


I am trying to extract a frame every second of a video, while having multiple videos in a folder. I got it working for 1 video like this, but I think I am messing up my loop for all videos. Below is the code for 1 video that works.

import cv2
pathOut = r"C:/Users/Me/Out/"
vidcap = cv2.VideoCapture(r'C:\Me\Desktop\test.mp4');
count = 0
success = True
while success:
    success,image = vidcap.read()
    print('read a new frame:',success)
    if count%30 == 0 :
         cv2.imwrite(pathOut + 'frame%d.jpg'%count,image)
    count+=1

With the loop for all videos I made it up like this.

import os
import cv2
pathOut = r"C:/Users/Me/Out/"
count = 0
success = True
counter = 1
listing = os.listdir(r'C:/Users/Me/videos/train')
for vid in listing:
    vid = r"C:/Users/Me/videos/train/"+vid
    cap = cv2.VideoCapture(vid)
    count = 0
    counter += 1
    while success:
        success,image = cap.read()
        print('read a new frame:',success)
        if count%30 == 0 :
             cv2.imwrite(pathOut + 'frame%d.jpg'%count,image)
        count+=1

My vid loop does not seems to work because it is only taking one video. Then it states false, probably because there are no frames left, but I do not know how to push it forward to the next video. I think I need to do some minor adjustment, does anybody have any idea what exactly?


Solution

  • It seems to be a minor logical mistake: Once success has been set to false by the first video, it will never be set to true again and all subsequent while loops for all videos will be skipped. Try changing your program to:

    import os
    import cv2
    pathOut = r"C:/Users/Me/Out/"
    count = 0
    counter = 1
    listing = os.listdir(r'C:/Users/Me/videos/train')
    for vid in listing:
        vid = r"C:/Users/Me/videos/train/"+vid
        cap = cv2.VideoCapture(vid)
        count = 0
        counter += 1
        success = True
        while success:
            success,image = cap.read()
            print('read a new frame:',success)
            if count%30 == 0 :
                 cv2.imwrite(pathOut + 'frame%d.jpg'%count,image)
            count+=1