import cv2
from pathlib import Path

import fnmatch
import os


def listdir(dir_name, pattern="*"):
    return fnmatch.filter(os.listdir(dir_name), pattern)


data_folder = Path('../data/Video_V/')
video_files = listdir(str(data_folder), "*.mp4")

print("Number of videos: "+str(len(video_files)))


new_folder = Path('data/yolo_dataset/all/')

for i in range(len(video_files)):
    origin_name = video_files[i]

    file = data_folder / Path(origin_name)
    print(file)

    cap = cv2.VideoCapture(str(file))
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(length)

    number_name = 0

    while True:
        ret, frame = cap.read()
        if ret:
            split_origin_name = str(origin_name).split('.', 1)
            new_name = split_origin_name[0] + '_' + f"{number_name:07d}" + '.jpg'
            save = new_folder / Path(new_name)
            cv2.imwrite(str(save), frame)
            number_name += 1
        else:
            break
