File size: 9,967 Bytes
d26d563 | 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | import os
import json
import cv2
from typing import List, Optional, Sequence, Tuple
from collections import Counter
import multiprocessing
from tqdm import tqdm # 导入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:
# 检查文件扩展名是否为.mp4
if file.lower().endswith('.mp4'):
# 获取视频的绝对路径
video_paths.append(os.path.join(root, file))
return video_paths
def get_frame_count(file_path):
# 使用OpenCV读取视频并获取帧数
cap = cv2.VideoCapture(file_path)
if not cap.isOpened():
return 0
# 获取视频总帧数
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# fps = cap.get(cv2.CAP_PROP_FPS) # 帧率
# print(f"fps is {fps}")
cap.release()
return frame_count
def process_video(video_path):
# 处理每个视频,返回路径和帧数
frame_count = get_frame_count(video_path)
# if fps < 29 or fps > 31:
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
# return {"video_path": video_path, "frame_count": frame_count, "label_path": video_path.replace("/test_clips_tian_scenecut_resampled/", "/test_clips_tian_scenecut_face_labels_resampled/").replace(".mp4", ".mkv")}
def save_to_jsonl(results, output_file):
# 保存处理结果到JSONL文件
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):
# 使用Counter统计帧数分布
frame_count_distribution = Counter(frame_counts)
# fps_distribution = Counter(fps_counts)
print("帧数分布情况:")
for frame_count, count in sorted(frame_count_distribution.items()):
print(f"帧数: {frame_count} - 文件数: {count}")
# print("帧数分布情况:")
# for fps_count, count in sorted(fps_distribution.items()):
# print(f"帧数: {fps_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):
# 步骤1:获取所有mp4文件路径
video_paths = find_mp4_files(directory)
# 步骤2:使用多进程并行处理视频文件,并添加进度条
with multiprocessing.Pool() as pool:
# 使用tqdm结合multiprocessing.Pool.map,显示进度条
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]
# 步骤3:提取所有的帧数并打印帧数分布情况
frame_counts = [result['frame_count'] for result in filter_results]
# fps_counts = [round(result['fps']) for result in filter_results]
print_frame_distribution(frame_counts)
# 步骤4:保存结果到JSONL文件
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/MEAD' # 替换为目标目录路径
# # output_file = 'MEAD_f90_facealignment.jsonl' # 输出文件名
# output_file = 'MEAD_f90.jsonl' # 输出文件名
# data_type = "MEAD"
# 示例调用
directory = '/share/zhaohu_workspace/Downloaded_Data/hallo3_training_data/videos' # 替换为目标目录路径
output_file = 'hallo3_f90.jsonl' # 输出文件名
data_type = "hallo3"
# directory = '/share/zhaohu_workspace/Downloaded_Data/ted_clips/test_clips_tian_scenecut_resampled' # 替换为目标目录路径
# data_type = "TED"
# output_file = 'TED_f90_facealignment.jsonl' # 输出文件名
main(directory, output_file)
|