| import os
|
| import cv2
|
| from tqdm import tqdm
|
|
|
|
|
| INPUT_FOLDER = "bus"
|
| PREFIX = "08"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| ROOT_DIR = r"your_root_path"
|
| CLIPS_DIR = r"your_clips_path"
|
|
|
| SAMPLING_FPS = 2
|
| TRIM_HEAD_SEC = 180
|
| TRIM_TAIL_SEC = 180
|
|
|
|
|
|
|
| def sanitize_filename(name: str) -> str:
|
| """Remove illegal characters from file names."""
|
| return "".join(c for c in name if c.isalnum() or c in (" ", "-", "_")).strip()
|
|
|
|
|
| def process_videos(input_dir, clips_dir, prefix, folder_name):
|
| output_main_dir = os.path.join(clips_dir, f"{prefix}_{folder_name}")
|
| os.makedirs(output_main_dir, exist_ok=True)
|
|
|
| video_files = sorted([
|
| f for f in os.listdir(input_dir)
|
| if f.lower().endswith(('.mp4', '.mkv', '.avi', '.mov'))
|
| ])
|
|
|
| print(f"\nFound {len(video_files)} video files")
|
|
|
| video_index = 0
|
|
|
|
|
| start_from = None
|
|
|
| for filename in video_files:
|
| if start_from is not None:
|
| if filename != start_from:
|
| print(f"Skip: {filename}")
|
| video_index += 1
|
| continue
|
| else:
|
| print(f"Start from specified video: {filename}")
|
| start_from = None
|
|
|
| file_path = os.path.join(input_dir, filename)
|
| print(f"\nProcessing video: {file_path}")
|
|
|
| cap = cv2.VideoCapture(file_path)
|
| if not cap.isOpened():
|
| print("Failed to open video file")
|
| continue
|
|
|
| fps = cap.get(cv2.CAP_PROP_FPS)
|
| total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| duration = total_frames / fps
|
|
|
| print(f"Duration: {duration:.2f} seconds")
|
|
|
| if duration < TRIM_HEAD_SEC + TRIM_TAIL_SEC:
|
| print("Skip: video too short after trimming")
|
| cap.release()
|
| continue
|
|
|
| start_frame = int(TRIM_HEAD_SEC * fps)
|
| end_frame = int(total_frames - TRIM_TAIL_SEC * fps)
|
| extract_interval = max(1, int(fps / SAMPLING_FPS))
|
|
|
| video_name = os.path.splitext(filename)[0]
|
| safe_video_name = sanitize_filename(video_name)
|
| output_subdir = os.path.join(output_main_dir, f"{prefix}_{video_index:05d}")
|
| os.makedirs(output_subdir, exist_ok=True)
|
|
|
| cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
|
| frame_count = 0
|
| saved_count = 0
|
|
|
| for _ in tqdm(
|
| range(end_frame - start_frame),
|
| desc=f"Extracting {safe_video_name}",
|
| ncols=100
|
| ):
|
| ret, frame = cap.read()
|
| if not ret:
|
| break
|
|
|
| if frame_count % extract_interval == 0:
|
| output_file = os.path.join(
|
| output_subdir,
|
| f"{prefix}_{video_index:05d}_{saved_count:06d}.jpg"
|
| )
|
| cv2.imwrite(
|
| output_file,
|
| frame,
|
| [int(cv2.IMWRITE_JPEG_QUALITY), 90]
|
| )
|
| saved_count += 1
|
|
|
| frame_count += 1
|
|
|
| cap.release()
|
| print(f"Saved {saved_count} frames to {output_subdir}")
|
| video_index += 1
|
|
|
|
|
| def main():
|
| input_dir = os.path.join(ROOT_DIR, INPUT_FOLDER)
|
|
|
| if not os.path.isdir(input_dir):
|
| print(f"Invalid input directory: {input_dir}")
|
| return
|
|
|
| print(f"Start processing folder: {input_dir}")
|
| process_videos(input_dir, CLIPS_DIR, PREFIX, INPUT_FOLDER)
|
| print("\nAll videos processed.")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|