File size: 3,702 Bytes
c2ff18a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import csv
import cv2

VIDEO_EXTENSIONS = [".mp4", ".webm", ".mkv"]

def list_video_files(folder_path):
    return [f for f in os.listdir(folder_path) if os.path.splitext(f)[1].lower() in VIDEO_EXTENSIONS]

def load_csv(csv_path):
    with open(csv_path, 'r', newline='', encoding='utf-8') as csv_file:
        reader = csv.reader(csv_file)
        next(reader)  # Skip header
        return list(reader)

def save_csv(csv_path, data):
    with open(csv_path, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["filename", "label"])
        writer.writerows(data)

def find_first_unlabeled(data):
    for i, row in enumerate(data):
        if row[1] == '-1':
            return i
    return -1

def create_label_csv(folder_path, csv_file_path):
    video_files = list_video_files(folder_path)
    if not video_files:
        print(f"No video files found in {folder_path}")
        return

    folder_name = os.path.basename(folder_path)
    csv_file_path = os.path.join(csv_file_path, f"{folder_name}.csv")

    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["filename", "label"]) 
        for video_file in video_files:
            writer.writerow([video_file, -1])  
    print(f"CSV file created: {csv_file_path}")

def play_video(video_path):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"Failed to open video: {video_path}")
        return

    print("Press 'q' to end view.")
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        cv2.imshow(os.path.basename(video_path), frame)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

def label_videos(folder_path, csv_file_path):
    csv_path = os.path.join(csv_file_path, f"{os.path.basename(folder_path)}.csv")
    if not os.path.exists(csv_path):
        print(f"CSV file not found: {csv_path}, creating...")
        create_label_csv(folder_path, csv_file_path)

    data = load_csv(csv_path)
    total_videos = len(data)
    unlabeled_index = find_first_unlabeled(data)

    if unlabeled_index == -1:
        print("All videos are labeled.")
        return

    while unlabeled_index < total_videos:
        video_name, label = data[unlabeled_index]
        video_path = os.path.join(folder_path, video_name)

        print(f"Current video: {video_name}")
        print(f"Progress: {unlabeled_index + 1}/{total_videos} ({(unlabeled_index + 1) / total_videos * 100:.2f}%)")

        play_video(video_path)

        while True:
            label_input = input("Enter label (0, 1, 2), 'w' to exit, 'r' to replay: ")
            if label_input in ['0', '1', '2']:
                data[unlabeled_index][1] = label_input
                save_csv(csv_path, data)
                print(f"Label {label_input} saved for {video_name}.")
                break
            elif label_input == 'w':
                print("Exiting")
                return
            elif label_input == 'r':
                print(f"Replaying {video_name}")
                play_video(video_path)
            else:
                print("Invalid input. Please enter 0, 1, 2, 'w' or 'r'.")

        unlabeled_index = find_first_unlabeled(data)
        if unlabeled_index == -1:
            print("All videos are labeled.")
            break

if __name__ == "__main__":
    batch_folder = "./batch_0"
    csv_file_path = './'
    label_videos(batch_folder, csv_file_path)