zhang-yl's picture
Upload 4 files
c2ff18a verified
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)