Abhishek Srivastava
Abhishek Srivastava

Reputation: 46

Frame extraction for multiple videos in file directory

Though there exist several ways to extract frames from video, I want to create a loop for frame extraction of multiple videos present in directory.

A main key feature to include is to number frames in a serial manner (i.e. 1-60 then 61-120 and further). one method is to extract for one video at a time and repeat for all but this is way lengthy.

tried code: (got it from somewhere and tried changes as per my directory)

i = 1  # Counter of first video
input_filenames='Dataset/videos'

for input_filename in intput_filenames:
    cap = cv2.VideoCapture(input_filename)

   
    while True:
        ret, frame = cap.read()  # Read frame from first video

        if ret:
            cv2.imwrite(str(i) + '.jpg', frame)  
            cv2.imshow('frame', frame)  # Displaying frame for testing
            i += 1 # Advance file counter
        else:
            break # Break the interal loop when res status is False.

        cv2.waitKey(100) #Wait 100msec 

    cap.release() 

Upvotes: 0

Views: 723

Answers (2)

Abhishek Srivastava
Abhishek Srivastava

Reputation: 46

After a lot of search and trial, I finally achieved the goal of iterating the video file in the directory and extract the frame in continuous sequence.

code:

def frames_multiple_videos(filenames):
    i = 1  # Counter of first video

    for j in filenames:
        cap = cv2.VideoCapture(j)

        while True:
            ret, frame = cap.read()  # Read frame from first video
        
            if ret!=True:
                cv2.imwrite(filenames +'frame' + str(i) + '.jpg', frame)  # Write frame to JPEG file (frame1.jpg, frame2.jpg, ...)
                i += 1 # next file counter
            else:
                break

            cv2.waitKey(100) #(for debugging)

        cap.release() #Release must be inside the outer loop
        
all_frame=frames_multiple_videos('*your_directory*')

Upvotes: 2

Linh
Linh

Reputation: 43

If I guess right, you want to extract each video in the directory at a specific number of frames, right? You can try this code out!

for line in f.readlines(): #reading each video in directory, in this case I save in txt and read each line
    frame_reader = imageio.get_reader(link_video, 'ffmpeg', mode='I')
    start_idx, end_idx = 10, 70
    save_mat = np.full((output_size, output_size, 3, 1), 0) #please define the size of frame
    for frame_num, frame in enumerate(frame_reader):
        if frame_num >= end_idx:
           break
        if frame_num <= start_idx:
           continue
        save_mat = np.concatenate((save_mat, np.expand_dims(frame, axis=3)), axis=3)

     

Upvotes: 0

Related Questions