| import os |
| import json |
| import cv2 |
| from typing import List, Optional, Sequence, Tuple |
| from collections import Counter |
| import multiprocessing |
| from tqdm import tqdm |
| import numpy as np |
| import ffmpeg |
|
|
|
|
| def _read_labels_from_video(video_path: str) -> Optional[np.ndarray]: |
| """Read grayscale label video back as numpy array: (T, H, W), uint8.""" |
| try: |
| probe = ffmpeg.probe(video_path) |
| video_info = next(s for s in probe["streams"] if s["codec_type"] == "video") |
| width = int(video_info["width"]) |
| height = int(video_info["height"]) |
|
|
| out, _ = ( |
| ffmpeg.input(video_path) |
| .output("pipe:", format="rawvideo", pix_fmt="gray") |
| .run(capture_stdout=True, capture_stderr=True) |
| ) |
|
|
| decoded = np.frombuffer(out, np.uint8).reshape((-1, height, width)) |
| return decoded |
| except Exception as e: |
| print(f"Error reading label video {video_path}: {e}") |
| return None |
|
|
|
|
| def _compute_lip_bboxes( |
| labels: np.ndarray, |
| lip_scale: float = 1.0, |
| nose_labels: Sequence[int] = (2,), |
| face_labels: Sequence[int] = (1,), |
| ) -> List[Optional[Tuple[int, int, int, int]]]: |
| """Compute per-frame mouth-region bboxes using nose + face masks, with temporal interpolation.""" |
| if labels.ndim != 3: |
| raise ValueError("labels must have shape (T, H, W)") |
|
|
| T, H, W = labels.shape |
| lip_scale = max(float(lip_scale), 1.0) |
|
|
| raw_bboxes: List[Optional[Tuple[int, int, int, int]]] = [None] * T |
|
|
| for t in range(T): |
| frame_labels = labels[t] |
|
|
| nose_mask = np.isin(frame_labels, nose_labels) |
| face_mask = np.isin(frame_labels, face_labels) |
|
|
| if not np.any(nose_mask) or not np.any(face_mask): |
| continue |
|
|
| nose_ys, _ = np.where(nose_mask) |
| y_top = float(nose_ys.max()) |
|
|
| face_ys, face_xs = np.where(face_mask) |
| y_bottom = float(face_ys.max()) |
| x_left = float(face_xs.min()) |
| x_right = float(face_xs.max()) |
|
|
| if y_bottom <= y_top: |
| continue |
|
|
| x_min = x_left |
| x_max = x_right |
| y_min = y_top |
| y_max = y_bottom |
|
|
| w = x_max - x_min + 1.0 |
| h = y_max - y_min + 1.0 |
| cx = (x_min + x_max) / 2.0 |
| cy = (y_min + y_max) / 2.0 |
|
|
| new_w = w * lip_scale |
| new_h = h * lip_scale |
|
|
| x_min_s = int(round(cx - new_w / 2.0)) |
| x_max_s = int(round(cx + new_w / 2.0)) |
| y_min_s = int(round(cy - new_h / 2.0)) |
| y_max_s = int(round(cy + new_h / 2.0)) |
|
|
| x_min_s = max(0, min(x_min_s, W - 1)) |
| x_max_s = max(0, min(x_max_s, W - 1)) |
| y_min_s = max(0, min(y_min_s, H - 1)) |
| y_max_s = max(0, min(y_max_s, H - 1)) |
|
|
| if x_max_s <= x_min_s or y_max_s <= y_min_s: |
| continue |
|
|
| raw_bboxes[t] = (x_min_s, y_min_s, x_max_s, y_max_s) |
|
|
| if not any(bb is not None for bb in raw_bboxes): |
| return raw_bboxes |
|
|
| coords: List[List[Optional[int]]] = [[None] * T for _ in range(4)] |
| for t, bb in enumerate(raw_bboxes): |
| if bb is None: |
| continue |
| for d in range(4): |
| coords[d][t] = bb[d] |
|
|
| for d in range(4): |
| keyframes = [(t, coords[d][t]) for t in range(T) if coords[d][t] is not None] |
| if not keyframes: |
| continue |
|
|
| first_idx, first_val = keyframes[0] |
| for t in range(0, first_idx): |
| coords[d][t] = first_val |
|
|
| for (i, v0), (j, v1) in zip(keyframes, keyframes[1:]): |
| coords[d][i] = v0 |
| coords[d][j] = v1 |
| gap = j - i |
| if gap <= 1: |
| continue |
| for t in range(i + 1, j): |
| alpha = (t - i) / float(gap) |
| interp_val = int(round(v0 + (v1 - v0) * alpha)) |
| coords[d][t] = interp_val |
|
|
| last_idx, last_val = keyframes[-1] |
| for t in range(last_idx + 1, T): |
| coords[d][t] = last_val |
|
|
| final_bboxes: List[Optional[Tuple[int, int, int, int]]] = [None] * T |
| for t in range(T): |
| if all(coords[d][t] is not None for d in range(4)): |
| final_bboxes[t] = ( |
| int(coords[0][t]), |
| int(coords[1][t]), |
| int(coords[2][t]), |
| int(coords[3][t]), |
| ) |
|
|
| return final_bboxes |
|
|
|
|
| def _bbox_area(bb: Tuple[int, int, int, int]) -> int: |
| x_min, y_min, x_max, y_max = bb |
| return max(0, x_max - x_min + 1) * max(0, y_max - y_min + 1) |
|
|
|
|
| def _has_area_jump( |
| bboxes: List[Optional[Tuple[int, int, int, int]]], |
| area_ratio_thresh: float = 1.5, |
| ) -> bool: |
| if area_ratio_thresh <= 1.0: |
| return False |
|
|
| prev_area: Optional[int] = None |
| for bb in bboxes: |
| if bb is None: |
| continue |
| area = _bbox_area(bb) |
| if area <= 0: |
| continue |
| if prev_area is not None: |
| ratio = max(area / prev_area, prev_area / area) |
| if ratio >= area_ratio_thresh: |
| return True |
| prev_area = area |
| return False |
|
|
| def find_mp4_files(directory): |
| |
| video_paths = [] |
|
|
| |
| for root, dirs, files in os.walk(directory): |
| for file in files: |
| |
| if file.lower().endswith('.mp4'): |
| |
| video_paths.append(os.path.join(root, file)) |
| |
| return video_paths |
|
|
| def get_frame_count(file_path): |
| |
| cap = cv2.VideoCapture(file_path) |
|
|
| if not cap.isOpened(): |
| return 0 |
| |
| frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| |
|
|
| |
| cap.release() |
| return frame_count |
|
|
| def process_video(video_path): |
| |
| frame_count = get_frame_count(video_path) |
| |
| global data_type |
| label_path = None |
| if data_type == "hallo3": |
| label_path = video_path.replace("/videos/", "/face_parse_labels/").replace(".mp4", ".mp4.mkv") |
| elif data_type == "MEAD": |
| label_path = video_path.replace("/MEAD/", "/MEAD_face_labels/").replace(".mp4", ".mkv") |
| elif data_type == "TED": |
| label_path = video_path.replace("/test_clips_tian_scenecut_resampled/", "/test_clips_tian_scenecut_face_labels_resampled_face_alignment/").replace(".mp4", ".mkv") |
|
|
| if label_path and os.path.exists(label_path): |
| labels = _read_labels_from_video(label_path) |
| if labels is None: |
| return None |
| bboxes = _compute_lip_bboxes(labels) |
| if _has_area_jump(bboxes, area_ratio_thresh=1.5): |
| return None |
| return {"video_path": video_path, "frame_count": frame_count, "label_path": label_path} |
|
|
| return None |
| |
|
|
| def save_to_jsonl(results, output_file): |
| |
| with open(output_file, 'w', encoding='utf-8') as f: |
| for result in results: |
| f.write(json.dumps(result, ensure_ascii=False) + '\n') |
|
|
| def print_frame_distribution(frame_counts): |
| |
| frame_count_distribution = Counter(frame_counts) |
| |
| |
| print("帧数分布情况:") |
| for frame_count, count in sorted(frame_count_distribution.items()): |
| print(f"帧数: {frame_count} - 文件数: {count}") |
|
|
| |
| |
| |
|
|
| def format_count_suffix(count): |
| if count >= 1000: |
| suffix = f"{count / 1000:.1f}k" |
| return suffix.replace(".0k", "k") |
| return str(count) |
|
|
| def main(directory, output_file): |
| |
| video_paths = find_mp4_files(directory) |
|
|
| |
| with multiprocessing.Pool() as pool: |
| |
| results = list(tqdm(pool.imap(process_video, video_paths), total=len(video_paths), desc="处理视频")) |
|
|
| filter_results = [res for res in results if res is not None and res['frame_count'] > 90] |
|
|
| |
| frame_counts = [result['frame_count'] for result in filter_results] |
| |
| print_frame_distribution(frame_counts) |
|
|
| |
| count_suffix = format_count_suffix(len(filter_results)) |
| base, ext = os.path.splitext(output_file) |
| output_file_with_count = f"{base}_{count_suffix}{ext}" |
| save_to_jsonl(filter_results, output_file_with_count) |
|
|
| print(f"len results is {len(filter_results)}") |
| print(f"output file is {output_file_with_count}") |
|
|
| print("完成!所有的.mp4文件路径和帧数已经保存为 JSONL 格式。") |
|
|
| |
| |
| |
| |
| |
|
|
|
|
| |
| directory = '/share/zhaohu_workspace/Downloaded_Data/hallo3_training_data/videos' |
| output_file = 'hallo3_f90.jsonl' |
| data_type = "hallo3" |
|
|
|
|
| |
| |
| |
|
|
| main(directory, output_file) |
|
|