| import argparse |
| import subprocess |
| import os |
| import glob |
| from tqdm import tqdm |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| import threading |
|
|
| def extract_video_info_split(input_file): |
| filename = os.path.splitext(os.path.basename(input_file))[0] |
| parts = filename.split('_') |
| |
| start_frame = int(parts[-2]) |
| end_frame = int(parts[-1]) |
|
|
| |
| video_id = filename |
|
|
| return video_id, start_frame, end_frame |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| def check_segments_exist(video_id, start_frame, total_frames, output_dir, frames_per_segment): |
| """ |
| 检查该视频的所有片段是否已存在 |
| |
| Returns: |
| bool: True表示所有片段都存在,False表示有片段缺失 |
| list: 缺失的片段文件名列表 |
| """ |
| missing_segments = [] |
| current_frame = start_frame |
| |
| while current_frame < start_frame + total_frames: |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) |
| output_filename = f"{video_id}_{current_frame:07d}_{(segment_end_frame+1):07d}.mp4" |
| output_file = os.path.join(output_dir, output_filename) |
| |
| if not os.path.exists(output_file): |
| missing_segments.append(output_filename) |
| |
| current_frame = segment_end_frame + 1 |
| |
| return len(missing_segments) == 0, missing_segments |
|
|
| def process_single_video(input_file, output_dir, frames_per_segment=386, skip_existing=True): |
| try: |
| video_id, start_frame, original_end_frame = extract_video_info_split(input_file) |
| |
| |
| result = subprocess.run([ |
| 'ffprobe', '-v', 'quiet', '-select_streams', 'v:0', |
| '-show_entries', 'stream=r_frame_rate', '-of', 'csv=p=0', input_file |
| ], capture_output=True, text=True) |
| |
| frame_rate_str = result.stdout.strip() |
| if frame_rate_str and '/' in frame_rate_str: |
| frame_rate = eval(frame_rate_str) |
| else: |
| frame_rate = 30.0 |
| |
| |
| result = subprocess.run([ |
| 'ffprobe', '-v', 'quiet', '-select_streams', 'v:0', |
| '-show_entries', 'stream=nb_frames', '-of', 'csv=p=0', input_file |
| ], capture_output=True, text=True) |
| |
| total_frames = int(result.stdout.strip()) |
| |
| |
| if skip_existing: |
| all_exist, missing_segments = check_segments_exist( |
| video_id, start_frame, total_frames, output_dir, frames_per_segment |
| ) |
| |
| thread_id = threading.current_thread().name |
| |
| if all_exist: |
| |
| expected_segments = 0 |
| current_frame = start_frame |
| while current_frame < start_frame + total_frames: |
| expected_segments += 1 |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) |
| current_frame = segment_end_frame + 1 |
| |
| print(f"[{thread_id}] 跳过文件: {os.path.basename(input_file)} - 所有{expected_segments}个片段已存在") |
| return True, expected_segments, os.path.basename(input_file), True |
| else: |
| print(f"[{thread_id}] 处理文件: {os.path.basename(input_file)} - 缺失{len(missing_segments)}个片段") |
| |
| current_frame = start_frame |
| |
| |
| thread_id = threading.current_thread().name |
| if not skip_existing or not all_exist: |
| print(f"[{thread_id}] 原视频片段: 第{start_frame}帧 到 第{original_end_frame}帧") |
| print(f"[{thread_id}] 文件总帧数: {total_frames}") |
| |
| segment_index = 0 |
| processed_segments = 0 |
| |
| while current_frame < start_frame + total_frames: |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) |
| |
| output_filename = f"{video_id}_{current_frame:07d}_{(segment_end_frame + 1):07d}.mp4" |
| output_file = os.path.join(output_dir, output_filename) |
| |
| if skip_existing and os.path.exists(output_file): |
| print(f"[{thread_id}] 跳过片段: {output_filename} (已存在)") |
| pass |
| else: |
| start_time = (current_frame - start_frame) / frame_rate |
| |
| actual_frames = segment_end_frame - current_frame + 1 |
| duration = actual_frames / frame_rate |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| subprocess.run([ |
| 'ffmpeg', '-ss', str(start_time), '-i', input_file, |
| '-t', str(duration), |
| '-c', 'copy', |
| output_file, '-y' |
| ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| |
| print(f"[{thread_id}] 生成片段: {output_filename} ({actual_frames}帧)") |
| processed_segments += 1 |
| |
| current_frame = segment_end_frame + 1 |
| segment_index += 1 |
| |
| if not skip_existing or not all_exist: |
| if processed_segments > 0: |
| print(f"[{thread_id}] 完成: {os.path.basename(input_file)} - 新生成{processed_segments}个片段") |
| else: |
| print(f"[{thread_id}] 完成: {os.path.basename(input_file)} - 所有片段都已存在") |
| |
| return True, segment_index, os.path.basename(input_file), False |
| |
| except Exception as e: |
| thread_id = threading.current_thread().name |
| print(f"[{thread_id}] 处理文件 {input_file} 时出错: {str(e)}") |
| return False, 0, os.path.basename(input_file), False |
|
|
| def batch_process_videos(input_folder, output_dir, frames_per_segment=386, max_workers=4, |
| skip_existing=True, cur_part=None, total_part=None): |
| """ |
| 多线程批量处理视频 |
| |
| Args: |
| input_folder: 输入文件夹路径 |
| output_dir: 输出目录 |
| frames_per_segment: 每个片段的帧数 |
| max_workers: 最大线程数,建议设置为CPU核心数的1-2倍 |
| skip_existing: 是否跳过已存在的文件 |
| cur_part: 当前处理的部分 (1-based, 从1开始) |
| total_part: 总共分割的部分数 |
| """ |
| |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| video_files = glob.glob(os.path.join(input_folder, "*.mp4")) |
| |
| if not video_files: |
| print(f"在目录 {input_folder} 中未找到mp4文件") |
| return |
| |
| |
| video_files.sort() |
| |
| |
| if cur_part is not None and total_part is not None: |
| if not (1 <= cur_part <= total_part): |
| raise ValueError(f"cur_part ({cur_part}) 必须在 1 到 {total_part} 之间") |
| |
| total_videos = len(video_files) |
| videos_per_part = total_videos // total_part |
| remainder = total_videos % total_part |
| |
| |
| if cur_part <= remainder: |
| |
| start_idx = (cur_part - 1) * (videos_per_part + 1) |
| end_idx = start_idx + videos_per_part + 1 |
| else: |
| |
| start_idx = remainder * (videos_per_part + 1) + (cur_part - remainder - 1) * videos_per_part |
| end_idx = start_idx + videos_per_part |
| |
| video_files = video_files[start_idx:end_idx] |
| |
| print(f"分割处理模式: 第 {cur_part} 部分 / 共 {total_part} 部分") |
| print(f"原始视频总数: {total_videos}") |
| print(f"当前部分处理: {len(video_files)} 个视频 (索引 {start_idx} 到 {end_idx-1})") |
| |
| if not video_files: |
| print("当前部分没有需要处理的视频文件") |
| return |
| |
| print(f"找到 {len(video_files)} 个视频文件") |
| print(f"输出目录: {output_dir}") |
| print(f"使用 {max_workers} 个线程进行处理") |
| print(f"跳过已存在文件: {'是' if skip_existing else '否'}") |
| |
| total_segments = 0 |
| success_count = 0 |
| skipped_count = 0 |
| failed_files = [] |
| |
| |
| with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| |
| future_to_file = { |
| executor.submit(process_single_video, video_file, output_dir, frames_per_segment, skip_existing): video_file |
| for video_file in video_files |
| } |
| |
| |
| progress_desc = "处理进度" |
| if cur_part is not None and total_part is not None: |
| progress_desc = f"处理进度 ({cur_part}/{total_part})" |
| |
| with tqdm(total=len(video_files), desc=progress_desc) as pbar: |
| for future in as_completed(future_to_file): |
| video_file = future_to_file[future] |
| try: |
| success, segments, filename, was_skipped = future.result() |
| if success: |
| success_count += 1 |
| total_segments += segments |
| if was_skipped: |
| skipped_count += 1 |
| else: |
| failed_files.append(filename) |
| except Exception as exc: |
| print(f'视频文件 {video_file} 处理时发生异常: {exc}') |
| failed_files.append(os.path.basename(video_file)) |
| finally: |
| pbar.update(1) |
| |
| print(f"\n批量处理完成!") |
| if cur_part is not None and total_part is not None: |
| print(f"当前部分 ({cur_part}/{total_part}) 处理结果:") |
| print(f"成功处理: {success_count}/{len(video_files)} 个视频") |
| print(f"跳过文件: {skipped_count} 个视频 (所有片段已存在)") |
| print(f"实际处理: {success_count - skipped_count} 个视频") |
| print(f"总共生成: {total_segments} 个片段") |
| |
| if failed_files: |
| print(f"处理失败的文件: {failed_files}") |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='批量处理视频文件,提取帧并分段保存') |
| |
| parser.add_argument('--input_folder', type=str, default="./", help='输入文件夹路径') |
| parser.add_argument('--output_dir', type=str, default="./dummy_segments_33", help='输出目录路径') |
| parser.add_argument('--frames-per-segment', type=int, default=193, help='每段的帧数') |
| parser.add_argument('--max-workers', type=int, default=8, help='线程数') |
| parser.add_argument('--skip-existing', action='store_true', default=True, help='跳过已存在的文件') |
| parser.add_argument('--no-skip-existing', dest='skip_existing', action='store_false', help='强制重新处理') |
| parser.add_argument('--cur-part', type=int, default=1, help='当前处理的部分') |
| parser.add_argument('--total-part', type=int, default=1, help='总共分成几部分') |
| |
| args = parser.parse_args() |
| |
| batch_process_videos( |
| input_folder=args.input_folder, |
| output_dir=args.output_dir, |
| frames_per_segment=args.frames_per_segment, |
| max_workers=args.max_workers, |
| skip_existing=args.skip_existing, |
| cur_part=args.cur_part, |
| total_part=args.total_part |
| ) |
|
|
| if __name__ == "__main__": |
| main() |