FangSen9000 commited on
Commit ·
29c2c7a
1
Parent(s): dd36216
Add Python scripts and documentation
Browse filesFiles changed (13)
- README.mdAdded+170
- batch_merge_videos.pyAdded+228
- extract_gloss_mapping.pyAdded+230
- main.pyAdded+84
- merge_all_to_database.pyAdded+328
- preprocess_pipeline.pyAdded+279
- qa_system.pyAdded+583
- quick_vis_controlnext_style_dwpose_from_npz_or_input_img.pyAdded+43
- requirements.txtAdded+70
- step0_learn_quick_vis_controlnext_style_dwpose_from_npz_or_input_img.pyAdded+44
- step1_run_step1_from_csv.pyAdded+46
- step2_merge_npz.pyAdded+186
- step3_read_and_vis_merge_npz_to_pose_video.pyAdded+274
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# fast_dwpose
The goal of Easy DWPose is to provide a generic, reliable, and easy-to-use interface for making skeletons for ControlNet.
SF do some improve for [easy-dwpose](https://github.com/reallyigor/easy_dwpose), named it fast-dwpose.
## Installation
### PIP
```bashpip install easy-dwpose```
## Quickstart
### In you own .py scrip or in Jupyter
```pythonimport torchfrom PIL import Imageimport numpy as npimport json
from easy_dwpose import DWposeDetector
#####---------Setup init# You can use a different GPU, e.g. "cuda:1"device = "cuda:0" if torch.cuda.is_available() else "cpu"detector = DWposeDetector(device=device)input_image = Image.open("assets/pose.png").convert("RGB")
#####---------Get both the skeleton image# SF: skeleton should be a kind of img skeleton = detector(input_image, output_type="pil", include_hands=True, include_face=True)# Save the skeleton imageskeleton.save("skeleton.png")
#####---------Get pose data# SF: pose_data should be numpy/tensor# # This returns the dictionarypose_data = detector(input_image, draw_pose=False)
# Save the skeleton pose information:# Option 1: Save as NPY filenp.save('pose_data.npy', pose_data)
# Option 2: Save as NPZ filenp.savez('pose_data.npz', **pose_data)
# Option 3: Save as JSON file# Convert numpy arrays to lists for JSON serializationpose_data_json = {k: v.tolist() if isinstance(v, np.ndarray) else v for k, v in pose_data.items()}with open('pose_data.json', 'w') as f: json.dump(pose_data_json, f)```
<table align="center"> <tr> <th align="center">Input</th> <th align="center">Output</th> </tr> <tr> <td align="center"> <br /> <img src="./assets/pose.png"/> </td> <td align="center"> <br/> <img src="./assets/skeleton.png"/> </td> </tr></table>
### On a video
```bashpython scripts/inference_on_video.py --input assets/dance.mp4 --output_path result.mp4```
<table align="center"> <tr> <th align="center">Input</th> <th align="center">Output</th> </tr> <tr> <td align="center"> <br /> <img src="./assets/dance.gif"/> </td> <td align="center"> <br/> <img src="./assets/skeleton.gif"/> </td> </tr></table>
### On a folder of images
```bashpython scripts/inference_on_folder.py --input assets/ --output_path results/```
### Easy-DWPose Custom skeleton drawing
By default, we use standart skeleton drawing function but several projects change it (e.g. [MusePose](https://github.com/TMElyralab/MusePose)). Modify it or write your own from scratch!
```pythonfrom PIL import Imagefrom easy_dwpose import DWposeDetectorfrom easy_dwpose.draw.musepose import draw_pose as draw_pose_musepose
detector = DWposeDetector(device="cpu")input_image = Image.open("assets/pose.png").convert("RGB")
skeleton = detector(input_image, output_type="pil", draw_pose=draw_pose_musepose, draw_face=False)skeleton.save("skeleton.png")```
### SF Custom skeleton drawing
I prefer ControlNext style, I have developed a visualization method and placed it in `./easy_dwpose/draw/controlnext.py`. It does not integrate with easy dwpose and the calling method is slightly different:
```pythonimport torchfrom PIL import Imageimport numpy as npimport json
from easy_dwpose import DWposeDetectorfrom easy_dwpose.draw.controlnext import draw_pose, process_pose_data
#####---------Setup init# You can use a different GPU, e.g. "cuda:1"device = "cuda:0" if torch.cuda.is_available() else "cpu"detector = DWposeDetector(device=device)input_image = Image.open("assets/pose.png").convert("RGB")
#####---------Custom ControlNext drawing style# Get pose data for custom drawingpose_data = detector(input_image, draw_pose=False)
# Get image dimensionswidth, height = input_image.size
# Process the pose data for custom drawingprocessed_pred = process_pose_data(pose_data, height, width)
# Draw pose using custom ControlNext stylevis_img = draw_pose( pose=processed_pred, H=height, W=width, include_body=True, include_hand=True, include_face=True)
# Convert to PIL Image and save (vis_img is in CHW format)custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))custom_skeleton.save("skeleton_controlnext.png")```
## Acknowledgement
We thank the original authors of the [DWPose](https://github.com/IDEA-Research/DWPose) for their incredible models!
Thanks for open-sourcing!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228#!/usr/bin/env python3
"""
批量合并所有视频的npz文件
从 assets/WLASL_small_results/{video_id}/results_dwpose/npz/
合并到 output/single/{video_id}.npz
"""
import csv
import subprocess
import sys
import os
from pathlib import Path
import argparse
from tqdm import tqdm
def load_video_mapping(csv_path="output/gloss_video_mapping.csv"):
"""从CSV文件加载视频映射信息"""
video_mapping = {}
try:
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
video_id = row['video_id']
npz_path = row['npz_path']
video_mapping[video_id] = {
'npz_path': npz_path,
'gloss': row['gloss'],
'original_gloss': row['original_gloss']
}
print(f"✅ 成功加载视频映射: {len(video_mapping)} 个视频")
return video_mapping
except Exception as e:
print(f"❌ 加载视频映射失败: {e}")
return None
def check_npz_folder_exists(npz_path):
"""检查npz文件夹是否存在且包含npz文件"""
folder_path = Path(npz_path)
if not folder_path.exists():
return False, "文件夹不存在"
npz_files = list(folder_path.glob("*.npz"))
if not npz_files:
return False, "文件夹中没有npz文件"
return True, f"包含 {len(npz_files)} 个npz文件"
def merge_single_video(video_id, npz_folder_path, output_dir="output/single"):
"""合并单个视频的npz文件"""
try:
# 确保输出目录存在
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# 检查输出文件是否已存在
output_file = output_path / f"{video_id}.npz"
if output_file.exists():
return True, "文件已存在,跳过"
# 调用step2_merge_npz.py
cmd = [
sys.executable, "step2_merge_npz.py",
npz_folder_path,
"--output", output_dir
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
# 检查生成的文件并重命名(如果需要)
# step2_merge_npz.py 可能使用文件夹名作为输出文件名
generated_files = list(output_path.glob("*.npz"))
# 查找最新生成的文件
expected_name = Path(npz_folder_path).parts[-3] # 从路径中提取视频名
expected_file = output_path / f"{expected_name}.npz"
if expected_file.exists() and expected_file != output_file:
# 重命名为video_id.npz
expected_file.rename(output_file)
if output_file.exists():
return True, f"合并成功"
else:
return False, "合并后文件未找到"
else:
return False, f"合并失败: {result.stderr.strip()}"
except Exception as e:
return False, f"处理异常: {str(e)}"
def batch_merge_all_videos(video_mapping, output_dir="output/single"):
"""批量合并所有视频"""
print(f"🔄 开始批量合并 {len(video_mapping)} 个视频...")
success_count = 0
skip_count = 0
error_count = 0
error_videos = []
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
for video_id, info in tqdm(video_mapping.items(), desc="合并视频"):
npz_path = info['npz_path']
gloss = info['gloss']
# 检查npz文件夹
exists, status = check_npz_folder_exists(npz_path)
if not exists:
error_count += 1
error_videos.append((video_id, gloss, f"NPZ文件夹问题: {status}"))
continue
# 执行合并
success, message = merge_single_video(video_id, npz_path, output_dir)
if success:
if "跳过" in message:
skip_count += 1
else:
success_count += 1
else:
error_count += 1
error_videos.append((video_id, gloss, message))
# 输出统计结果
print(f"\n📊 批量合并完成:")
print(f" ✅ 成功合并: {success_count} 个")
print(f" ⏭️ 跳过已存在: {skip_count} 个")
print(f" ❌ 失败: {error_count} 个")
if error_videos:
print(f"\n❌ 失败的视频:")
for video_id, gloss, error_msg in error_videos[:10]: # 只显示前10个错误
print(f" {video_id} ({gloss}): {error_msg}")
if len(error_videos) > 10:
print(f" ... 还有 {len(error_videos) - 10} 个错误")
return success_count, skip_count, error_count, error_videos
def verify_merged_files(video_mapping, output_dir="output/single"):
"""验证合并后的文件"""
print(f"\n🔍 验证合并后的文件...")
total_expected = len(video_mapping)
existing_files = list(Path(output_dir).glob("*.npz"))
existing_count = len(existing_files)
print(f" 期望文件数: {total_expected}")
print(f" 实际文件数: {existing_count}")
if existing_count == total_expected:
print(f" ✅ 所有文件都已生成!")
else:
missing_count = total_expected - existing_count
print(f" ⚠️ 缺失 {missing_count} 个文件")
# 找出缺失的文件
existing_video_ids = {f.stem for f in existing_files}
expected_video_ids = set(video_mapping.keys())
missing_video_ids = expected_video_ids - existing_video_ids
if missing_video_ids and len(missing_video_ids) <= 10:
print(f" 缺失的video_id: {list(missing_video_ids)}")
def main():
parser = argparse.ArgumentParser(description='批量合并所有视频的npz文件')
parser.add_argument('--mapping', '-m', default='output/gloss_video_mapping.csv',
help='视频映射CSV文件路径 (默认: output/gloss_video_mapping.csv)')
parser.add_argument('--output', '-o', default='output/single',
help='输出目录 (默认: output/single)')
parser.add_argument('--verify', action='store_true',
help='验证合并后的文件')
args = parser.parse_args()
# 检查映射文件是否存在
if not Path(args.mapping).exists():
print(f"❌ 映射文件不存在: {args.mapping}")
print(" 请先运行 extract_gloss_mapping.py 生成映射文件")
return
# 检查step2_merge_npz.py是否存在
if not Path("step2_merge_npz.py").exists():
print(f"❌ 依赖文件不存在: step2_merge_npz.py")
return
# 加载视频映射
video_mapping = load_video_mapping(args.mapping)
if not video_mapping:
return
# 批量合并
success_count, skip_count, error_count, error_videos = batch_merge_all_videos(
video_mapping, args.output
)
# 验证结果
if args.verify or True: # 默认总是验证
verify_merged_files(video_mapping, args.output)
# 保存错误报告
if error_videos:
error_report_path = Path(args.output).parent / "merge_errors.txt"
with open(error_report_path, 'w', encoding='utf-8') as f:
f.write("合并失败的视频报告:\n")
f.write("=" * 50 + "\n")
for video_id, gloss, error_msg in error_videos:
f.write(f"{video_id} ({gloss}): {error_msg}\n")
print(f"\n📝 错误报告已保存: {error_report_path}")
print(f"\n🎉 批量合并任务完成!")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230#!/usr/bin/env python3
"""
从train.json提取gloss映射信息
生成 output/gloss_mapping.json 和 output/gloss_video_mapping.csv
"""
import json
import csv
from pathlib import Path
from collections import defaultdict
import argparse
def load_train_json(json_path):
"""加载train.json文件"""
try:
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"✅ 成功加载 {json_path}")
print(f"📊 包含 {len(data)} 个gloss条目")
return data
except Exception as e:
print(f"❌ 加载JSON文件失败: {e}")
return None
def extract_mapping_data(train_data, dataset_root):
"""从train.json提取映射数据"""
gloss_to_videos = defaultdict(list)
video_details = {}
print("🔄 正在提取映射数据...")
for entry in train_data:
gloss = entry['gloss'].upper() # 统一转为大写
for instance in entry['instances']:
video_id = instance['video_id']
# 添加到gloss映射
if video_id not in gloss_to_videos[gloss]:
gloss_to_videos[gloss].append(video_id)
# 保存视频详细信息
video_details[video_id] = {
'gloss': gloss,
'original_gloss': entry['gloss'], # 保留原始大小写
'signer_id': instance['signer_id'],
'fps': instance['fps'],
'frame_start': instance['frame_start'],
'frame_end': instance['frame_end'],
'bbox': instance['bbox'],
'source': instance['source'],
'split': instance['split'],
'url': instance['url'],
'variation_id': instance['variation_id'],
'instance_id': instance['instance_id'],
'npz_path': f"{dataset_root}/{video_id}/results_dwpose/npz"
}
# 转换为普通字典并处理单个视频的情况
gloss_mapping = {}
for gloss, videos in gloss_to_videos.items():
if len(videos) == 1:
gloss_mapping[gloss] = videos[0]
else:
gloss_mapping[gloss] = videos
print(f"✅ 提取完成:")
print(f" 📝 {len(gloss_mapping)} 个不同的gloss")
print(f" 🎬 {len(video_details)} 个视频实例")
return gloss_mapping, video_details
def save_gloss_mapping_json(gloss_mapping, output_path="output/gloss_mapping.json"):
"""保存gloss映射为JSON文件"""
try:
# 确保输出目录存在
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(gloss_mapping, f, indent=2, ensure_ascii=False)
print(f"✅ gloss映射已保存: {output_path}")
return True
except Exception as e:
print(f"❌ 保存JSON映射失败: {e}")
return False
def save_video_mapping_csv(video_details, output_path="output/gloss_video_mapping.csv"):
"""保存视频映射为CSV文件"""
try:
# 确保输出目录存在
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
fieldnames = [
'video_id', 'gloss', 'original_gloss', 'npz_path',
'signer_id', 'fps', 'frame_start', 'frame_end',
'bbox_x', 'bbox_y', 'bbox_w', 'bbox_h',
'source', 'split', 'url', 'variation_id', 'instance_id'
]
with open(output_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for video_id, details in video_details.items():
# 处理bbox
bbox = details['bbox']
row = {
'video_id': video_id,
'gloss': details['gloss'],
'original_gloss': details['original_gloss'],
'npz_path': details['npz_path'],
'signer_id': details['signer_id'],
'fps': details['fps'],
'frame_start': details['frame_start'],
'frame_end': details['frame_end'],
'bbox_x': bbox[0],
'bbox_y': bbox[1],
'bbox_w': bbox[2] - bbox[0],
'bbox_h': bbox[3] - bbox[1],
'source': details['source'],
'split': details['split'],
'url': details['url'],
'variation_id': details['variation_id'],
'instance_id': details['instance_id']
}
writer.writerow(row)
print(f"✅ 视频映射已保存: {output_path}")
return True
except Exception as e:
print(f"❌ 保存CSV文件失败: {e}")
return False
def generate_statistics(gloss_mapping, video_details):
"""生成统计信息"""
print("\n" + "=" * 50)
print("📊 数据统计")
print("=" * 50)
# Gloss统计
total_glosses = len(gloss_mapping)
single_video_glosses = sum(1 for v in gloss_mapping.values() if isinstance(v, str))
multi_video_glosses = total_glosses - single_video_glosses
print(f"📝 Gloss统计:")
print(f" 总gloss数: {total_glosses}")
print(f" 单视频gloss: {single_video_glosses}")
print(f" 多视频gloss: {multi_video_glosses}")
# 视频统计
total_videos = len(video_details)
sources = set(d['source'] for d in video_details.values())
splits = set(d['split'] for d in video_details.values())
signers = set(d['signer_id'] for d in video_details.values())
print(f"\n🎬 视频统计:")
print(f" 总视频数: {total_videos}")
print(f" 数据源: {', '.join(sources)}")
print(f" 数据集分割: {', '.join(splits)}")
print(f" 签名者数量: {len(signers)}")
# Top 10 最多视频的gloss
video_counts = []
for gloss, videos in gloss_mapping.items():
count = len(videos) if isinstance(videos, list) else 1
video_counts.append((gloss, count))
video_counts.sort(key=lambda x: x[1], reverse=True)
print(f"\n🏆 视频数量最多的10个gloss:")
for i, (gloss, count) in enumerate(video_counts[:10], 1):
print(f" {i:2d}. {gloss}: {count} 个视频")
print("=" * 50)
def main():
parser = argparse.ArgumentParser(description='从train.json提取gloss映射')
parser.add_argument('--dataset-root', '-d',
default='assets/WLASL_small_results',
help='数据集根目录路径 (默认: assets/WLASL_small_results)')
parser.add_argument('--input', '-i',
help='输入的JSON文件路径 (默认: {dataset_root}/train.json)')
args = parser.parse_args()
# 如果没有指定input,使用dataset_root + train.json
if not args.input:
args.input = f"{args.dataset_root}/train.json"
print(f"📁 数据集根目录: {args.dataset_root}")
print(f"📄 JSON文件路径: {args.input}")
# 检查输入文件
if not Path(args.input).exists():
print(f"❌ 输入文件不存在: {args.input}")
return
# 加载数据
train_data = load_train_json(args.input)
if not train_data:
return
# 提取映射数据
gloss_mapping, video_details = extract_mapping_data(train_data, args.dataset_root)
# 保存文件
print(f"\n💾 正在保存文件...")
success = True
success &= save_gloss_mapping_json(gloss_mapping)
success &= save_video_mapping_csv(video_details)
if success:
print(f"\n🎉 映射文件生成成功!")
print(f"📁 生成的文件:")
print(f" - output/gloss_mapping.json (QA系统使用)")
print(f" - output/gloss_video_mapping.csv (详细映射信息)")
# 生成统计信息
generate_statistics(gloss_mapping, video_details)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/usr/bin/env python3
import csv
import subprocess
import sys
import os
import argparse
from pathlib import Path
def read_mapping(gloss, csv_path):
result = []
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if row['gloss'].strip().lower() == gloss.strip().lower():
result.append((row['video_id'], row['npz_dir']))
return result
def run_merge_step1(npz_dir, output_dir="posedict"):
cmd = [sys.executable, "step1_merge_npz.py", npz_dir, "--output", output_dir]
ret = subprocess.run(cmd, capture_output=True, text=True)
return ret.returncode == 0
def run_merge_step2(npz_dir, output_dir="posedict"):
cmd = [sys.executable, "step2_merge_npz.py", npz_dir, "--output", output_dir]
ret = subprocess.run(cmd, capture_output=True, text=True)
return ret.returncode == 0
def run_render_step3(merged_npz_path, output_folder="pose_videos"):
cmd = [sys.executable, "step3_read_and_vis_merge_npz_to_pose_video.py", merged_npz_path, "--output", output_folder]
ret = subprocess.run(cmd, capture_output=True, text=True)
return ret.returncode == 0
def main():
parser = argparse.ArgumentParser(description="gloss → npz → merged.npz → pose video pipeline")
parser.add_argument("--gloss", required=True, help="输入 gloss 关键词")
parser.add_argument("--csv", default="assets/WLASL_small_results/gloss_npz_mapping.csv", help="gloss→video_id→npz 映射表")
parser.add_argument("--merge1_out", default="posedict", help="step1 输出合并目录")
parser.add_argument("--merge2_out", default="posedict", help="step2 输出 merged npz 目录")
parser.add_argument("--video_out", default="pose_videos", help="step3 输出视频目录")
args = parser.parse_args()
mapping = read_mapping(args.gloss, args.csv)
if not mapping:
print(f"❌ 没找到 gloss={args.gloss} 对应路径")
sys.exit(1)
os.makedirs(args.merge1_out, exist_ok=True)
os.makedirs(args.video_out, exist_ok=True)
for video_id, npz_path in mapping:
if not os.path.isdir(npz_path):
print(f"[跳过] npz目录不存在: {npz_path}")
continue
print(f"\n🔹 处理 video_id={video_id}")
# Step1
print("▶ step1 合并原始 npz")
if not run_merge_step1(npz_path, args.merge1_out):
print("❌ step1失败,跳过")
continue
# Step2
print("▶ step2 再次合并成大npz")
if not run_merge_step2(npz_path, args.merge2_out):
print("❌ step2失败,跳过")
continue
# Step3
merged_npz = Path(args.merge2_out) / f"{video_id}.npz"
if not merged_npz.exists():
print(f"❌ step2结果不存在: {merged_npz}")
continue
print("▶ step3 渲染视频")
if run_render_step3(str(merged_npz), args.video_out):
print(f"✅ 渲染完成: {args.video_out}/{video_id}_pose_video.mp4")
else:
print("❌ 渲染失败")
print("\n🎉 所有流程完成")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328#!/usr/bin/env python3
"""
将所有单个视频的npz文件合并成一个大数据库
从 output/single/*.npz 合并到 output/merge/merged_database.npz
"""
import numpy as np
from pathlib import Path
import argparse
from tqdm import tqdm
import json
def load_single_npz(npz_path):
"""加载一个单独的视频npz文件"""
try:
data = np.load(npz_path, allow_pickle=True)
# 检查是否有metadata
if '_metadata' not in data:
print(f"⚠️ {npz_path.name}: 没有找到metadata")
return None, None
metadata = data['_metadata'].item()
frame_dict = {}
# 重构帧数据
keys = metadata['original_keys']
frame_keys = metadata['frame_keys']
for frame_key in frame_keys:
frame_data = {}
for k in keys:
combined_key = f"{frame_key}_{k}"
if combined_key in data:
frame_data[k] = data[combined_key]
frame_dict[frame_key] = frame_data
return frame_dict, keys
except Exception as e:
print(f"❌ 加载失败 {npz_path.name}: {e}")
return None, None
def merge_all_videos_to_database(single_dir="output/single", output_file="output/merge/merged_database.npz"):
"""将所有单个视频npz合并成大数据库"""
single_path = Path(single_dir)
output_path = Path(output_file)
# 检查输入目录
if not single_path.exists():
print(f"❌ 输入目录不存在: {single_dir}")
return False
# 获取所有npz文件
npz_files = list(single_path.glob("*.npz"))
if not npz_files:
print(f"❌ 在 {single_dir} 中没有找到npz文件")
return False
print(f"📁 找到 {len(npz_files)} 个视频npz文件")
# 创建输出目录
output_path.parent.mkdir(parents=True, exist_ok=True)
# 合并数据
merged_data = {}
metadata = {
"video_index": {},
"original_keys": [],
"total_frames": 0,
"video_count": 0
}
frame_counter = 0
successful_videos = 0
failed_videos = []
print("🔄 开始合并视频数据...")
for npz_file in tqdm(sorted(npz_files), desc="合并视频"):
video_id = npz_file.stem # 文件名即为video_id
# 加载单个视频数据
frame_dict, keys = load_single_npz(npz_file)
if frame_dict is None:
failed_videos.append(video_id)
continue
# 设置original_keys(第一次)
if not metadata["original_keys"]:
metadata["original_keys"] = keys
# 记录该视频的起始帧
start_frame = frame_counter
# 将帧数据添加到合并数据中
for local_idx, (frame_key, frame_data) in enumerate(frame_dict.items()):
new_key = f"frame_{frame_counter:08d}"
# 添加所有帧数据
for k in keys:
if k in frame_data:
merged_data[f"{new_key}_{k}"] = frame_data[k]
frame_counter += 1
end_frame = frame_counter - 1
# 记录视频索引信息
metadata["video_index"][video_id] = {
"start_frame": start_frame,
"end_frame": end_frame,
"frame_count": end_frame - start_frame + 1
}
successful_videos += 1
# 完善metadata
metadata["total_frames"] = frame_counter
metadata["video_count"] = successful_videos
merged_data["_metadata"] = metadata
# 保存合并后的数据库
try:
np.savez_compressed(output_path, **merged_data)
print(f"\n✅ 数据库合并完成!")
print(f" 📊 成功合并: {successful_videos} 个视频")
print(f" 🎞️ 总帧数: {frame_counter}")
print(f" 💾 输出文件: {output_path}")
print(f" 📦 文件大小: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
if failed_videos:
print(f" ⚠️ 失败视频: {len(failed_videos)} 个")
if len(failed_videos) <= 10:
print(f" 失败列表: {failed_videos}")
return True
except Exception as e:
print(f"❌ 保存数据库失败: {e}")
return False
def verify_database(database_path="output/merge/merged_database.npz",
mapping_path="output/gloss_mapping.json"):
"""验证数据库完整性"""
print(f"\n🔍 验证数据库完整性...")
try:
# 加载数据库
data = np.load(database_path, allow_pickle=True)
metadata = data['_metadata'].item()
print(f"✅ 数据库基本信息:")
print(f" 总视频数: {metadata['video_count']}")
print(f" 总帧数: {metadata['total_frames']}")
print(f" 数据维度: {len(metadata['original_keys'])} 个原始key")
# 验证帧数据完整性
print(f"\n🔍 验证帧数据完整性...")
original_keys = metadata['original_keys']
missing_frames = 0
for frame_idx in range(min(100, metadata['total_frames'])): # 检查前100帧
frame_key = f"frame_{frame_idx:08d}"
frame_complete = True
for key in original_keys:
combined_key = f"{frame_key}_{key}"
if combined_key not in data:
frame_complete = False
break
if not frame_complete:
missing_frames += 1
if missing_frames == 0:
print(f" ✅ 前100帧数据完整")
else:
print(f" ⚠️ 前100帧中有 {missing_frames} 帧数据不完整")
# 验证视频索引
print(f"\n🔍 验证视频索引...")
video_index = metadata['video_index']
total_indexed_frames = sum(
info['frame_count'] for info in video_index.values()
)
if total_indexed_frames == metadata['total_frames']:
print(f" ✅ 视频索引帧数一致: {total_indexed_frames}")
else:
print(f" ⚠️ 视频索引帧数不一致: 索引={total_indexed_frames}, 实际={metadata['total_frames']}")
# 与映射文件对比
if Path(mapping_path).exists():
try:
with open(mapping_path, 'r', encoding='utf-8') as f:
gloss_mapping = json.load(f)
# 收集映射中的所有video_id
mapping_video_ids = set()
for videos in gloss_mapping.values():
if isinstance(videos, list):
mapping_video_ids.update(videos)
else:
mapping_video_ids.add(videos)
db_video_ids = set(video_index.keys())
matched = mapping_video_ids & db_video_ids
missing_in_db = mapping_video_ids - db_video_ids
extra_in_db = db_video_ids - mapping_video_ids
print(f"\n🔍 与映射文件对比:")
print(f" 映射中视频数: {len(mapping_video_ids)}")
print(f" 数据库中视频数: {len(db_video_ids)}")
print(f" 匹配视频数: {len(matched)}")
if missing_in_db:
print(f" ⚠️ 映射中有但数据库缺失: {len(missing_in_db)} 个")
if len(missing_in_db) <= 5:
print(f" {list(missing_in_db)}")
if extra_in_db:
print(f" ℹ️ 数据库中有但映射缺失: {len(extra_in_db)} 个")
if len(extra_in_db) <= 5:
print(f" {list(extra_in_db)}")
if len(matched) == len(mapping_video_ids) == len(db_video_ids):
print(f" ✅ 映射与数据库完全一致!")
except Exception as e:
print(f" ⚠️ 映射文件验证失败: {e}")
print(f"\n✅ 数据库验证完成!")
return True
except Exception as e:
print(f"❌ 数据库验证失败: {e}")
return False
def generate_database_summary(database_path="output/merge/merged_database.npz",
output_path="output/database_summary.txt"):
"""生成数据库摘要报告"""
try:
data = np.load(database_path, allow_pickle=True)
metadata = data['_metadata'].item()
with open(output_path, 'w', encoding='utf-8') as f:
f.write("手语数据库摘要报告\n")
f.write("=" * 50 + "\n\n")
f.write(f"数据库文件: {database_path}\n")
f.write(f"生成时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("基本统计:\n")
f.write(f" 总视频数: {metadata['video_count']}\n")
f.write(f" 总帧数: {metadata['total_frames']}\n")
f.write(f" 平均每视频帧数: {metadata['total_frames'] / metadata['video_count']:.1f}\n")
f.write(f" 数据维度: {len(metadata['original_keys'])} 个key\n\n")
f.write("数据key类型:\n")
for key in metadata['original_keys']:
f.write(f" - {key}\n")
f.write("\n")
f.write("视频索引 (前20个):\n")
for i, (video_id, info) in enumerate(list(metadata['video_index'].items())[:20]):
f.write(f" {video_id}: 帧 {info['start_frame']}-{info['end_frame']} ({info['frame_count']} 帧)\n")
if len(metadata['video_index']) > 20:
f.write(f" ... 还有 {len(metadata['video_index']) - 20} 个���频\n")
print(f"📝 数据库摘要已保存: {output_path}")
return True
except Exception as e:
print(f"❌ 生成摘要失败: {e}")
return False
def main():
parser = argparse.ArgumentParser(description='将所有视频npz合并成大数据库')
parser.add_argument('--input', '-i', default='output/single',
help='输入目录 (默认: output/single)')
parser.add_argument('--output', '-o', default='output/merge/merged_database.npz',
help='输出数据库文件 (默认: output/merge/merged_database.npz)')
parser.add_argument('--verify', action='store_true',
help='验证生成的数据库')
parser.add_argument('--summary', action='store_true',
help='生成数据库摘要报告')
args = parser.parse_args()
# 检查输入目录
if not Path(args.input).exists():
print(f"❌ 输入目录不存在: {args.input}")
print(" 请先运行 batch_merge_videos.py 生成单个视频npz文件")
return
# 执行合并
success = merge_all_videos_to_database(args.input, args.output)
if not success:
print("❌ 数据库合并失败!")
return
# 验证数据库
if args.verify or True: # 默认总是验证
verify_database(args.output)
# 生成摘要报告
if args.summary or True: # 默认总是生成摘要
summary_path = Path(args.output).parent / "database_summary.txt"
generate_database_summary(args.output, summary_path)
print(f"\n🎉 数据库生成任务完成!")
print(f"📁 数据库文件: {args.output}")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279#!/usr/bin/env python3
"""
手语数据预处理主控脚本 - 支持数据集路径参数
自动化执行完整的数据预处理流程
"""
import subprocess
import sys
import os
from pathlib import Path
import argparse
import time
def run_command(cmd, description):
"""执行命令并显示进度"""
print(f"\n{'=' * 60}")
print(f"🔄 {description}")
print(f"{'=' * 60}")
print(f"命令: {' '.join(cmd)}")
start_time = time.time()
try:
result = subprocess.run(cmd, check=True, text=True, capture_output=False)
elapsed = time.time() - start_time
print(f"\n✅ {description} 完成! (耗时: {elapsed:.1f}秒)")
return True
except subprocess.CalledProcessError as e:
elapsed = time.time() - start_time
print(f"\n❌ {description} 失败! (耗时: {elapsed:.1f}秒)")
print(f"错误码: {e.returncode}")
return False
except Exception as e:
elapsed = time.time() - start_time
print(f"\n❌ {description} 异常! (耗时: {elapsed:.1f}秒)")
print(f"异常信息: {e}")
return False
def check_prerequisites(dataset_root):
"""检查前置条件"""
print("🔍 检查前置条件...")
required_files = [
"step2_merge_npz.py",
"extract_gloss_mapping.py",
"batch_merge_videos.py",
"merge_all_to_database.py",
"qa_system.py"
]
missing_files = []
for file_path in required_files:
if not Path(file_path).exists():
missing_files.append(file_path)
if missing_files:
print("❌ 缺少必要文件:")
for file_path in missing_files:
print(f" - {file_path}")
return False
# 检查数据集根目录
dataset_path = Path(dataset_root)
if not dataset_path.exists():
print(f"❌ 数据集根目录不存在: {dataset_root}")
return False
# 检查train.json是否存在
train_json_path = dataset_path / "train.json"
if not train_json_path.exists():
print(f"❌ train.json 文件不存在: {train_json_path}")
return False
try:
import json
with open(train_json_path, 'r') as f:
data = json.load(f)
if not data:
print("❌ train.json 文件为空")
return False
print(f"✅ train.json 包含 {len(data)} 个条目")
# 检查是否有视频目录
video_dirs = [d for d in dataset_path.iterdir() if d.is_dir() and d.name != '__pycache__']
print(f"✅ 数据集目录包含 {len(video_dirs)} 个视频目录")
except Exception as e:
print(f"❌ train.json 文件格式错误: {e}")
return False
print("✅ 所有前置条件满足")
return True
def check_directory_structure():
"""检查并创建目录结构"""
print("\n📁 检查目录结构...")
required_dirs = [
"output",
"output/single",
"output/merge",
"output/video"
]
for dir_path in required_dirs:
Path(dir_path).mkdir(parents=True, exist_ok=True)
print(f"✅ {dir_path}")
return True
def step1_extract_mapping(dataset_root):
"""步骤1: 提取gloss映射"""
cmd = [sys.executable, "extract_gloss_mapping.py", "--dataset-root", dataset_root]
return run_command(cmd, "步骤1: 提取Gloss映射")
def step2_batch_merge():
"""步骤2: 批量合并视频npz"""
cmd = [sys.executable, "batch_merge_videos.py", "--verify"]
return run_command(cmd, "步骤2: 批量合并视频NPZ文件")
def step3_merge_database():
"""步骤3: 合并成大数据库"""
cmd = [sys.executable, "merge_all_to_database.py", "--verify", "--summary"]
return run_command(cmd, "步骤3: 合并成大数据库")
def verify_final_output():
"""验证最终输出"""
print(f"\n🔍 验证最终输出...")
required_outputs = [
"output/gloss_mapping.json",
"output/gloss_video_mapping.csv",
"output/merge/merged_database.npz"
]
all_exist = True
for output_path in required_outputs:
if Path(output_path).exists():
size = Path(output_path).stat().st_size / 1024 / 1024
print(f"✅ {output_path} ({size:.2f} MB)")
else:
print(f"❌ {output_path} 不存在")
all_exist = False
# 检查single目录中的文件数量
single_dir = Path("output/single")
if single_dir.exists():
npz_files = list(single_dir.glob("*.npz"))
print(f"✅ output/single/ 包含 {len(npz_files)} 个视频NPZ文件")
else:
print(f"❌ output/single/ 目录不存在")
all_exist = False
return all_exist
def show_completion_summary(dataset_root):
"""显���完成摘要"""
print(f"\n{'=' * 60}")
print(f"🎉 数据预处理完成!")
print(f"{'=' * 60}")
print(f"📁 输入数据集: {dataset_root}")
print(f"📁 生成的文件:")
print(f" 📊 映射文件:")
print(f" - output/gloss_mapping.json")
print(f" - output/gloss_video_mapping.csv")
print(f" 🎬 视频NPZ文件:")
print(f" - output/single/*.npz (单个视频)")
print(f" - output/merge/merged_database.npz (合并数据库)")
print(f" 📝 报告文件:")
print(f" - output/database_summary.txt")
print(f"\n🚀 下一步:")
print(f" 运行QA系统: python qa_system.py")
print(f" 或命令行模式: python qa_system.py --gloss \"HELLO WORLD\"")
print(f"\n💡 提示:")
print(f" - QA系统会自动加载生成的数据库和映射文件")
print(f" - 生成的视频将保存在 output/video/ 目录")
def main():
parser = argparse.ArgumentParser(description='手语数据预处理主控脚本')
parser.add_argument('--dataset-root', '-d',
default='assets/WLASL_small_results',
help='数据集根目录路径 (默认: assets/WLASL_small_results)')
parser.add_argument('--skip-step1', action='store_true',
help='跳过步骤1 (提取映射)')
parser.add_argument('--skip-step2', action='store_true',
help='跳过步骤2 (批量合并)')
parser.add_argument('--skip-step3', action='store_true',
help='跳过步骤3 (合并数据库)')
parser.add_argument('--only-verify', action='store_true',
help='仅验证输出文件')
args = parser.parse_args()
print("🤖 手语数据预处理管道")
print("=" * 60)
print(f"📁 数据集路径: {args.dataset_root}")
# 仅验证模式
if args.only_verify:
if verify_final_output():
print("\n✅ 所有输出文件都存在且正确!")
show_completion_summary(args.dataset_root)
else:
print("\n❌ 输出文件验证失败!")
return
# 检查前置条件
if not check_prerequisites(args.dataset_root):
print("\n❌ 前置条件检查失败,请检查数据集路径和必要文件!")
sys.exit(1)
# 检查并创建目录结构
if not check_directory_structure():
print("\n❌ 目录结构创建失败!")
sys.exit(1)
total_start_time = time.time()
failed_steps = []
# 执行预处理步骤
if not args.skip_step1:
if not step1_extract_mapping(args.dataset_root):
failed_steps.append("步骤1: 提取映射")
else:
print("\n⏭️ 跳过步骤1: 提取映射")
if not args.skip_step2 and "步骤1: 提取映射" not in failed_steps:
if not step2_batch_merge():
failed_steps.append("步骤2: 批量合并")
else:
if args.skip_step2:
print("\n⏭️ 跳过步骤2: 批量合并")
if not args.skip_step3 and "步骤2: 批量合并" not in failed_steps:
if not step3_merge_database():
failed_steps.append("步骤3: 合并数据库")
else:
if args.skip_step3:
print("\n⏭️ 跳过步骤3: 合并数据库")
total_elapsed = time.time() - total_start_time
# 最终验证
if not failed_steps:
print(f"\n🔍 最终验证...")
if verify_final_output():
print(f"\n🎉 所有步骤执行成功! (总耗时: {total_elapsed / 60:.1f}分钟)")
show_completion_summary(args.dataset_root)
else:
print(f"\n⚠️ 步骤执行完成但输出验证失败!")
else:
print(f"\n❌ 以下步骤执行失败:")
for step in failed_steps:
print(f" - {step}")
print(f"\n总耗时: {total_elapsed / 60:.1f}分钟")
print(f"\n💡 故障排除建议:")
print(f" 1. 检查错误信息并修复问题")
print(f" 2. 使用 --skip-stepX 跳过已完成的步骤")
print(f" 3. 使用 --only-verify 验证现有输出")
print(f" 4. 检查数据集路径: {args.dataset_root}")
sys.exit(1)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583#!/usr/bin/env python3
"""
手语Gloss问答系统
用户输入gloss,系统生成对应的pose视频
"""
import torch
from PIL import Image
import numpy as np
import json
import os
import sys
import argparse
from pathlib import Path
import cv2
from tqdm import tqdm
import re
from easy_dwpose import DWposeDetector
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
# 固定配置
DATABASE_PATH = "output/merge/merged_database.npz" # 数据库文件路径
MAPPING_FILE = "output/gloss_mapping.json" # 映射文件路径
OUTPUT_DIR = "output/video" # 输出视频目录
class SignLanguageQA:
def __init__(self):
self.data = None
self.metadata = None
self.gloss_mapping = None
self.load_database()
self.load_mapping()
def load_database(self):
"""加载数据库"""
try:
if not Path(DATABASE_PATH).exists():
print(f"❌ 数据库文件不存在: {DATABASE_PATH}")
print(" 请确保已运行 merge_all_to_database.py 生成数据库文件")
sys.exit(1)
print(f"📚 正在加载数据库: {DATABASE_PATH}")
self.data = np.load(DATABASE_PATH, allow_pickle=True)
self.metadata = self.data['_metadata'].item()
print(f"✅ 数据库加载成功!")
print(f" 📊 总帧数: {self.metadata['total_frames']}")
print(f" 🎬 视频数量: {self.metadata['video_count']}")
except Exception as e:
print(f"❌ 数据库加载失败: {e}")
sys.exit(1)
def load_mapping(self):
"""加载gloss映射文件"""
if Path(MAPPING_FILE).exists():
try:
with open(MAPPING_FILE, 'r', encoding='utf-8') as f:
self.gloss_mapping = json.load(f)
print(f"✅ 映射文件加载成功: {MAPPING_FILE}")
print(f" 📝 包含 {len(self.gloss_mapping)} 个gloss映射")
except Exception as e:
print(f"⚠️ 映射文件加载失败: {e}")
self.gloss_mapping = None
else:
print(f"ℹ️ 映射文件不存在: {MAPPING_FILE}")
print(" 将使用智能匹配模式")
self.gloss_mapping = None
def find_gloss_videos(self, gloss):
"""根据单个gloss找到对应的video_ids"""
if self.gloss_mapping and gloss.upper() in self.gloss_mapping:
# 使用映射文件
video_ids = self.gloss_mapping[gloss.upper()]
if not isinstance(video_ids, list):
video_ids = [video_ids]
return video_ids
else:
# 智能匹配模式
gloss_upper = gloss.upper()
matched_videos = []
for video_id in self.metadata['video_index'].keys():
# 多种匹配策略
if (gloss_upper == video_id.upper() or
gloss_upper in video_id.upper() or
video_id.upper().endswith(f"_{gloss_upper}") or
video_id.upper().startswith(f"{gloss_upper}_") or
f"_{gloss_upper}_" in video_id.upper()):
matched_videos.append(video_id)
return matched_videos
def get_frames_for_glosses(self, gloss_list, one_video_per_gloss=True):
"""获取gloss列表对应的所有帧
Args:
gloss_list: gloss列表
one_video_per_gloss: 是否每个gloss只选择一个视频
"""
all_frame_groups = [] # 按gloss分组的帧
video_info = []
for gloss in gloss_list:
matched_videos = self.find_gloss_videos(gloss)
if matched_videos:
print(f"🎯 '{gloss}' -> 找到 {len(matched_videos)} 个视频")
# 如果只选择一个视频,找第一个有效的(在数据库中存在的)
videos_to_use = []
if one_video_per_gloss:
# 找到第一个在数据库中存在的视频
for video_id in matched_videos:
if video_id in self.metadata['video_index']:
videos_to_use = [video_id]
if len(matched_videos) > 1:
print(f" 💡 选择第一个有效视频: {video_id},跳过其他 {len(matched_videos) - 1} 个")
break
if not videos_to_use:
print(f" ❌ 没有找到有效的视频(所有video_id都不在数据库中)")
continue
else:
videos_to_use = matched_videos
gloss_frames = [] # 当前gloss的所有帧
for video_id in videos_to_use:
if video_id in self.metadata['video_index']:
start_frame = self.metadata['video_index'][video_id]['start_frame']
end_frame = self.metadata['video_index'][video_id]['end_frame']
frames = list(range(start_frame, end_frame + 1))
gloss_frames.extend(frames)
video_info.append({
'gloss': gloss,
'video_id': video_id,
'start_frame': start_frame,
'end_frame': end_frame,
'frame_count': len(frames)
})
print(f" 📹 {video_id}: {len(frames)} 帧 ({start_frame}-{end_frame})")
else:
print(f" ⚠️ {video_id}: 在数据库中未找到")
if gloss_frames:
all_frame_groups.append(gloss_frames)
else:
print(f"❌ '{gloss}' -> 未找到匹配视频")
self.suggest_similar_glosses(gloss)
# 按顺序拼接所有gloss的帧
all_frames = []
for frame_group in all_frame_groups:
all_frames.extend(frame_group)
return all_frames, video_info
def suggest_similar_glosses(self, gloss):
"""为未找到的gloss提供相似建议"""
gloss_upper = gloss.upper()
similar_videos = []
# 查找包含部分字符的video_id
for video_id in self.metadata['video_index'].keys():
score = 0
for char in gloss_upper:
if char in video_id.upper():
score += 1
if score >= len(gloss_upper) * 0.5: # 至少50%字符匹配
similar_videos.append(video_id)
if similar_videos:
print(f" 💡 相似的video_id: {similar_videos[:5]}")
# 如果有映射文件,显示可用的gloss
if self.gloss_mapping:
available_glosses = list(self.gloss_mapping.keys())
similar_glosses = [g for g in available_glosses if
any(char in g for char in gloss_upper)]
if similar_glosses:
print(f" 💡 相似的gloss: {similar_glosses[:5]}")
def create_pose_frame(self, frame_data, width=480, height=480):
"""创建单帧pose图像"""
try:
processed_pred = process_pose_data(frame_data, height, width)
vis_img = draw_pose(
pose=processed_pred,
H=height,
W=width,
include_body=True,
include_hand=True,
include_face=True
)
return vis_img.transpose(1, 2, 0)
except Exception as e:
print(f"⚠️ 创建pose帧失败: {e}")
return None
def generate_video(self, frame_indices, output_path, video_info, fps=30, width=480, height=480,
smoothing_frames=5, smoothing_method='none'):
"""生成pose视频
Args:
frame_indices: 帧索引列表
output_path: 输出路径
video_info: 视频信息列表
fps: 帧率
width: 宽度
height: 高度
smoothing_frames: 平滑过渡帧数
smoothing_method: 平滑方法 ('fade', 'blend', 'pause', 'none')
"""
if not frame_indices:
return False
# 创建输出目录
output_path.parent.mkdir(parents=True, exist_ok=True)
# 设置视频编码器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
if not video_writer.isOpened():
print("❌ 无法创建视频文件")
return False
original_keys = self.metadata['original_keys']
successful_frames = 0
print(f"🎬 正在生成视频 (平滑方式: {smoothing_method})...")
# 按gloss分组生成pose帧
all_pose_frame_groups = []
print("🔄 渲染pose帧...")
current_frame_idx = 0
for info in video_info:
gloss_frames = []
frame_count = info['frame_count']
for _ in range(frame_count):
if current_frame_idx < len(frame_indices):
frame_idx = frame_indices[current_frame_idx]
frame_key = f"frame_{frame_idx:08d}"
frame_data = {}
for key in original_keys:
combined_key = f"{frame_key}_{key}"
if combined_key in self.data:
frame_data[key] = self.data[combined_key]
if frame_data:
pose_frame = self.create_pose_frame(frame_data, width, height)
if pose_frame is not None:
gloss_frames.append(pose_frame)
current_frame_idx += 1
if gloss_frames:
all_pose_frame_groups.append(gloss_frames)
print(f" ✅ {info['gloss']}: {len(gloss_frames)} 帧")
if not all_pose_frame_groups:
print("❌ 没有成功生成任何帧")
video_writer.release()
return False
# 应用平滑处理
if smoothing_method != 'none' and len(all_pose_frame_groups) > 1:
final_frames = self.apply_group_smoothing(all_pose_frame_groups, smoothing_frames, smoothing_method)
else:
# 直接拼接所有帧
final_frames = []
for group in all_pose_frame_groups:
final_frames.extend(group)
# 写入视频
print("💾 写入视频文件...")
for pose_frame in tqdm(final_frames, desc="写入帧"):
pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
video_writer.write(pose_frame_bgr)
successful_frames += 1
video_writer.release()
if successful_frames > 0:
print(f"✅ 视频生成成功!")
print(f" 📁 文件: {output_path}")
print(f" 📊 {successful_frames} 帧, {fps}fps, {width}x{height}")
if output_path.exists():
print(f" 💾 大小: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
return True
else:
print(f"❌ 视频生成失败")
return False
def apply_group_smoothing(self, frame_groups, smoothing_frames, method):
"""对gloss分组应用平滑过渡效果"""
if len(frame_groups) <= 1 or smoothing_frames <= 0:
final_frames = []
for group in frame_groups:
final_frames.extend(group)
return final_frames
print(f"🌊 应用 {method} 平滑过渡 ({smoothing_frames} 帧)...")
if method == 'fade':
return self.apply_group_fade_smoothing(frame_groups, smoothing_frames)
elif method == 'blend':
return self.apply_group_blend_smoothing(frame_groups, smoothing_frames)
elif method == 'pause':
return self.apply_group_pause_smoothing(frame_groups, smoothing_frames)
else:
final_frames = []
for group in frame_groups:
final_frames.extend(group)
return final_frames
def apply_group_fade_smoothing(self, frame_groups, fade_frames):
"""对gloss分组应用淡入淡出平滑"""
smoothed_frames = []
for i, group in enumerate(frame_groups):
if i == 0:
# 第一组:淡入
for f in range(fade_frames):
alpha = f / fade_frames
black_frame = np.zeros_like(group[0])
faded_frame = (black_frame * (1 - alpha) + group[0] * alpha).astype(np.uint8)
smoothed_frames.append(faded_frame)
# 添加当前组的所有帧
smoothed_frames.extend(group)
if i < len(frame_groups) - 1:
# 组间过渡:当前组最后一帧淡出到下一组第一帧淡入
next_group = frame_groups[i + 1]
current_last = group[-1]
next_first = next_group[0]
for f in range(fade_frames):
alpha = f / fade_frames
blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
smoothed_frames.append(blended_frame)
return smoothed_frames
def apply_group_blend_smoothing(self, frame_groups, blend_frames):
"""对gloss分组应用混合平滑"""
smoothed_frames = []
for i, group in enumerate(frame_groups):
smoothed_frames.extend(group)
if i < len(frame_groups) - 1:
next_group = frame_groups[i + 1]
current_last = group[-1]
next_first = next_group[0]
# 在两组之间插入混合帧
for f in range(1, blend_frames + 1):
alpha = f / (blend_frames + 1)
blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
smoothed_frames.append(blended_frame)
return smoothed_frames
def apply_group_pause_smoothing(self, frame_groups, pause_frames):
"""对gloss分组应用暂停平滑"""
smoothed_frames = []
for i, group in enumerate(frame_groups):
smoothed_frames.extend(group)
# 在每组后添加暂停帧(重复最后一帧)
if i < len(frame_groups) - 1:
last_frame = group[-1]
for _ in range(pause_frames):
smoothed_frames.append(last_frame.copy())
return smoothed_frames
def show_available_glosses(self, limit=20):
"""显示可用的gloss或video_id"""
if self.gloss_mapping:
glosses = list(self.gloss_mapping.keys())
print(f"\n📋 可用的Gloss ({len(glosses)}个):")
for i, gloss in enumerate(glosses[:limit]):
videos = self.gloss_mapping[gloss]
if isinstance(videos, list):
print(f" {gloss} -> {len(videos)} 个视频")
else:
print(f" {gloss} -> {videos}")
if len(glosses) > limit:
print(f" ... 还有 {len(glosses) - limit} 个")
else:
video_ids = list(self.metadata['video_index'].keys())
print(f"\n📋 可用的Video ID ({len(video_ids)}个):")
for i, vid in enumerate(video_ids[:limit]):
frame_count = (self.metadata['video_index'][vid]['end_frame'] -
self.metadata['video_index'][vid]['start_frame'] + 1)
print(f" {vid} ({frame_count} 帧)")
if len(video_ids) > limit:
print(f" ... 还有 {len(video_ids) - limit} 个")
def run_qa_system(self):
"""运行QA系统"""
print("\n" + "=" * 60)
print("🤖 手语Gloss问答系统")
print("=" * 60)
print("💬 输入想要转换的gloss,用空格分隔多个词")
print("📋 输入 'list' 查看可用的gloss/video")
print("🔧 输入 'help' 查看帮助")
print("👋 输入 'quit' 退出系统")
print("=" * 60)
while True:
try:
user_input = input("\n🤖 请输入gloss: ").strip()
if not user_input:
continue
elif user_input.lower() == 'quit':
print("👋 感谢使用!")
break
elif user_input.lower() == 'list':
self.show_available_glosses()
continue
elif user_input.lower() == 'help':
self.show_help()
continue
# 解析输入的gloss
gloss_list = user_input.upper().split()
print(f"\n🎯 查询: {' + '.join(gloss_list)}")
# 获取对应的帧(每个gloss只选一个视频)
frame_indices, video_info = self.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)
if not frame_indices:
print("❌ 没有找到任何匹配的视频帧")
continue
print(f"\n📊 总共找到 {len(frame_indices)} 帧,来自 {len(video_info)} 个视频")
# 如果有多个视频,询问平滑选项
smoothing_method = 'none'
smoothing_frames = 0
if len(video_info) > 1:
print(f"\n🌊 检测到多个视频片段,选择平滑过渡方式:")
print(f" 1. none - 无平滑 (直接拼接)")
print(f" 2. fade - 淡入淡出过渡")
print(f" 3. blend - 帧间混合过渡")
print(f" 4. pause - 增加暂停间隔")
smooth_choice = input(f"选择平滑方式 [1-4, 默认1]: ").strip()
if smooth_choice == '2':
smoothing_method = 'fade'
smoothing_frames = int(input("淡入淡出帧数 [默认5]: ").strip() or "5")
elif smooth_choice == '3':
smoothing_method = 'blend'
smoothing_frames = int(input("混合帧数 [默认3]: ").strip() or "3")
elif smooth_choice == '4':
smoothing_method = 'pause'
smoothing_frames = int(input("暂停帧数 [默认10]: ").strip() or "10")
# 生成输出文件名
gloss_str = "_".join(gloss_list)
timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"
# 询问用户是否生成视频
confirm = input(f"\n❓ 生成视频到 {output_file}? [y/n]: ").strip().lower()
if confirm in ['y', 'yes', '']:
success = self.generate_video(
frame_indices, output_file, video_info,
smoothing_frames=smoothing_frames,
smoothing_method=smoothing_method
)
if success:
print(f"\n🎉 视频已生成: {output_file}")
# 显示视频详情
print(f"\n📈 视频详情:")
for info in video_info:
print(f" {info['gloss']}: {info['video_id']} ({info['frame_count']} 帧)")
else:
print("⏭️ 跳过视频生成")
except KeyboardInterrupt:
print("\n\n👋 系统已退出")
break
except Exception as e:
print(f"❌ 发生错误: {e}")
def show_help(self):
"""显示帮助信息"""
print("\n" + "=" * 50)
print("📖 帮助信息")
print("=" * 50)
print("🔹 输入单个gloss: HELLO")
print("🔹 输入多个gloss: HELLO WORLD GOODBYE")
print("🔹 查看可用内容: list")
print("🔹 系统会自动匹配对应的手语视频")
print(f"🔹 生成的视频保存在 {OUTPUT_DIR}/ 目录")
print("🔹 支持的映射文件格式 (gloss_mapping.json):")
print(' {"HELLO": ["video1", "video2"], "WORLD": "video3"}')
print("🔹 平滑过渡选项:")
print(" - fade: 淡入淡出过渡")
print(" - blend: 帧间混合过渡")
print(" - pause: 增加暂停间隔")
print("=" * 50)
def main():
parser = argparse.ArgumentParser(description='手语Gloss问答系统')
parser.add_argument('--gloss', '-g',
help='直接输入gloss生成视频,用空格分隔')
parser.add_argument('--fps', type=int, default=30,
help='视频帧率 (默认: 30)')
parser.add_argument('--width', type=int, default=480,
help='视频宽度 (默认: 480)')
parser.add_argument('--height', type=int, default=480,
help='视频高度 (默认: 480)')
parser.add_argument('--smoothing', choices=['none', 'fade', 'blend', 'pause'],
default='none', help='平滑过渡方式 (默认: none)')
parser.add_argument('--smoothing-frames', type=int, default=5,
help='平滑过渡帧数 (默认: 5)')
args = parser.parse_args()
# 初始化QA系统
qa_system = SignLanguageQA()
# 如果提供了gloss参数,直接处理
if args.gloss:
gloss_list = args.gloss.upper().split()
print(f"🎯 处理gloss: {' + '.join(gloss_list)}")
frame_indices, video_info = qa_system.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)
if frame_indices:
gloss_str = "_".join(gloss_list)
timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
suffix = f"_{args.smoothing}" if args.smoothing != 'none' else ""
output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"
print(f"📊 找到 {len(frame_indices)} 帧,来自 {len(video_info)} 个视频")
if args.smoothing != 'none':
print(f"🌊 使用 {args.smoothing} 平滑过渡 ({args.smoothing_frames} 帧)")
success = qa_system.generate_video(
frame_indices, output_file, video_info, args.fps, args.width, args.height,
args.smoothing_frames, args.smoothing
)
if success:
print(f"🎉 视频已生成: {output_file}")
print(f"\n📈 视频详情:")
for info in video_info:
print(f" {info['gloss']}: {info['video_id']} ({info['frame_count']} 帧)")
else:
print("❌ 没有找到匹配的视频")
else:
# 启动交互式QA系统
qa_system.run_qa_system()
if __name__ == "__main__":
main()12345678910111213141516171819202122232425262728293031323334353637383940414243import torchfrom PIL import Imageimport numpy as npimport json
from easy_dwpose import DWposeDetectorfrom easy_dwpose.draw.controlnext import draw_pose, process_pose_data
#####---------Setup init# You can use a different GPU, e.g. "cuda:1"device = "cuda:0" if torch.cuda.is_available() else "cpu"detector = DWposeDetector(device=device)input_image = Image.open("assets/pose.png").convert("RGB")
#####---------Custom ControlNext drawing style# Get pose data for custom drawing#pose_data = detector(input_image, draw_pose=False)# orpose_data = dict(np.load('assets/WLASL_01214/results_dwpose/npz/00000011.npz'))
# Get image dimensions#width, height = input_image.size# orwidth, height = 480, 480 #When I handle it, I default to a square with the largest side length. The size of the WLASL is 480*480.
# Process the pose data for custom drawingprocessed_pred = process_pose_data(pose_data, height, width)
# Draw pose using custom ControlNext stylevis_img = draw_pose( pose=processed_pred, H=height, W=width, include_body=True, include_hand=True, include_face=True)
# Convert to PIL Image and save (vis_img is in CHW format)custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))custom_skeleton.save("skeleton_controlnext.png")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970antlr4-python3-runtime==4.9.3av==14.4.0certifi==2025.4.26charset-normalizer==3.4.2click==8.2.1coloredlogs==15.0.1contourpy==1.3.2cycler==0.12.1easy_dwpose==1.0.2filelock==3.18.0flatbuffers==25.2.10fonttools==4.58.0fsspec==2025.5.1hf-xet==1.1.2huggingface-hub==0.24.7humanfriendly==10.0idna==3.10imageio==2.37.0imageio-ffmpeg==0.6.0Jinja2==3.1.6kiwisolver==1.4.8loguru==0.7.3MarkupSafe==3.0.2matplotlib==3.10.3mpmath==1.3.0natsort==8.4.0networkx==3.4.2numpy==1.26.4nvidia-cublas-cu12==12.6.4.1nvidia-cuda-cupti-cu12==12.6.80nvidia-cuda-nvrtc-cu12==12.6.77nvidia-cuda-runtime-cu12==12.6.77nvidia-cudnn-cu12==9.5.1.17nvidia-cufft-cu12==11.3.0.4nvidia-cufile-cu12==1.11.1.6nvidia-curand-cu12==10.3.7.77nvidia-cusolver-cu12==11.7.1.2nvidia-cusparse-cu12==12.5.4.2nvidia-cusparselt-cu12==0.6.3nvidia-nccl-cu12==2.26.2nvidia-nvjitlink-cu12==12.6.85nvidia-nvtx-cu12==12.6.77omegaconf==2.3.0onnxruntime==1.22.0onnxruntime-gpu==1.16.2opencv-python==4.11.0.86packaging==25.0pandas==2.2.3pillow==11.2.1pose_format==0.9.1protobuf==6.31.1psutil==7.0.0pyparsing==3.2.3python-dateutil==2.9.0.post0pytz==2025.2PyYAML==6.0.2requests==2.32.3scipy==1.15.3simplemma==1.1.2six==1.17.0-e git+https://github.com/sign-language-processing/spoken-to-signed-translation.git@21a34fbb7ae6439eb8ed54b0c4a2a5c4538a7977#egg=spoken_to_signedsvgwrite==1.4.3sympy==1.14.0torch==2.7.0tqdm==4.67.1Tree==0.2.4triton==3.3.0typing_extensions==4.13.2tzdata==2025.2urllib3==2.4.01234567891011121314151617181920212223242526272829303132333435363738394041424344import torchfrom PIL import Imageimport numpy as npimport json
from easy_dwpose import DWposeDetectorfrom easy_dwpose.draw.controlnext import draw_pose, process_pose_data
#####---------Setup init# You can use a different GPU, e.g. "cuda:1"device = "cuda:0" if torch.cuda.is_available() else "cpu"detector = DWposeDetector(device=device)input_image = Image.open("assets/pose.png").convert("RGB")
#####---------Custom ControlNext drawing style# Get pose data for custom drawing#pose_data = detector(input_image, draw_pose=False)# orpose_data = dict(np.load('assets/WLASL_01214/results_dwpose/npz/00000003.npz'))
# Get image dimensions#width, height = input_image.size# orwidth, height = 480, 480 #When I handle it, I default to a square with the largest side length. The size of the WLASL is 480*480.
# Process the pose data for custom drawingprocessed_pred = process_pose_data(pose_data, height, width)
# Draw pose using custom ControlNext stylevis_img = draw_pose( pose=processed_pred, H=height, W=width, include_body=True, include_hand=True, include_face=True)
# Convert to PIL Image and save (vis_img is in CHW format)custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))custom_skeleton.save("skeleton_controlnext3.png")12345678910111213141516171819202122232425262728293031323334353637383940414243444546#!/usr/bin/env python3
import csv
import subprocess
import sys
import os
import argparse
def read_csv_for_gloss(csv_path, gloss_key):
results = []
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if row['gloss'].strip().lower() == gloss_key.strip().lower():
results.append((row['video_id'], row['npz_dir']))
return results
def run_merge(npz_dir, output_dir="posedict"):
cmd = [sys.executable, "step2_merge_npz.py", npz_dir, "--output", output_dir]
ret = subprocess.run(cmd, capture_output=True, text=True)
if ret.returncode != 0:
print(f"❌ 合并失败:{npz_dir}")
print("stderr:")
print(ret.stderr)
print("stdout:")
print(ret.stdout)
return ret.returncode == 0
def main():
parser = argparse.ArgumentParser(description="从CSV中查gloss并合并npz,仅提示成功video_id")
parser.add_argument("--gloss", required=True, help="gloss关键词")
parser.add_argument("--csv", default="assets/WLASL_small_results/gloss_npz_mapping.csv", help="映射CSV路径")
parser.add_argument("--output", default="posedict", help="合并输出目录")
args = parser.parse_args()
mapping = read_csv_for_gloss(args.csv, args.gloss)
print("合并成功的文件id名称:")
for vid, npz_dir in mapping:
if not os.path.isdir(npz_dir):
continue
if run_merge(npz_dir, args.output):
print(vid)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186#!/usr/bin/env python3"""NPZ文件合并脚本用法: python merge.py <npz_folder_path>例如: python merge.py ./assets/WLASL_01214/results_dwpose/npz
将指定文件夹下的所有npz文件合并成一个大的npz文件,以视频名称命名并保存到./posedict文件夹下。"""
import osimport sysimport numpy as npfrom pathlib import Pathimport argparsefrom collections import defaultdict
def extract_frame_number(filename): """从文件名中提取帧号""" # 假设文件名格式为 00000001.npz, 00000002.npz 等 name = Path(filename).stem try: return int(name) except ValueError: print(f"警告: 无法从文件名 '{filename}' 中提取帧号") return 0
def get_video_name_from_path(npz_folder_path): """从路径中提取视频名称""" # 路径格式: ./assets/WLASL_01214/results_dwpose/npz # 提取 WLASL_01214 作为视频名称 path_parts = Path(npz_folder_path).parts for part in reversed(path_parts): if part != 'npz' and part != 'results_dwpose': return part return "unknown_video"
def merge_npz_files(npz_folder_path, output_folder="./posedict"): """ 合并指定文件夹下的所有npz文件 Args: npz_folder_path: 包含npz文件的文件夹路径 output_folder: 输出文件夹路径 """ # 确保输入路径存在 npz_folder = Path(npz_folder_path) if not npz_folder.exists(): print(f"错误: 文件夹 '{npz_folder_path}' 不存在") return False # 获取所有npz文件 npz_files = list(npz_folder.glob("*.npz")) if not npz_files: print(f"错误: 在文件夹 '{npz_folder_path}' 中未找到npz文件") return False print(f"找到 {len(npz_files)} 个npz文件") # 按帧号排序 npz_files.sort(key=lambda x: extract_frame_number(x.name)) # 创建输出文件夹 output_path = Path(output_folder) output_path.mkdir(parents=True, exist_ok=True) # 获取视频名称 video_name = get_video_name_from_path(npz_folder_path) output_file = output_path / f"{video_name}.npz" # 合并所有npz文件的数据 merged_data = {} for npz_file in npz_files: frame_number = extract_frame_number(npz_file.name) frame_key = f"frame_{frame_number:08d}" # 格式化为8位数字,如 frame_00000001 try: # 加载npz文件 data = np.load(npz_file, allow_pickle=True) # 将数据存储到合并字典中 frame_data = {} for key in data.files: frame_data[key] = data[key] merged_data[frame_key] = frame_data print(f"处理完成: {npz_file.name} -> {frame_key}") except Exception as e: print(f"错误: 无法加载文件 '{npz_file}': {e}") continue if not merged_data: print("错误: 没有成功加载任何npz文件") return False # 保存合并后的数据 try: # 由于npz格式的限制,我们需要特殊处理嵌套字典 # 将嵌套数据扁平化保存 flattened_data = {} for frame_key, frame_data in merged_data.items(): for data_key, data_value in frame_data.items(): combined_key = f"{frame_key}_{data_key}" flattened_data[combined_key] = data_value # 另外保存一个元数据,包含帧信息 frame_info = { 'frame_count': len(merged_data), 'frame_keys': list(merged_data.keys()), 'video_name': video_name, 'original_keys': list(next(iter(merged_data.values())).keys()) if merged_data else [] } flattened_data['_metadata'] = frame_info np.savez_compressed(output_file, **flattened_data) print(f"\n成功合并 {len(merged_data)} 帧数据") print(f"输出文件: {output_file}") print(f"文件大小: {output_file.stat().st_size / 1024 / 1024:.2f} MB") return True except Exception as e: print(f"错误: 保存合并文件时出错: {e}") return False
def load_merged_npz(npz_file_path): """ 加载合并后的npz文件的辅助函数 Args: npz_file_path: 合并后的npz文件路径 Returns: dict: 重构的帧数据字典 """ data = np.load(npz_file_path, allow_pickle=True) metadata = data['_metadata'].item() # 重构原始数据结构 frames_data = {} original_keys = metadata['original_keys'] for frame_key in metadata['frame_keys']: frame_data = {} for orig_key in original_keys: combined_key = f"{frame_key}_{orig_key}" if combined_key in data: frame_data[orig_key] = data[combined_key] frames_data[frame_key] = frame_data return frames_data, metadata
def main(): parser = argparse.ArgumentParser(description='合并NPZ文件') parser.add_argument('npz_folder', help='包含npz文件的文件夹路径') parser.add_argument('--output', '-o', default='./posedict', help='输出文件夹路径 (默认: ./posedict)') args = parser.parse_args() success = merge_npz_files(args.npz_folder, args.output) if success: print("\n✅ 合并完成!") # 演示如何读取合并后的文件 video_name = get_video_name_from_path(args.npz_folder) output_file = Path(args.output) / f"{video_name}.npz" print(f"\n💡 读取示例:") print(f"frames_data, metadata = load_merged_npz('{output_file}')") print(f"# 访问第11帧数据: frames_data['frame_00000011']") else: print("\n❌ 合并失败!") sys.exit(1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274#!/usr/bin/env python3"""NPZ转Pose视频脚本用法: python step2_read_and_vis_merge_npz_to_pose_video.py <merged_npz_path>例如: python step2_read_and_vis_merge_npz_to_pose_video.py ./posedict/WLASL_01214.npz
将合并后的多帧npz文件可视化成pose视频"""
import torchfrom PIL import Imageimport numpy as npimport jsonimport osimport sysimport argparsefrom pathlib import Pathimport cv2from tqdm import tqdm
from easy_dwpose import DWposeDetectorfrom easy_dwpose.draw.controlnext import draw_pose, process_pose_data
from pathlib import Pathimport numpy as np
def load_merged_npz(npz_file_path): """ 加载合并后的npz文件的辅助函数 Returns: frames_data: dict[str, dict[str, np.ndarray]] metadata: dict """ try: path = Path(npz_file_path) if not path.exists(): print(f"错误: 文件 '{npz_file_path}' 不存在") return None, None if not path.is_file(): print(f"错误: 路径 '{npz_file_path}' 不是一个有效的 .npz 文件") return None, None
data = np.load(path, allow_pickle=True) metadata = data['_metadata'].item()
frames_data = {} original_keys = metadata['original_keys']
for frame_key in metadata['frame_keys']: frame_data = {} for orig_key in original_keys: combined_key = f"{frame_key}_{orig_key}" if combined_key in data: frame_data[orig_key] = data[combined_key] frames_data[frame_key] = frame_data
return frames_data, metadata
except Exception as e: print(f"错误: 无法加载合并的npz文件 '{npz_file_path}': {e}") return None, None
def create_pose_frame(pose_data, width=480, height=480): """ 从pose数据创建单帧pose图像 Args: pose_data: 单帧的pose数据字典 width: 图像宽度 height: 图像高度 Returns: numpy.ndarray: RGB格式的图像数组 """ try: # Process the pose data for custom drawing processed_pred = process_pose_data(pose_data, height, width) # Draw pose using custom ControlNext style vis_img = draw_pose( pose=processed_pred, H=height, W=width, include_body=True, include_hand=True, include_face=True ) # Convert from CHW to HWC format pose_frame = vis_img.transpose(1, 2, 0) return pose_frame except Exception as e: print(f"错误: 创建pose帧时出错: {e}") return None
def create_pose_video(merged_npz_path, output_folder="./output_pose_video", fps=30, width=480, height=480): """ 从合并的npz文件创建pose视频 Args: merged_npz_path: 合并后的npz文件路径 output_folder: 输出文件夹 fps: 视频帧率 width: 视频宽度 height: 视频高度 """ # 检查输入文件是否存在 npz_path = Path(merged_npz_path) if not npz_path.exists(): print(f"错误: 文件 '{merged_npz_path}' 不存在") return False # 加载合并的npz数据 print(f"正在加载合并的npz文件: {merged_npz_path}") frames_data, metadata = load_merged_npz(merged_npz_path) if frames_data is None: print("错误: 无法加载npz数据") return False print(f"成功加载 {metadata['frame_count']} 帧数据") # 创建输出文件夹 output_path = Path(output_folder) output_path.mkdir(parents=True, exist_ok=True) # 生成输出视频文件名 video_name = npz_path.stem # 获取文件名(不含扩展名) output_video_path = output_path / f"{video_name}_pose_video.mp4" # 设置视频编码器 fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter(str(output_video_path), fourcc, fps, (width, height)) if not video_writer.isOpened(): print("错误: 无法创建视频文件") return False # 按帧号排序 sorted_frame_keys = sorted(frames_data.keys(), key=lambda x: int(x.split('_')[1])) print(f"正在生成pose视频...") # 生成每一帧 for frame_key in tqdm(sorted_frame_keys, desc="处理帧"): pose_data = frames_data[frame_key] # 创建pose帧 pose_frame = create_pose_frame(pose_data, width, height) if pose_frame is not None: # 转换为BGR格式(OpenCV格式) pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR) # 写入视频 video_writer.write(pose_frame_bgr) else: print(f"警告: 跳过帧 {frame_key}(处理失败)") # 释放视频写入器 video_writer.release() print(f"\n✅ Pose视频生成完成!") print(f"输出文件: {output_video_path}") print(f"视频信息: {len(sorted_frame_keys)} 帧, {fps} fps, {width}x{height}") print(f"文件大小: {output_video_path.stat().st_size / 1024 / 1024:.2f} MB") return True
def create_pose_images(merged_npz_path, output_folder="./output_pose_images", width=480, height=480): """ 从合并的npz文件创建pose图像序列(可选功能) Args: merged_npz_path: 合并后的npz文件路径 output_folder: 输出文件夹 width: 图像宽度 height: 图像高度 """ # 检查输入文件是否存在 npz_path = Path(merged_npz_path) if not npz_path.exists(): print(f"错误: 文件 '{merged_npz_path}' 不存在") return False # 加载合并的npz数据 print(f"正在加载合并的npz文件: {merged_npz_path}") frames_data, metadata = load_merged_npz(merged_npz_path) if frames_data is None: print("错误: 无法加载npz数据") return False # 创建输出文件夹 video_name = npz_path.stem output_path = Path(output_folder) / video_name output_path.mkdir(parents=True, exist_ok=True) # 按帧号排序 sorted_frame_keys = sorted(frames_data.keys(), key=lambda x: int(x.split('_')[1])) print(f"正在生成pose图像序列...") # 生成每一帧图像 for i, frame_key in enumerate(tqdm(sorted_frame_keys, desc="处理帧")): pose_data = frames_data[frame_key] # 创建pose帧 pose_frame = create_pose_frame(pose_data, width, height) if pose_frame is not None: # 保存为PNG图像 frame_number = int(frame_key.split('_')[1]) output_image_path = output_path / f"pose_{frame_number:08d}.png" pose_image = Image.fromarray(pose_frame) pose_image.save(output_image_path) else: print(f"警告: 跳过帧 {frame_key}(处理失败)") print(f"\n✅ Pose图像序列生成完成!") print(f"输出文件夹: {output_path}") print(f"生成图像数: {len(sorted_frame_keys)} 张") return True
def main(): parser = argparse.ArgumentParser(description='将合并的NPZ文件转换为Pose视频') parser.add_argument('merged_npz_path', help='合并后的npz文件路径') parser.add_argument('--output', '-o', default='./output_pose_video', help='输出文件夹路径 (默认: ./output_pose_video)') parser.add_argument('--fps', type=int, default=30, help='视频帧率 (默认: 30)') parser.add_argument('--width', type=int, default=480, help='视频宽度 (默认: 480)') parser.add_argument('--height', type=int, default=480, help='视频高度 (默认: 480)') parser.add_argument('--images', action='store_true', help='同时生成图像序列') args = parser.parse_args() # 生成pose视频 success = create_pose_video( args.merged_npz_path, args.output, args.fps, args.width, args.height ) if not success: print("\n❌ 视频生成失败!") sys.exit(1) # 如果指定了--images选项,同时生成图像序列 if args.images: print("\n" + "="*50) print("生成图像序列...") create_pose_images( args.merged_npz_path, args.output.replace('video', 'images'), args.width, args.height )
if __name__ == "__main__": main()README.mdAdded+170
batch_merge_videos.pyAdded+228
extract_gloss_mapping.pyAdded+230
main.pyAdded+84
merge_all_to_database.pyAdded+328
preprocess_pipeline.pyAdded+279
qa_system.pyAdded+583
quick_vis_controlnext_style_dwpose_from_npz_or_input_img.pyAdded+43
requirements.txtAdded+70
step0_learn_quick_vis_controlnext_style_dwpose_from_npz_or_input_img.pyAdded+44
step1_run_step1_from_csv.pyAdded+46
step2_merge_npz.pyAdded+186
step3_read_and_vis_merge_npz_to_pose_video.pyAdded+274