Video to Images Python OpenCV code

Video Folder Name: Test
Video Type: avi
New Image Folder: Test_re
Image Type: jpg

import sys
sys.path.append('.')

import cv2
import os
import glob
import re
from fastprogress import progress_bar


def extract_numbers(file_name):
    numbers = re.findall(r'(\d+)', file_name)
    return tuple(map(int, numbers))


work='Test'

video_list = glob.glob(f'./{work}/*.avi')
video_list = sorted(video_list, key=extract_numbers)
print(video_list)

video_name_list = os.listdir(f'./{work}')
video_name_list = sorted(video_name_list, key=extract_numbers)


for i, video in progress_bar(enumerate(video_list), total=len(video_list)):
    video_name = video_name_list[i].split('.')[0]
    print(f'--------------{i, video_name}------------------')
    if not os.path.exists(f"./{work}_re/{video_name}"):
        os.makedirs(f"./{work}_re/{video_name}")


    vidcap = cv2.VideoCapture(video)
    success,image = vidcap.read()
    count = 0
    while success:
      cv2.imwrite(f"./{work}_re/{video_name}/%04d.jpg" % count, image)     # save frame as JPEG file
      success,image = vidcap.read()
      count += 1

    print("finish! convert video to frame")

Leave a Reply

Your email address will not be published. Required fields are marked *