FangSen9000 commited on
Commit ·
29c2c7a
1
Parent(s): dd36216
Add Python scripts and documentation
Browse files- README.md +170 -0
- batch_merge_videos.py +228 -0
- extract_gloss_mapping.py +230 -0
- main.py +84 -0
- merge_all_to_database.py +328 -0
- preprocess_pipeline.py +279 -0
- qa_system.py +583 -0
- quick_vis_controlnext_style_dwpose_from_npz_or_input_img.py +43 -0
- requirements.txt +70 -0
- step0_learn_quick_vis_controlnext_style_dwpose_from_npz_or_input_img.py +44 -0
- step1_run_step1_from_csv.py +46 -0
- step2_merge_npz.py +186 -0
- step3_read_and_vis_merge_npz_to_pose_video.py +274 -0
README.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# fast_dwpose
|
| 2 |
+
|
| 3 |
+
The goal of Easy DWPose is to provide a generic, reliable, and easy-to-use interface for making skeletons for ControlNet.
|
| 4 |
+
|
| 5 |
+
SF do some improve for [easy-dwpose](https://github.com/reallyigor/easy_dwpose), named it fast-dwpose.
|
| 6 |
+
|
| 7 |
+
## Installation
|
| 8 |
+
|
| 9 |
+
### PIP
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
pip install easy-dwpose
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Quickstart
|
| 16 |
+
|
| 17 |
+
### In you own .py scrip or in Jupyter
|
| 18 |
+
|
| 19 |
+
```python
|
| 20 |
+
import torch
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import numpy as np
|
| 23 |
+
import json
|
| 24 |
+
|
| 25 |
+
from easy_dwpose import DWposeDetector
|
| 26 |
+
|
| 27 |
+
#####---------Setup init
|
| 28 |
+
# You can use a different GPU, e.g. "cuda:1"
|
| 29 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 30 |
+
detector = DWposeDetector(device=device)
|
| 31 |
+
input_image = Image.open("assets/pose.png").convert("RGB")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
#####---------Get both the skeleton image
|
| 35 |
+
# SF: skeleton should be a kind of img
|
| 36 |
+
skeleton = detector(input_image, output_type="pil", include_hands=True, include_face=True)
|
| 37 |
+
# Save the skeleton image
|
| 38 |
+
skeleton.save("skeleton.png")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
#####---------Get pose data
|
| 42 |
+
# SF: pose_data should be numpy/tensor
|
| 43 |
+
# # This returns the dictionary
|
| 44 |
+
pose_data = detector(input_image, draw_pose=False)
|
| 45 |
+
|
| 46 |
+
# Save the skeleton pose information:
|
| 47 |
+
# Option 1: Save as NPY file
|
| 48 |
+
np.save('pose_data.npy', pose_data)
|
| 49 |
+
|
| 50 |
+
# Option 2: Save as NPZ file
|
| 51 |
+
np.savez('pose_data.npz', **pose_data)
|
| 52 |
+
|
| 53 |
+
# Option 3: Save as JSON file
|
| 54 |
+
# Convert numpy arrays to lists for JSON serialization
|
| 55 |
+
pose_data_json = {k: v.tolist() if isinstance(v, np.ndarray) else v for k, v in pose_data.items()}
|
| 56 |
+
with open('pose_data.json', 'w') as f:
|
| 57 |
+
json.dump(pose_data_json, f)
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
<table align="center">
|
| 61 |
+
<tr>
|
| 62 |
+
<th align="center">Input</th>
|
| 63 |
+
<th align="center">Output</th>
|
| 64 |
+
</tr>
|
| 65 |
+
<tr>
|
| 66 |
+
<td align="center">
|
| 67 |
+
<br />
|
| 68 |
+
<img src="./assets/pose.png"/>
|
| 69 |
+
</td>
|
| 70 |
+
<td align="center">
|
| 71 |
+
<br/>
|
| 72 |
+
<img src="./assets/skeleton.png"/>
|
| 73 |
+
</td>
|
| 74 |
+
</tr>
|
| 75 |
+
</table>
|
| 76 |
+
|
| 77 |
+
### On a video
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
python scripts/inference_on_video.py --input assets/dance.mp4 --output_path result.mp4
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
<table align="center">
|
| 84 |
+
<tr>
|
| 85 |
+
<th align="center">Input</th>
|
| 86 |
+
<th align="center">Output</th>
|
| 87 |
+
</tr>
|
| 88 |
+
<tr>
|
| 89 |
+
<td align="center">
|
| 90 |
+
<br />
|
| 91 |
+
<img src="./assets/dance.gif"/>
|
| 92 |
+
</td>
|
| 93 |
+
<td align="center">
|
| 94 |
+
<br/>
|
| 95 |
+
<img src="./assets/skeleton.gif"/>
|
| 96 |
+
</td>
|
| 97 |
+
</tr>
|
| 98 |
+
</table>
|
| 99 |
+
|
| 100 |
+
### On a folder of images
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
python scripts/inference_on_folder.py --input assets/ --output_path results/
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
### Easy-DWPose Custom skeleton drawing
|
| 107 |
+
|
| 108 |
+
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!
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
from PIL import Image
|
| 112 |
+
from easy_dwpose import DWposeDetector
|
| 113 |
+
from easy_dwpose.draw.musepose import draw_pose as draw_pose_musepose
|
| 114 |
+
|
| 115 |
+
detector = DWposeDetector(device="cpu")
|
| 116 |
+
input_image = Image.open("assets/pose.png").convert("RGB")
|
| 117 |
+
|
| 118 |
+
skeleton = detector(input_image, output_type="pil", draw_pose=draw_pose_musepose, draw_face=False)
|
| 119 |
+
skeleton.save("skeleton.png")
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### SF Custom skeleton drawing
|
| 123 |
+
|
| 124 |
+
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:
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
import torch
|
| 128 |
+
from PIL import Image
|
| 129 |
+
import numpy as np
|
| 130 |
+
import json
|
| 131 |
+
|
| 132 |
+
from easy_dwpose import DWposeDetector
|
| 133 |
+
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
| 134 |
+
|
| 135 |
+
#####---------Setup init
|
| 136 |
+
# You can use a different GPU, e.g. "cuda:1"
|
| 137 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 138 |
+
detector = DWposeDetector(device=device)
|
| 139 |
+
input_image = Image.open("assets/pose.png").convert("RGB")
|
| 140 |
+
|
| 141 |
+
#####---------Custom ControlNext drawing style
|
| 142 |
+
# Get pose data for custom drawing
|
| 143 |
+
pose_data = detector(input_image, draw_pose=False)
|
| 144 |
+
|
| 145 |
+
# Get image dimensions
|
| 146 |
+
width, height = input_image.size
|
| 147 |
+
|
| 148 |
+
# Process the pose data for custom drawing
|
| 149 |
+
processed_pred = process_pose_data(pose_data, height, width)
|
| 150 |
+
|
| 151 |
+
# Draw pose using custom ControlNext style
|
| 152 |
+
vis_img = draw_pose(
|
| 153 |
+
pose=processed_pred,
|
| 154 |
+
H=height,
|
| 155 |
+
W=width,
|
| 156 |
+
include_body=True,
|
| 157 |
+
include_hand=True,
|
| 158 |
+
include_face=True
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# Convert to PIL Image and save (vis_img is in CHW format)
|
| 162 |
+
custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))
|
| 163 |
+
custom_skeleton.save("skeleton_controlnext.png")
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
## Acknowledgement
|
| 167 |
+
|
| 168 |
+
We thank the original authors of the [DWPose](https://github.com/IDEA-Research/DWPose) for their incredible models!
|
| 169 |
+
|
| 170 |
+
Thanks for open-sourcing!
|
batch_merge_videos.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
批量合并所有视频的npz文件
|
| 4 |
+
从 assets/WLASL_small_results/{video_id}/results_dwpose/npz/
|
| 5 |
+
合并到 output/single/{video_id}.npz
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import csv
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import argparse
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_video_mapping(csv_path="output/gloss_video_mapping.csv"):
|
| 18 |
+
"""从CSV文件加载视频映射信息"""
|
| 19 |
+
video_mapping = {}
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
with open(csv_path, 'r', encoding='utf-8') as f:
|
| 23 |
+
reader = csv.DictReader(f)
|
| 24 |
+
for row in reader:
|
| 25 |
+
video_id = row['video_id']
|
| 26 |
+
npz_path = row['npz_path']
|
| 27 |
+
video_mapping[video_id] = {
|
| 28 |
+
'npz_path': npz_path,
|
| 29 |
+
'gloss': row['gloss'],
|
| 30 |
+
'original_gloss': row['original_gloss']
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
print(f"✅ 成功加载视频映射: {len(video_mapping)} 个视频")
|
| 34 |
+
return video_mapping
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"❌ 加载视频映射失败: {e}")
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def check_npz_folder_exists(npz_path):
|
| 42 |
+
"""检查npz文件夹是否存在且包含npz文件"""
|
| 43 |
+
folder_path = Path(npz_path)
|
| 44 |
+
|
| 45 |
+
if not folder_path.exists():
|
| 46 |
+
return False, "文件夹不存在"
|
| 47 |
+
|
| 48 |
+
npz_files = list(folder_path.glob("*.npz"))
|
| 49 |
+
if not npz_files:
|
| 50 |
+
return False, "文件夹中没有npz文件"
|
| 51 |
+
|
| 52 |
+
return True, f"包含 {len(npz_files)} 个npz文件"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def merge_single_video(video_id, npz_folder_path, output_dir="output/single"):
|
| 56 |
+
"""合并单个视频的npz文件"""
|
| 57 |
+
try:
|
| 58 |
+
# 确保输出目录存在
|
| 59 |
+
output_path = Path(output_dir)
|
| 60 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
|
| 62 |
+
# 检查输出文件是否已存在
|
| 63 |
+
output_file = output_path / f"{video_id}.npz"
|
| 64 |
+
if output_file.exists():
|
| 65 |
+
return True, "文件已存在,跳过"
|
| 66 |
+
|
| 67 |
+
# 调用step2_merge_npz.py
|
| 68 |
+
cmd = [
|
| 69 |
+
sys.executable, "step2_merge_npz.py",
|
| 70 |
+
npz_folder_path,
|
| 71 |
+
"--output", output_dir
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 75 |
+
|
| 76 |
+
if result.returncode == 0:
|
| 77 |
+
# 检查生成的文件并重命名(如果需要)
|
| 78 |
+
# step2_merge_npz.py 可能使用文件夹名作为输出文件名
|
| 79 |
+
generated_files = list(output_path.glob("*.npz"))
|
| 80 |
+
|
| 81 |
+
# 查找最新生成的文件
|
| 82 |
+
expected_name = Path(npz_folder_path).parts[-3] # 从路径中提取视频名
|
| 83 |
+
expected_file = output_path / f"{expected_name}.npz"
|
| 84 |
+
|
| 85 |
+
if expected_file.exists() and expected_file != output_file:
|
| 86 |
+
# 重命名为video_id.npz
|
| 87 |
+
expected_file.rename(output_file)
|
| 88 |
+
|
| 89 |
+
if output_file.exists():
|
| 90 |
+
return True, f"合并成功"
|
| 91 |
+
else:
|
| 92 |
+
return False, "合并后文件未找到"
|
| 93 |
+
else:
|
| 94 |
+
return False, f"合并失败: {result.stderr.strip()}"
|
| 95 |
+
|
| 96 |
+
except Exception as e:
|
| 97 |
+
return False, f"处理异常: {str(e)}"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def batch_merge_all_videos(video_mapping, output_dir="output/single"):
|
| 101 |
+
"""批量合并所有视频"""
|
| 102 |
+
print(f"🔄 开始批量合并 {len(video_mapping)} 个视频...")
|
| 103 |
+
|
| 104 |
+
success_count = 0
|
| 105 |
+
skip_count = 0
|
| 106 |
+
error_count = 0
|
| 107 |
+
error_videos = []
|
| 108 |
+
|
| 109 |
+
# 创建输出目录
|
| 110 |
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
| 111 |
+
|
| 112 |
+
for video_id, info in tqdm(video_mapping.items(), desc="合并视频"):
|
| 113 |
+
npz_path = info['npz_path']
|
| 114 |
+
gloss = info['gloss']
|
| 115 |
+
|
| 116 |
+
# 检查npz文件夹
|
| 117 |
+
exists, status = check_npz_folder_exists(npz_path)
|
| 118 |
+
|
| 119 |
+
if not exists:
|
| 120 |
+
error_count += 1
|
| 121 |
+
error_videos.append((video_id, gloss, f"NPZ文件夹问题: {status}"))
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
# 执行合并
|
| 125 |
+
success, message = merge_single_video(video_id, npz_path, output_dir)
|
| 126 |
+
|
| 127 |
+
if success:
|
| 128 |
+
if "跳过" in message:
|
| 129 |
+
skip_count += 1
|
| 130 |
+
else:
|
| 131 |
+
success_count += 1
|
| 132 |
+
else:
|
| 133 |
+
error_count += 1
|
| 134 |
+
error_videos.append((video_id, gloss, message))
|
| 135 |
+
|
| 136 |
+
# 输出统计结果
|
| 137 |
+
print(f"\n📊 批量合并完成:")
|
| 138 |
+
print(f" ✅ 成功合并: {success_count} 个")
|
| 139 |
+
print(f" ⏭️ 跳过已存在: {skip_count} 个")
|
| 140 |
+
print(f" ❌ 失败: {error_count} 个")
|
| 141 |
+
|
| 142 |
+
if error_videos:
|
| 143 |
+
print(f"\n❌ 失败的视频:")
|
| 144 |
+
for video_id, gloss, error_msg in error_videos[:10]: # 只显示前10个错误
|
| 145 |
+
print(f" {video_id} ({gloss}): {error_msg}")
|
| 146 |
+
if len(error_videos) > 10:
|
| 147 |
+
print(f" ... 还有 {len(error_videos) - 10} 个错误")
|
| 148 |
+
|
| 149 |
+
return success_count, skip_count, error_count, error_videos
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def verify_merged_files(video_mapping, output_dir="output/single"):
|
| 153 |
+
"""验证合并后的文件"""
|
| 154 |
+
print(f"\n🔍 验证合并后的文件...")
|
| 155 |
+
|
| 156 |
+
total_expected = len(video_mapping)
|
| 157 |
+
existing_files = list(Path(output_dir).glob("*.npz"))
|
| 158 |
+
existing_count = len(existing_files)
|
| 159 |
+
|
| 160 |
+
print(f" 期望文件数: {total_expected}")
|
| 161 |
+
print(f" 实际文件数: {existing_count}")
|
| 162 |
+
|
| 163 |
+
if existing_count == total_expected:
|
| 164 |
+
print(f" ✅ 所有文件都已生成!")
|
| 165 |
+
else:
|
| 166 |
+
missing_count = total_expected - existing_count
|
| 167 |
+
print(f" ⚠️ 缺失 {missing_count} 个文件")
|
| 168 |
+
|
| 169 |
+
# 找出缺失的文件
|
| 170 |
+
existing_video_ids = {f.stem for f in existing_files}
|
| 171 |
+
expected_video_ids = set(video_mapping.keys())
|
| 172 |
+
missing_video_ids = expected_video_ids - existing_video_ids
|
| 173 |
+
|
| 174 |
+
if missing_video_ids and len(missing_video_ids) <= 10:
|
| 175 |
+
print(f" 缺失的video_id: {list(missing_video_ids)}")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def main():
|
| 179 |
+
parser = argparse.ArgumentParser(description='批量合并所有视频的npz文件')
|
| 180 |
+
parser.add_argument('--mapping', '-m', default='output/gloss_video_mapping.csv',
|
| 181 |
+
help='视频映射CSV文件路径 (默认: output/gloss_video_mapping.csv)')
|
| 182 |
+
parser.add_argument('--output', '-o', default='output/single',
|
| 183 |
+
help='输出目录 (默认: output/single)')
|
| 184 |
+
parser.add_argument('--verify', action='store_true',
|
| 185 |
+
help='验证合并后的文件')
|
| 186 |
+
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
|
| 189 |
+
# 检查映射文件是否存在
|
| 190 |
+
if not Path(args.mapping).exists():
|
| 191 |
+
print(f"❌ 映射文件不存在: {args.mapping}")
|
| 192 |
+
print(" 请先运行 extract_gloss_mapping.py 生成映射文件")
|
| 193 |
+
return
|
| 194 |
+
|
| 195 |
+
# 检查step2_merge_npz.py是否存在
|
| 196 |
+
if not Path("step2_merge_npz.py").exists():
|
| 197 |
+
print(f"❌ 依赖文件不存在: step2_merge_npz.py")
|
| 198 |
+
return
|
| 199 |
+
|
| 200 |
+
# 加载视频映射
|
| 201 |
+
video_mapping = load_video_mapping(args.mapping)
|
| 202 |
+
if not video_mapping:
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
# 批量合并
|
| 206 |
+
success_count, skip_count, error_count, error_videos = batch_merge_all_videos(
|
| 207 |
+
video_mapping, args.output
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# 验证结果
|
| 211 |
+
if args.verify or True: # 默认总是验证
|
| 212 |
+
verify_merged_files(video_mapping, args.output)
|
| 213 |
+
|
| 214 |
+
# 保存错误报告
|
| 215 |
+
if error_videos:
|
| 216 |
+
error_report_path = Path(args.output).parent / "merge_errors.txt"
|
| 217 |
+
with open(error_report_path, 'w', encoding='utf-8') as f:
|
| 218 |
+
f.write("合并失败的视频报告:\n")
|
| 219 |
+
f.write("=" * 50 + "\n")
|
| 220 |
+
for video_id, gloss, error_msg in error_videos:
|
| 221 |
+
f.write(f"{video_id} ({gloss}): {error_msg}\n")
|
| 222 |
+
print(f"\n📝 错误报告已保存: {error_report_path}")
|
| 223 |
+
|
| 224 |
+
print(f"\n🎉 批量合并任务完成!")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
从train.json提取gloss映射信息
|
| 4 |
+
生成 output/gloss_mapping.json 和 output/gloss_video_mapping.csv
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import csv
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
import argparse
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_train_json(json_path):
|
| 15 |
+
"""加载train.json文件"""
|
| 16 |
+
try:
|
| 17 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
| 18 |
+
data = json.load(f)
|
| 19 |
+
print(f"✅ 成功加载 {json_path}")
|
| 20 |
+
print(f"📊 包含 {len(data)} 个gloss条目")
|
| 21 |
+
return data
|
| 22 |
+
except Exception as e:
|
| 23 |
+
print(f"❌ 加载JSON文件失败: {e}")
|
| 24 |
+
return None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def extract_mapping_data(train_data, dataset_root):
|
| 28 |
+
"""从train.json提取映射数据"""
|
| 29 |
+
gloss_to_videos = defaultdict(list)
|
| 30 |
+
video_details = {}
|
| 31 |
+
|
| 32 |
+
print("🔄 正在提取映射数据...")
|
| 33 |
+
|
| 34 |
+
for entry in train_data:
|
| 35 |
+
gloss = entry['gloss'].upper() # 统一转为大写
|
| 36 |
+
|
| 37 |
+
for instance in entry['instances']:
|
| 38 |
+
video_id = instance['video_id']
|
| 39 |
+
|
| 40 |
+
# 添加到gloss映射
|
| 41 |
+
if video_id not in gloss_to_videos[gloss]:
|
| 42 |
+
gloss_to_videos[gloss].append(video_id)
|
| 43 |
+
|
| 44 |
+
# 保存视频详细信息
|
| 45 |
+
video_details[video_id] = {
|
| 46 |
+
'gloss': gloss,
|
| 47 |
+
'original_gloss': entry['gloss'], # 保留原始大小写
|
| 48 |
+
'signer_id': instance['signer_id'],
|
| 49 |
+
'fps': instance['fps'],
|
| 50 |
+
'frame_start': instance['frame_start'],
|
| 51 |
+
'frame_end': instance['frame_end'],
|
| 52 |
+
'bbox': instance['bbox'],
|
| 53 |
+
'source': instance['source'],
|
| 54 |
+
'split': instance['split'],
|
| 55 |
+
'url': instance['url'],
|
| 56 |
+
'variation_id': instance['variation_id'],
|
| 57 |
+
'instance_id': instance['instance_id'],
|
| 58 |
+
'npz_path': f"{dataset_root}/{video_id}/results_dwpose/npz"
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
# 转换为普通字典并处理单个视频的情况
|
| 62 |
+
gloss_mapping = {}
|
| 63 |
+
for gloss, videos in gloss_to_videos.items():
|
| 64 |
+
if len(videos) == 1:
|
| 65 |
+
gloss_mapping[gloss] = videos[0]
|
| 66 |
+
else:
|
| 67 |
+
gloss_mapping[gloss] = videos
|
| 68 |
+
|
| 69 |
+
print(f"✅ 提取完成:")
|
| 70 |
+
print(f" 📝 {len(gloss_mapping)} 个不同的gloss")
|
| 71 |
+
print(f" 🎬 {len(video_details)} 个视频实例")
|
| 72 |
+
|
| 73 |
+
return gloss_mapping, video_details
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def save_gloss_mapping_json(gloss_mapping, output_path="output/gloss_mapping.json"):
|
| 77 |
+
"""保存gloss映射为JSON文件"""
|
| 78 |
+
try:
|
| 79 |
+
# 确保输出目录存在
|
| 80 |
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| 81 |
+
|
| 82 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 83 |
+
json.dump(gloss_mapping, f, indent=2, ensure_ascii=False)
|
| 84 |
+
print(f"✅ gloss映射已保存: {output_path}")
|
| 85 |
+
return True
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"❌ 保存JSON映射失败: {e}")
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def save_video_mapping_csv(video_details, output_path="output/gloss_video_mapping.csv"):
|
| 92 |
+
"""保存视频映射为CSV文件"""
|
| 93 |
+
try:
|
| 94 |
+
# 确保输出目录存在
|
| 95 |
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
fieldnames = [
|
| 98 |
+
'video_id', 'gloss', 'original_gloss', 'npz_path',
|
| 99 |
+
'signer_id', 'fps', 'frame_start', 'frame_end',
|
| 100 |
+
'bbox_x', 'bbox_y', 'bbox_w', 'bbox_h',
|
| 101 |
+
'source', 'split', 'url', 'variation_id', 'instance_id'
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
with open(output_path, 'w', newline='', encoding='utf-8') as f:
|
| 105 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 106 |
+
writer.writeheader()
|
| 107 |
+
|
| 108 |
+
for video_id, details in video_details.items():
|
| 109 |
+
# 处理bbox
|
| 110 |
+
bbox = details['bbox']
|
| 111 |
+
row = {
|
| 112 |
+
'video_id': video_id,
|
| 113 |
+
'gloss': details['gloss'],
|
| 114 |
+
'original_gloss': details['original_gloss'],
|
| 115 |
+
'npz_path': details['npz_path'],
|
| 116 |
+
'signer_id': details['signer_id'],
|
| 117 |
+
'fps': details['fps'],
|
| 118 |
+
'frame_start': details['frame_start'],
|
| 119 |
+
'frame_end': details['frame_end'],
|
| 120 |
+
'bbox_x': bbox[0],
|
| 121 |
+
'bbox_y': bbox[1],
|
| 122 |
+
'bbox_w': bbox[2] - bbox[0],
|
| 123 |
+
'bbox_h': bbox[3] - bbox[1],
|
| 124 |
+
'source': details['source'],
|
| 125 |
+
'split': details['split'],
|
| 126 |
+
'url': details['url'],
|
| 127 |
+
'variation_id': details['variation_id'],
|
| 128 |
+
'instance_id': details['instance_id']
|
| 129 |
+
}
|
| 130 |
+
writer.writerow(row)
|
| 131 |
+
|
| 132 |
+
print(f"✅ 视频映射已保存: {output_path}")
|
| 133 |
+
return True
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"❌ 保存CSV文件失败: {e}")
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def generate_statistics(gloss_mapping, video_details):
|
| 140 |
+
"""生成统计信息"""
|
| 141 |
+
print("\n" + "=" * 50)
|
| 142 |
+
print("📊 数据统计")
|
| 143 |
+
print("=" * 50)
|
| 144 |
+
|
| 145 |
+
# Gloss统计
|
| 146 |
+
total_glosses = len(gloss_mapping)
|
| 147 |
+
single_video_glosses = sum(1 for v in gloss_mapping.values() if isinstance(v, str))
|
| 148 |
+
multi_video_glosses = total_glosses - single_video_glosses
|
| 149 |
+
|
| 150 |
+
print(f"📝 Gloss统计:")
|
| 151 |
+
print(f" 总gloss数: {total_glosses}")
|
| 152 |
+
print(f" 单视频gloss: {single_video_glosses}")
|
| 153 |
+
print(f" 多视频gloss: {multi_video_glosses}")
|
| 154 |
+
|
| 155 |
+
# 视频统计
|
| 156 |
+
total_videos = len(video_details)
|
| 157 |
+
sources = set(d['source'] for d in video_details.values())
|
| 158 |
+
splits = set(d['split'] for d in video_details.values())
|
| 159 |
+
signers = set(d['signer_id'] for d in video_details.values())
|
| 160 |
+
|
| 161 |
+
print(f"\n🎬 视频统计:")
|
| 162 |
+
print(f" 总视频数: {total_videos}")
|
| 163 |
+
print(f" 数据源: {', '.join(sources)}")
|
| 164 |
+
print(f" 数据集分割: {', '.join(splits)}")
|
| 165 |
+
print(f" 签名者数量: {len(signers)}")
|
| 166 |
+
|
| 167 |
+
# Top 10 最多视频的gloss
|
| 168 |
+
video_counts = []
|
| 169 |
+
for gloss, videos in gloss_mapping.items():
|
| 170 |
+
count = len(videos) if isinstance(videos, list) else 1
|
| 171 |
+
video_counts.append((gloss, count))
|
| 172 |
+
|
| 173 |
+
video_counts.sort(key=lambda x: x[1], reverse=True)
|
| 174 |
+
|
| 175 |
+
print(f"\n🏆 视频数量最多的10个gloss:")
|
| 176 |
+
for i, (gloss, count) in enumerate(video_counts[:10], 1):
|
| 177 |
+
print(f" {i:2d}. {gloss}: {count} 个视频")
|
| 178 |
+
|
| 179 |
+
print("=" * 50)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def main():
|
| 183 |
+
parser = argparse.ArgumentParser(description='从train.json提取gloss映射')
|
| 184 |
+
parser.add_argument('--dataset-root', '-d',
|
| 185 |
+
default='assets/WLASL_small_results',
|
| 186 |
+
help='数据集根目录路径 (默认: assets/WLASL_small_results)')
|
| 187 |
+
parser.add_argument('--input', '-i',
|
| 188 |
+
help='输入的JSON文件路径 (默认: {dataset_root}/train.json)')
|
| 189 |
+
|
| 190 |
+
args = parser.parse_args()
|
| 191 |
+
|
| 192 |
+
# 如果没有指定input,使用dataset_root + train.json
|
| 193 |
+
if not args.input:
|
| 194 |
+
args.input = f"{args.dataset_root}/train.json"
|
| 195 |
+
|
| 196 |
+
print(f"📁 数据集根目录: {args.dataset_root}")
|
| 197 |
+
print(f"📄 JSON文件路径: {args.input}")
|
| 198 |
+
|
| 199 |
+
# 检查输入文件
|
| 200 |
+
if not Path(args.input).exists():
|
| 201 |
+
print(f"❌ 输入文件不存在: {args.input}")
|
| 202 |
+
return
|
| 203 |
+
|
| 204 |
+
# 加载数据
|
| 205 |
+
train_data = load_train_json(args.input)
|
| 206 |
+
if not train_data:
|
| 207 |
+
return
|
| 208 |
+
|
| 209 |
+
# 提取映射数据
|
| 210 |
+
gloss_mapping, video_details = extract_mapping_data(train_data, args.dataset_root)
|
| 211 |
+
|
| 212 |
+
# 保存文件
|
| 213 |
+
print(f"\n💾 正在保存文件...")
|
| 214 |
+
|
| 215 |
+
success = True
|
| 216 |
+
success &= save_gloss_mapping_json(gloss_mapping)
|
| 217 |
+
success &= save_video_mapping_csv(video_details)
|
| 218 |
+
|
| 219 |
+
if success:
|
| 220 |
+
print(f"\n🎉 映射文件生成成功!")
|
| 221 |
+
print(f"📁 生成的文件:")
|
| 222 |
+
print(f" - output/gloss_mapping.json (QA系统使用)")
|
| 223 |
+
print(f" - output/gloss_video_mapping.csv (详细映射信息)")
|
| 224 |
+
|
| 225 |
+
# 生成统计信息
|
| 226 |
+
generate_statistics(gloss_mapping, video_details)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
main()
|
main.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import csv
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
import os
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
def read_mapping(gloss, csv_path):
|
| 10 |
+
result = []
|
| 11 |
+
with open(csv_path, 'r', encoding='utf-8') as f:
|
| 12 |
+
reader = csv.DictReader(f)
|
| 13 |
+
for row in reader:
|
| 14 |
+
if row['gloss'].strip().lower() == gloss.strip().lower():
|
| 15 |
+
result.append((row['video_id'], row['npz_dir']))
|
| 16 |
+
return result
|
| 17 |
+
|
| 18 |
+
def run_merge_step1(npz_dir, output_dir="posedict"):
|
| 19 |
+
cmd = [sys.executable, "step1_merge_npz.py", npz_dir, "--output", output_dir]
|
| 20 |
+
ret = subprocess.run(cmd, capture_output=True, text=True)
|
| 21 |
+
return ret.returncode == 0
|
| 22 |
+
|
| 23 |
+
def run_merge_step2(npz_dir, output_dir="posedict"):
|
| 24 |
+
cmd = [sys.executable, "step2_merge_npz.py", npz_dir, "--output", output_dir]
|
| 25 |
+
ret = subprocess.run(cmd, capture_output=True, text=True)
|
| 26 |
+
return ret.returncode == 0
|
| 27 |
+
|
| 28 |
+
def run_render_step3(merged_npz_path, output_folder="pose_videos"):
|
| 29 |
+
cmd = [sys.executable, "step3_read_and_vis_merge_npz_to_pose_video.py", merged_npz_path, "--output", output_folder]
|
| 30 |
+
ret = subprocess.run(cmd, capture_output=True, text=True)
|
| 31 |
+
return ret.returncode == 0
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
parser = argparse.ArgumentParser(description="gloss → npz → merged.npz → pose video pipeline")
|
| 35 |
+
parser.add_argument("--gloss", required=True, help="输入 gloss 关键词")
|
| 36 |
+
parser.add_argument("--csv", default="assets/WLASL_small_results/gloss_npz_mapping.csv", help="gloss→video_id→npz 映射表")
|
| 37 |
+
parser.add_argument("--merge1_out", default="posedict", help="step1 输出合并目录")
|
| 38 |
+
parser.add_argument("--merge2_out", default="posedict", help="step2 输出 merged npz 目录")
|
| 39 |
+
parser.add_argument("--video_out", default="pose_videos", help="step3 输出视频目录")
|
| 40 |
+
args = parser.parse_args()
|
| 41 |
+
|
| 42 |
+
mapping = read_mapping(args.gloss, args.csv)
|
| 43 |
+
if not mapping:
|
| 44 |
+
print(f"❌ 没找到 gloss={args.gloss} 对应路径")
|
| 45 |
+
sys.exit(1)
|
| 46 |
+
|
| 47 |
+
os.makedirs(args.merge1_out, exist_ok=True)
|
| 48 |
+
os.makedirs(args.video_out, exist_ok=True)
|
| 49 |
+
|
| 50 |
+
for video_id, npz_path in mapping:
|
| 51 |
+
if not os.path.isdir(npz_path):
|
| 52 |
+
print(f"[跳过] npz目录不存在: {npz_path}")
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
print(f"\n🔹 处理 video_id={video_id}")
|
| 56 |
+
|
| 57 |
+
# Step1
|
| 58 |
+
print("▶ step1 合并原始 npz")
|
| 59 |
+
if not run_merge_step1(npz_path, args.merge1_out):
|
| 60 |
+
print("❌ step1失败,跳过")
|
| 61 |
+
continue
|
| 62 |
+
|
| 63 |
+
# Step2
|
| 64 |
+
print("▶ step2 再次合并成大npz")
|
| 65 |
+
if not run_merge_step2(npz_path, args.merge2_out):
|
| 66 |
+
print("❌ step2失败,跳过")
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
# Step3
|
| 70 |
+
merged_npz = Path(args.merge2_out) / f"{video_id}.npz"
|
| 71 |
+
if not merged_npz.exists():
|
| 72 |
+
print(f"❌ step2结果不存在: {merged_npz}")
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
print("▶ step3 渲染视频")
|
| 76 |
+
if run_render_step3(str(merged_npz), args.video_out):
|
| 77 |
+
print(f"✅ 渲染完成: {args.video_out}/{video_id}_pose_video.mp4")
|
| 78 |
+
else:
|
| 79 |
+
print("❌ 渲染失败")
|
| 80 |
+
|
| 81 |
+
print("\n🎉 所有流程完成")
|
| 82 |
+
|
| 83 |
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!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
将所有单个视频的npz文件合并成一个大数据库
|
| 4 |
+
从 output/single/*.npz 合并到 output/merge/merged_database.npz
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import argparse
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
import json
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_single_npz(npz_path):
|
| 15 |
+
"""加载一个单独的视频npz文件"""
|
| 16 |
+
try:
|
| 17 |
+
data = np.load(npz_path, allow_pickle=True)
|
| 18 |
+
|
| 19 |
+
# 检查是否有metadata
|
| 20 |
+
if '_metadata' not in data:
|
| 21 |
+
print(f"⚠️ {npz_path.name}: 没有找到metadata")
|
| 22 |
+
return None, None
|
| 23 |
+
|
| 24 |
+
metadata = data['_metadata'].item()
|
| 25 |
+
frame_dict = {}
|
| 26 |
+
|
| 27 |
+
# 重构帧数据
|
| 28 |
+
keys = metadata['original_keys']
|
| 29 |
+
frame_keys = metadata['frame_keys']
|
| 30 |
+
|
| 31 |
+
for frame_key in frame_keys:
|
| 32 |
+
frame_data = {}
|
| 33 |
+
for k in keys:
|
| 34 |
+
combined_key = f"{frame_key}_{k}"
|
| 35 |
+
if combined_key in data:
|
| 36 |
+
frame_data[k] = data[combined_key]
|
| 37 |
+
frame_dict[frame_key] = frame_data
|
| 38 |
+
|
| 39 |
+
return frame_dict, keys
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"❌ 加载失败 {npz_path.name}: {e}")
|
| 43 |
+
return None, None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def merge_all_videos_to_database(single_dir="output/single", output_file="output/merge/merged_database.npz"):
|
| 47 |
+
"""将所有单个视频npz合并成大数据库"""
|
| 48 |
+
|
| 49 |
+
single_path = Path(single_dir)
|
| 50 |
+
output_path = Path(output_file)
|
| 51 |
+
|
| 52 |
+
# 检查输入目录
|
| 53 |
+
if not single_path.exists():
|
| 54 |
+
print(f"❌ 输入目录不存在: {single_dir}")
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
# 获取所有npz文件
|
| 58 |
+
npz_files = list(single_path.glob("*.npz"))
|
| 59 |
+
if not npz_files:
|
| 60 |
+
print(f"❌ 在 {single_dir} 中没有找到npz文件")
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
print(f"📁 找到 {len(npz_files)} 个视频npz文件")
|
| 64 |
+
|
| 65 |
+
# 创建输出目录
|
| 66 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
|
| 68 |
+
# 合并数据
|
| 69 |
+
merged_data = {}
|
| 70 |
+
metadata = {
|
| 71 |
+
"video_index": {},
|
| 72 |
+
"original_keys": [],
|
| 73 |
+
"total_frames": 0,
|
| 74 |
+
"video_count": 0
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
frame_counter = 0
|
| 78 |
+
successful_videos = 0
|
| 79 |
+
failed_videos = []
|
| 80 |
+
|
| 81 |
+
print("🔄 开始合并视频数据...")
|
| 82 |
+
|
| 83 |
+
for npz_file in tqdm(sorted(npz_files), desc="合并视频"):
|
| 84 |
+
video_id = npz_file.stem # 文件名即为video_id
|
| 85 |
+
|
| 86 |
+
# 加载单个视频数据
|
| 87 |
+
frame_dict, keys = load_single_npz(npz_file)
|
| 88 |
+
|
| 89 |
+
if frame_dict is None:
|
| 90 |
+
failed_videos.append(video_id)
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
# 设置original_keys(第一次)
|
| 94 |
+
if not metadata["original_keys"]:
|
| 95 |
+
metadata["original_keys"] = keys
|
| 96 |
+
|
| 97 |
+
# 记录该视频的起始帧
|
| 98 |
+
start_frame = frame_counter
|
| 99 |
+
|
| 100 |
+
# 将帧数据添加到合并数据中
|
| 101 |
+
for local_idx, (frame_key, frame_data) in enumerate(frame_dict.items()):
|
| 102 |
+
new_key = f"frame_{frame_counter:08d}"
|
| 103 |
+
|
| 104 |
+
# 添加所有帧数据
|
| 105 |
+
for k in keys:
|
| 106 |
+
if k in frame_data:
|
| 107 |
+
merged_data[f"{new_key}_{k}"] = frame_data[k]
|
| 108 |
+
|
| 109 |
+
frame_counter += 1
|
| 110 |
+
|
| 111 |
+
end_frame = frame_counter - 1
|
| 112 |
+
|
| 113 |
+
# 记录视频索引信息
|
| 114 |
+
metadata["video_index"][video_id] = {
|
| 115 |
+
"start_frame": start_frame,
|
| 116 |
+
"end_frame": end_frame,
|
| 117 |
+
"frame_count": end_frame - start_frame + 1
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
successful_videos += 1
|
| 121 |
+
|
| 122 |
+
# 完善metadata
|
| 123 |
+
metadata["total_frames"] = frame_counter
|
| 124 |
+
metadata["video_count"] = successful_videos
|
| 125 |
+
merged_data["_metadata"] = metadata
|
| 126 |
+
|
| 127 |
+
# 保存合并后的数据库
|
| 128 |
+
try:
|
| 129 |
+
np.savez_compressed(output_path, **merged_data)
|
| 130 |
+
|
| 131 |
+
print(f"\n✅ 数据库合并完成!")
|
| 132 |
+
print(f" 📊 成功合并: {successful_videos} 个视频")
|
| 133 |
+
print(f" 🎞️ 总帧数: {frame_counter}")
|
| 134 |
+
print(f" 💾 输出文件: {output_path}")
|
| 135 |
+
print(f" 📦 文件大小: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
|
| 136 |
+
|
| 137 |
+
if failed_videos:
|
| 138 |
+
print(f" ⚠️ 失败视频: {len(failed_videos)} 个")
|
| 139 |
+
if len(failed_videos) <= 10:
|
| 140 |
+
print(f" 失败列表: {failed_videos}")
|
| 141 |
+
|
| 142 |
+
return True
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"❌ 保存数据库失败: {e}")
|
| 146 |
+
return False
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def verify_database(database_path="output/merge/merged_database.npz",
|
| 150 |
+
mapping_path="output/gloss_mapping.json"):
|
| 151 |
+
"""验证数据库完整性"""
|
| 152 |
+
print(f"\n🔍 验证数据库完整性...")
|
| 153 |
+
|
| 154 |
+
try:
|
| 155 |
+
# 加载数据库
|
| 156 |
+
data = np.load(database_path, allow_pickle=True)
|
| 157 |
+
metadata = data['_metadata'].item()
|
| 158 |
+
|
| 159 |
+
print(f"✅ 数据库基本信息:")
|
| 160 |
+
print(f" 总视频数: {metadata['video_count']}")
|
| 161 |
+
print(f" 总帧数: {metadata['total_frames']}")
|
| 162 |
+
print(f" 数据维度: {len(metadata['original_keys'])} 个原始key")
|
| 163 |
+
|
| 164 |
+
# 验证帧数据完整性
|
| 165 |
+
print(f"\n🔍 验证帧数据完整性...")
|
| 166 |
+
original_keys = metadata['original_keys']
|
| 167 |
+
missing_frames = 0
|
| 168 |
+
|
| 169 |
+
for frame_idx in range(min(100, metadata['total_frames'])): # 检查前100帧
|
| 170 |
+
frame_key = f"frame_{frame_idx:08d}"
|
| 171 |
+
frame_complete = True
|
| 172 |
+
|
| 173 |
+
for key in original_keys:
|
| 174 |
+
combined_key = f"{frame_key}_{key}"
|
| 175 |
+
if combined_key not in data:
|
| 176 |
+
frame_complete = False
|
| 177 |
+
break
|
| 178 |
+
|
| 179 |
+
if not frame_complete:
|
| 180 |
+
missing_frames += 1
|
| 181 |
+
|
| 182 |
+
if missing_frames == 0:
|
| 183 |
+
print(f" ✅ 前100帧数据完整")
|
| 184 |
+
else:
|
| 185 |
+
print(f" ⚠️ 前100帧中有 {missing_frames} 帧数据不完整")
|
| 186 |
+
|
| 187 |
+
# 验证视频索引
|
| 188 |
+
print(f"\n🔍 验证视频索引...")
|
| 189 |
+
video_index = metadata['video_index']
|
| 190 |
+
total_indexed_frames = sum(
|
| 191 |
+
info['frame_count'] for info in video_index.values()
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
if total_indexed_frames == metadata['total_frames']:
|
| 195 |
+
print(f" ✅ 视频索引帧数一致: {total_indexed_frames}")
|
| 196 |
+
else:
|
| 197 |
+
print(f" ⚠️ 视频索引帧数不一致: 索引={total_indexed_frames}, 实际={metadata['total_frames']}")
|
| 198 |
+
|
| 199 |
+
# 与映射文件对比
|
| 200 |
+
if Path(mapping_path).exists():
|
| 201 |
+
try:
|
| 202 |
+
with open(mapping_path, 'r', encoding='utf-8') as f:
|
| 203 |
+
gloss_mapping = json.load(f)
|
| 204 |
+
|
| 205 |
+
# 收集映射中的所有video_id
|
| 206 |
+
mapping_video_ids = set()
|
| 207 |
+
for videos in gloss_mapping.values():
|
| 208 |
+
if isinstance(videos, list):
|
| 209 |
+
mapping_video_ids.update(videos)
|
| 210 |
+
else:
|
| 211 |
+
mapping_video_ids.add(videos)
|
| 212 |
+
|
| 213 |
+
db_video_ids = set(video_index.keys())
|
| 214 |
+
|
| 215 |
+
matched = mapping_video_ids & db_video_ids
|
| 216 |
+
missing_in_db = mapping_video_ids - db_video_ids
|
| 217 |
+
extra_in_db = db_video_ids - mapping_video_ids
|
| 218 |
+
|
| 219 |
+
print(f"\n🔍 与映射文件对比:")
|
| 220 |
+
print(f" 映射中视频数: {len(mapping_video_ids)}")
|
| 221 |
+
print(f" 数据库中视频数: {len(db_video_ids)}")
|
| 222 |
+
print(f" 匹配视频数: {len(matched)}")
|
| 223 |
+
|
| 224 |
+
if missing_in_db:
|
| 225 |
+
print(f" ⚠️ 映射中有但数据库缺失: {len(missing_in_db)} 个")
|
| 226 |
+
if len(missing_in_db) <= 5:
|
| 227 |
+
print(f" {list(missing_in_db)}")
|
| 228 |
+
|
| 229 |
+
if extra_in_db:
|
| 230 |
+
print(f" ℹ️ 数据库中有但映射缺失: {len(extra_in_db)} 个")
|
| 231 |
+
if len(extra_in_db) <= 5:
|
| 232 |
+
print(f" {list(extra_in_db)}")
|
| 233 |
+
|
| 234 |
+
if len(matched) == len(mapping_video_ids) == len(db_video_ids):
|
| 235 |
+
print(f" ✅ 映射与数据库完全一致!")
|
| 236 |
+
|
| 237 |
+
except Exception as e:
|
| 238 |
+
print(f" ⚠️ 映射文件验证失败: {e}")
|
| 239 |
+
|
| 240 |
+
print(f"\n✅ 数据库验证完成!")
|
| 241 |
+
return True
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
print(f"❌ 数据库验证失败: {e}")
|
| 245 |
+
return False
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def generate_database_summary(database_path="output/merge/merged_database.npz",
|
| 249 |
+
output_path="output/database_summary.txt"):
|
| 250 |
+
"""生成数据库摘要报告"""
|
| 251 |
+
try:
|
| 252 |
+
data = np.load(database_path, allow_pickle=True)
|
| 253 |
+
metadata = data['_metadata'].item()
|
| 254 |
+
|
| 255 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 256 |
+
f.write("手语数据库摘要报告\n")
|
| 257 |
+
f.write("=" * 50 + "\n\n")
|
| 258 |
+
|
| 259 |
+
f.write(f"数据库文件: {database_path}\n")
|
| 260 |
+
f.write(f"生成时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
|
| 261 |
+
|
| 262 |
+
f.write("基本统计:\n")
|
| 263 |
+
f.write(f" 总视频数: {metadata['video_count']}\n")
|
| 264 |
+
f.write(f" 总帧数: {metadata['total_frames']}\n")
|
| 265 |
+
f.write(f" 平均每视频帧数: {metadata['total_frames'] / metadata['video_count']:.1f}\n")
|
| 266 |
+
f.write(f" 数据维度: {len(metadata['original_keys'])} 个key\n\n")
|
| 267 |
+
|
| 268 |
+
f.write("数据key类型:\n")
|
| 269 |
+
for key in metadata['original_keys']:
|
| 270 |
+
f.write(f" - {key}\n")
|
| 271 |
+
f.write("\n")
|
| 272 |
+
|
| 273 |
+
f.write("视频索引 (前20个):\n")
|
| 274 |
+
for i, (video_id, info) in enumerate(list(metadata['video_index'].items())[:20]):
|
| 275 |
+
f.write(f" {video_id}: 帧 {info['start_frame']}-{info['end_frame']} ({info['frame_count']} 帧)\n")
|
| 276 |
+
|
| 277 |
+
if len(metadata['video_index']) > 20:
|
| 278 |
+
f.write(f" ... 还有 {len(metadata['video_index']) - 20} 个���频\n")
|
| 279 |
+
|
| 280 |
+
print(f"📝 数据库摘要已保存: {output_path}")
|
| 281 |
+
return True
|
| 282 |
+
|
| 283 |
+
except Exception as e:
|
| 284 |
+
print(f"❌ 生成摘要失败: {e}")
|
| 285 |
+
return False
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def main():
|
| 289 |
+
parser = argparse.ArgumentParser(description='将所有视频npz合并成大数据库')
|
| 290 |
+
parser.add_argument('--input', '-i', default='output/single',
|
| 291 |
+
help='输入目录 (默认: output/single)')
|
| 292 |
+
parser.add_argument('--output', '-o', default='output/merge/merged_database.npz',
|
| 293 |
+
help='输出数据库文件 (默认: output/merge/merged_database.npz)')
|
| 294 |
+
parser.add_argument('--verify', action='store_true',
|
| 295 |
+
help='验证生成的数据库')
|
| 296 |
+
parser.add_argument('--summary', action='store_true',
|
| 297 |
+
help='生成数据库摘要报告')
|
| 298 |
+
|
| 299 |
+
args = parser.parse_args()
|
| 300 |
+
|
| 301 |
+
# 检查输入目录
|
| 302 |
+
if not Path(args.input).exists():
|
| 303 |
+
print(f"❌ 输入目录不存在: {args.input}")
|
| 304 |
+
print(" 请先运行 batch_merge_videos.py 生成单个视频npz文件")
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
# 执行合并
|
| 308 |
+
success = merge_all_videos_to_database(args.input, args.output)
|
| 309 |
+
|
| 310 |
+
if not success:
|
| 311 |
+
print("❌ 数据库合并失败!")
|
| 312 |
+
return
|
| 313 |
+
|
| 314 |
+
# 验证数据库
|
| 315 |
+
if args.verify or True: # 默认总是验证
|
| 316 |
+
verify_database(args.output)
|
| 317 |
+
|
| 318 |
+
# 生成摘要报告
|
| 319 |
+
if args.summary or True: # 默认总是生成摘要
|
| 320 |
+
summary_path = Path(args.output).parent / "database_summary.txt"
|
| 321 |
+
generate_database_summary(args.output, summary_path)
|
| 322 |
+
|
| 323 |
+
print(f"\n🎉 数据库生成任务完成!")
|
| 324 |
+
print(f"📁 数据库文件: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
手语数据预处理主控脚本 - 支持数据集路径参数
|
| 4 |
+
自动化执行完整的数据预处理流程
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import argparse
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def run_command(cmd, description):
|
| 16 |
+
"""执行命令并显示进度"""
|
| 17 |
+
print(f"\n{'=' * 60}")
|
| 18 |
+
print(f"🔄 {description}")
|
| 19 |
+
print(f"{'=' * 60}")
|
| 20 |
+
print(f"命令: {' '.join(cmd)}")
|
| 21 |
+
|
| 22 |
+
start_time = time.time()
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
result = subprocess.run(cmd, check=True, text=True, capture_output=False)
|
| 26 |
+
elapsed = time.time() - start_time
|
| 27 |
+
print(f"\n✅ {description} 完成! (耗时: {elapsed:.1f}秒)")
|
| 28 |
+
return True
|
| 29 |
+
except subprocess.CalledProcessError as e:
|
| 30 |
+
elapsed = time.time() - start_time
|
| 31 |
+
print(f"\n❌ {description} 失败! (耗时: {elapsed:.1f}秒)")
|
| 32 |
+
print(f"错误码: {e.returncode}")
|
| 33 |
+
return False
|
| 34 |
+
except Exception as e:
|
| 35 |
+
elapsed = time.time() - start_time
|
| 36 |
+
print(f"\n❌ {description} 异常! (耗时: {elapsed:.1f}秒)")
|
| 37 |
+
print(f"异常信息: {e}")
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def check_prerequisites(dataset_root):
|
| 42 |
+
"""检查前置条件"""
|
| 43 |
+
print("🔍 检查前置条件...")
|
| 44 |
+
|
| 45 |
+
required_files = [
|
| 46 |
+
"step2_merge_npz.py",
|
| 47 |
+
"extract_gloss_mapping.py",
|
| 48 |
+
"batch_merge_videos.py",
|
| 49 |
+
"merge_all_to_database.py",
|
| 50 |
+
"qa_system.py"
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
missing_files = []
|
| 54 |
+
for file_path in required_files:
|
| 55 |
+
if not Path(file_path).exists():
|
| 56 |
+
missing_files.append(file_path)
|
| 57 |
+
|
| 58 |
+
if missing_files:
|
| 59 |
+
print("❌ 缺少必要文件:")
|
| 60 |
+
for file_path in missing_files:
|
| 61 |
+
print(f" - {file_path}")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
# 检查数据集根目录
|
| 65 |
+
dataset_path = Path(dataset_root)
|
| 66 |
+
if not dataset_path.exists():
|
| 67 |
+
print(f"❌ 数据集根目录不存在: {dataset_root}")
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
# 检查train.json是否存在
|
| 71 |
+
train_json_path = dataset_path / "train.json"
|
| 72 |
+
if not train_json_path.exists():
|
| 73 |
+
print(f"❌ train.json 文件不存在: {train_json_path}")
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
import json
|
| 78 |
+
with open(train_json_path, 'r') as f:
|
| 79 |
+
data = json.load(f)
|
| 80 |
+
if not data:
|
| 81 |
+
print("❌ train.json 文件为空")
|
| 82 |
+
return False
|
| 83 |
+
print(f"✅ train.json 包含 {len(data)} 个条目")
|
| 84 |
+
|
| 85 |
+
# 检查是否有视频目录
|
| 86 |
+
video_dirs = [d for d in dataset_path.iterdir() if d.is_dir() and d.name != '__pycache__']
|
| 87 |
+
print(f"✅ 数据集目录包含 {len(video_dirs)} 个视频目录")
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"❌ train.json 文件格式错误: {e}")
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
print("✅ 所有前置条件满足")
|
| 94 |
+
return True
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def check_directory_structure():
|
| 98 |
+
"""检查并创建目录结构"""
|
| 99 |
+
print("\n📁 检查目录结构...")
|
| 100 |
+
|
| 101 |
+
required_dirs = [
|
| 102 |
+
"output",
|
| 103 |
+
"output/single",
|
| 104 |
+
"output/merge",
|
| 105 |
+
"output/video"
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
for dir_path in required_dirs:
|
| 109 |
+
Path(dir_path).mkdir(parents=True, exist_ok=True)
|
| 110 |
+
print(f"✅ {dir_path}")
|
| 111 |
+
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def step1_extract_mapping(dataset_root):
|
| 116 |
+
"""步骤1: 提取gloss映射"""
|
| 117 |
+
cmd = [sys.executable, "extract_gloss_mapping.py", "--dataset-root", dataset_root]
|
| 118 |
+
return run_command(cmd, "步骤1: 提取Gloss映射")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def step2_batch_merge():
|
| 122 |
+
"""步骤2: 批量合并视频npz"""
|
| 123 |
+
cmd = [sys.executable, "batch_merge_videos.py", "--verify"]
|
| 124 |
+
return run_command(cmd, "步骤2: 批量合并视频NPZ文件")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def step3_merge_database():
|
| 128 |
+
"""步骤3: 合并成大数据库"""
|
| 129 |
+
cmd = [sys.executable, "merge_all_to_database.py", "--verify", "--summary"]
|
| 130 |
+
return run_command(cmd, "步骤3: 合并成大数据库")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def verify_final_output():
|
| 134 |
+
"""验证最终输出"""
|
| 135 |
+
print(f"\n🔍 验证最终输出...")
|
| 136 |
+
|
| 137 |
+
required_outputs = [
|
| 138 |
+
"output/gloss_mapping.json",
|
| 139 |
+
"output/gloss_video_mapping.csv",
|
| 140 |
+
"output/merge/merged_database.npz"
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
all_exist = True
|
| 144 |
+
for output_path in required_outputs:
|
| 145 |
+
if Path(output_path).exists():
|
| 146 |
+
size = Path(output_path).stat().st_size / 1024 / 1024
|
| 147 |
+
print(f"✅ {output_path} ({size:.2f} MB)")
|
| 148 |
+
else:
|
| 149 |
+
print(f"❌ {output_path} 不存在")
|
| 150 |
+
all_exist = False
|
| 151 |
+
|
| 152 |
+
# 检查single目录中的文件数量
|
| 153 |
+
single_dir = Path("output/single")
|
| 154 |
+
if single_dir.exists():
|
| 155 |
+
npz_files = list(single_dir.glob("*.npz"))
|
| 156 |
+
print(f"✅ output/single/ 包含 {len(npz_files)} 个视频NPZ文件")
|
| 157 |
+
else:
|
| 158 |
+
print(f"❌ output/single/ 目录不存在")
|
| 159 |
+
all_exist = False
|
| 160 |
+
|
| 161 |
+
return all_exist
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def show_completion_summary(dataset_root):
|
| 165 |
+
"""显���完成摘要"""
|
| 166 |
+
print(f"\n{'=' * 60}")
|
| 167 |
+
print(f"🎉 数据预处理完成!")
|
| 168 |
+
print(f"{'=' * 60}")
|
| 169 |
+
|
| 170 |
+
print(f"📁 输入数据集: {dataset_root}")
|
| 171 |
+
print(f"📁 生成的文件:")
|
| 172 |
+
print(f" 📊 映射文件:")
|
| 173 |
+
print(f" - output/gloss_mapping.json")
|
| 174 |
+
print(f" - output/gloss_video_mapping.csv")
|
| 175 |
+
print(f" 🎬 视频NPZ文件:")
|
| 176 |
+
print(f" - output/single/*.npz (单个视频)")
|
| 177 |
+
print(f" - output/merge/merged_database.npz (合并数据库)")
|
| 178 |
+
print(f" 📝 报告文件:")
|
| 179 |
+
print(f" - output/database_summary.txt")
|
| 180 |
+
|
| 181 |
+
print(f"\n🚀 下一步:")
|
| 182 |
+
print(f" 运行QA系统: python qa_system.py")
|
| 183 |
+
print(f" 或命令行模式: python qa_system.py --gloss \"HELLO WORLD\"")
|
| 184 |
+
|
| 185 |
+
print(f"\n💡 提示:")
|
| 186 |
+
print(f" - QA系统会自动加载生成的数据库和映射文件")
|
| 187 |
+
print(f" - 生成的视频将保存在 output/video/ 目录")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
parser = argparse.ArgumentParser(description='手语数据预处理主控脚本')
|
| 192 |
+
parser.add_argument('--dataset-root', '-d',
|
| 193 |
+
default='assets/WLASL_small_results',
|
| 194 |
+
help='数据集根目录路径 (默认: assets/WLASL_small_results)')
|
| 195 |
+
parser.add_argument('--skip-step1', action='store_true',
|
| 196 |
+
help='跳过步骤1 (提取映射)')
|
| 197 |
+
parser.add_argument('--skip-step2', action='store_true',
|
| 198 |
+
help='跳过步骤2 (批量合并)')
|
| 199 |
+
parser.add_argument('--skip-step3', action='store_true',
|
| 200 |
+
help='跳过步骤3 (合并数据库)')
|
| 201 |
+
parser.add_argument('--only-verify', action='store_true',
|
| 202 |
+
help='仅验证输出文件')
|
| 203 |
+
|
| 204 |
+
args = parser.parse_args()
|
| 205 |
+
|
| 206 |
+
print("🤖 手语数据预处理管道")
|
| 207 |
+
print("=" * 60)
|
| 208 |
+
print(f"📁 数据集路径: {args.dataset_root}")
|
| 209 |
+
|
| 210 |
+
# 仅验证模式
|
| 211 |
+
if args.only_verify:
|
| 212 |
+
if verify_final_output():
|
| 213 |
+
print("\n✅ 所有输出文件都存在且正确!")
|
| 214 |
+
show_completion_summary(args.dataset_root)
|
| 215 |
+
else:
|
| 216 |
+
print("\n❌ 输出文件验证失败!")
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
# 检查前置条件
|
| 220 |
+
if not check_prerequisites(args.dataset_root):
|
| 221 |
+
print("\n❌ 前置条件检查失败,请检查数据集路径和必要文件!")
|
| 222 |
+
sys.exit(1)
|
| 223 |
+
|
| 224 |
+
# 检查并创建目录结构
|
| 225 |
+
if not check_directory_structure():
|
| 226 |
+
print("\n❌ 目录结构创建失败!")
|
| 227 |
+
sys.exit(1)
|
| 228 |
+
|
| 229 |
+
total_start_time = time.time()
|
| 230 |
+
failed_steps = []
|
| 231 |
+
|
| 232 |
+
# 执行预处理步骤
|
| 233 |
+
if not args.skip_step1:
|
| 234 |
+
if not step1_extract_mapping(args.dataset_root):
|
| 235 |
+
failed_steps.append("步骤1: 提取映射")
|
| 236 |
+
else:
|
| 237 |
+
print("\n⏭️ 跳过步骤1: 提取映射")
|
| 238 |
+
|
| 239 |
+
if not args.skip_step2 and "步骤1: 提取映射" not in failed_steps:
|
| 240 |
+
if not step2_batch_merge():
|
| 241 |
+
failed_steps.append("步骤2: 批量合并")
|
| 242 |
+
else:
|
| 243 |
+
if args.skip_step2:
|
| 244 |
+
print("\n⏭️ 跳过步骤2: 批量合并")
|
| 245 |
+
|
| 246 |
+
if not args.skip_step3 and "步骤2: 批量合并" not in failed_steps:
|
| 247 |
+
if not step3_merge_database():
|
| 248 |
+
failed_steps.append("步骤3: 合并数据库")
|
| 249 |
+
else:
|
| 250 |
+
if args.skip_step3:
|
| 251 |
+
print("\n⏭️ 跳过步骤3: 合并数据库")
|
| 252 |
+
|
| 253 |
+
total_elapsed = time.time() - total_start_time
|
| 254 |
+
|
| 255 |
+
# 最终验证
|
| 256 |
+
if not failed_steps:
|
| 257 |
+
print(f"\n🔍 最终验证...")
|
| 258 |
+
if verify_final_output():
|
| 259 |
+
print(f"\n🎉 所有步骤执行成功! (总耗时: {total_elapsed / 60:.1f}分钟)")
|
| 260 |
+
show_completion_summary(args.dataset_root)
|
| 261 |
+
else:
|
| 262 |
+
print(f"\n⚠️ 步骤执行完成但输出验证失败!")
|
| 263 |
+
else:
|
| 264 |
+
print(f"\n❌ 以下步骤执行失败:")
|
| 265 |
+
for step in failed_steps:
|
| 266 |
+
print(f" - {step}")
|
| 267 |
+
print(f"\n总耗时: {total_elapsed / 60:.1f}分钟")
|
| 268 |
+
|
| 269 |
+
print(f"\n💡 故障排除建议:")
|
| 270 |
+
print(f" 1. 检查错误信息并修复问题")
|
| 271 |
+
print(f" 2. 使用 --skip-stepX 跳过已完成的步骤")
|
| 272 |
+
print(f" 3. 使用 --only-verify 验证现有输出")
|
| 273 |
+
print(f" 4. 检查数据集路径: {args.dataset_root}")
|
| 274 |
+
|
| 275 |
+
sys.exit(1)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
main()
|
qa_system.py
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
手语Gloss问答系统
|
| 4 |
+
用户输入gloss,系统生成对应的pose视频
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import numpy as np
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import argparse
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import cv2
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
from easy_dwpose import DWposeDetector
|
| 20 |
+
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
| 21 |
+
|
| 22 |
+
# 固定配置
|
| 23 |
+
DATABASE_PATH = "output/merge/merged_database.npz" # 数据库文件路径
|
| 24 |
+
MAPPING_FILE = "output/gloss_mapping.json" # 映射文件路径
|
| 25 |
+
OUTPUT_DIR = "output/video" # 输出视频目录
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SignLanguageQA:
|
| 29 |
+
def __init__(self):
|
| 30 |
+
self.data = None
|
| 31 |
+
self.metadata = None
|
| 32 |
+
self.gloss_mapping = None
|
| 33 |
+
self.load_database()
|
| 34 |
+
self.load_mapping()
|
| 35 |
+
|
| 36 |
+
def load_database(self):
|
| 37 |
+
"""加载数据库"""
|
| 38 |
+
try:
|
| 39 |
+
if not Path(DATABASE_PATH).exists():
|
| 40 |
+
print(f"❌ 数据库文件不存在: {DATABASE_PATH}")
|
| 41 |
+
print(" 请确保已运行 merge_all_to_database.py 生成数据库文件")
|
| 42 |
+
sys.exit(1)
|
| 43 |
+
|
| 44 |
+
print(f"📚 正在加载数据库: {DATABASE_PATH}")
|
| 45 |
+
self.data = np.load(DATABASE_PATH, allow_pickle=True)
|
| 46 |
+
self.metadata = self.data['_metadata'].item()
|
| 47 |
+
|
| 48 |
+
print(f"✅ 数据库加载成功!")
|
| 49 |
+
print(f" 📊 总帧数: {self.metadata['total_frames']}")
|
| 50 |
+
print(f" 🎬 视频数量: {self.metadata['video_count']}")
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"❌ 数据库加载失败: {e}")
|
| 54 |
+
sys.exit(1)
|
| 55 |
+
|
| 56 |
+
def load_mapping(self):
|
| 57 |
+
"""加载gloss映射文件"""
|
| 58 |
+
if Path(MAPPING_FILE).exists():
|
| 59 |
+
try:
|
| 60 |
+
with open(MAPPING_FILE, 'r', encoding='utf-8') as f:
|
| 61 |
+
self.gloss_mapping = json.load(f)
|
| 62 |
+
print(f"✅ 映射文件加载成功: {MAPPING_FILE}")
|
| 63 |
+
print(f" 📝 包含 {len(self.gloss_mapping)} 个gloss映射")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"⚠️ 映射文件加载失败: {e}")
|
| 66 |
+
self.gloss_mapping = None
|
| 67 |
+
else:
|
| 68 |
+
print(f"ℹ️ 映射文件不存在: {MAPPING_FILE}")
|
| 69 |
+
print(" 将使用智能匹配模式")
|
| 70 |
+
self.gloss_mapping = None
|
| 71 |
+
|
| 72 |
+
def find_gloss_videos(self, gloss):
|
| 73 |
+
"""根据单个gloss找到对应的video_ids"""
|
| 74 |
+
if self.gloss_mapping and gloss.upper() in self.gloss_mapping:
|
| 75 |
+
# 使用映射文件
|
| 76 |
+
video_ids = self.gloss_mapping[gloss.upper()]
|
| 77 |
+
if not isinstance(video_ids, list):
|
| 78 |
+
video_ids = [video_ids]
|
| 79 |
+
return video_ids
|
| 80 |
+
else:
|
| 81 |
+
# 智能匹配模式
|
| 82 |
+
gloss_upper = gloss.upper()
|
| 83 |
+
matched_videos = []
|
| 84 |
+
|
| 85 |
+
for video_id in self.metadata['video_index'].keys():
|
| 86 |
+
# 多种匹配策略
|
| 87 |
+
if (gloss_upper == video_id.upper() or
|
| 88 |
+
gloss_upper in video_id.upper() or
|
| 89 |
+
video_id.upper().endswith(f"_{gloss_upper}") or
|
| 90 |
+
video_id.upper().startswith(f"{gloss_upper}_") or
|
| 91 |
+
f"_{gloss_upper}_" in video_id.upper()):
|
| 92 |
+
matched_videos.append(video_id)
|
| 93 |
+
|
| 94 |
+
return matched_videos
|
| 95 |
+
|
| 96 |
+
def get_frames_for_glosses(self, gloss_list, one_video_per_gloss=True):
|
| 97 |
+
"""获取gloss列表对应的所有帧
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
gloss_list: gloss列表
|
| 101 |
+
one_video_per_gloss: 是否每个gloss只选择一个视频
|
| 102 |
+
"""
|
| 103 |
+
all_frame_groups = [] # 按gloss分组的帧
|
| 104 |
+
video_info = []
|
| 105 |
+
|
| 106 |
+
for gloss in gloss_list:
|
| 107 |
+
matched_videos = self.find_gloss_videos(gloss)
|
| 108 |
+
|
| 109 |
+
if matched_videos:
|
| 110 |
+
print(f"🎯 '{gloss}' -> 找到 {len(matched_videos)} 个视频")
|
| 111 |
+
|
| 112 |
+
# 如果只选择一个视频,找第一个有效的(在数据库中存在的)
|
| 113 |
+
videos_to_use = []
|
| 114 |
+
if one_video_per_gloss:
|
| 115 |
+
# 找到第一个在数据库中存在的视频
|
| 116 |
+
for video_id in matched_videos:
|
| 117 |
+
if video_id in self.metadata['video_index']:
|
| 118 |
+
videos_to_use = [video_id]
|
| 119 |
+
if len(matched_videos) > 1:
|
| 120 |
+
print(f" 💡 选择第一个有效视频: {video_id},跳过其他 {len(matched_videos) - 1} 个")
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
if not videos_to_use:
|
| 124 |
+
print(f" ❌ 没有找到有效的视频(所有video_id都不在数据库中)")
|
| 125 |
+
continue
|
| 126 |
+
else:
|
| 127 |
+
videos_to_use = matched_videos
|
| 128 |
+
|
| 129 |
+
gloss_frames = [] # 当前gloss的所有帧
|
| 130 |
+
for video_id in videos_to_use:
|
| 131 |
+
if video_id in self.metadata['video_index']:
|
| 132 |
+
start_frame = self.metadata['video_index'][video_id]['start_frame']
|
| 133 |
+
end_frame = self.metadata['video_index'][video_id]['end_frame']
|
| 134 |
+
frames = list(range(start_frame, end_frame + 1))
|
| 135 |
+
gloss_frames.extend(frames)
|
| 136 |
+
video_info.append({
|
| 137 |
+
'gloss': gloss,
|
| 138 |
+
'video_id': video_id,
|
| 139 |
+
'start_frame': start_frame,
|
| 140 |
+
'end_frame': end_frame,
|
| 141 |
+
'frame_count': len(frames)
|
| 142 |
+
})
|
| 143 |
+
print(f" 📹 {video_id}: {len(frames)} 帧 ({start_frame}-{end_frame})")
|
| 144 |
+
else:
|
| 145 |
+
print(f" ⚠️ {video_id}: 在数据库中未找到")
|
| 146 |
+
|
| 147 |
+
if gloss_frames:
|
| 148 |
+
all_frame_groups.append(gloss_frames)
|
| 149 |
+
else:
|
| 150 |
+
print(f"❌ '{gloss}' -> 未找到匹配视频")
|
| 151 |
+
self.suggest_similar_glosses(gloss)
|
| 152 |
+
|
| 153 |
+
# 按顺序拼接所有gloss的帧
|
| 154 |
+
all_frames = []
|
| 155 |
+
for frame_group in all_frame_groups:
|
| 156 |
+
all_frames.extend(frame_group)
|
| 157 |
+
|
| 158 |
+
return all_frames, video_info
|
| 159 |
+
|
| 160 |
+
def suggest_similar_glosses(self, gloss):
|
| 161 |
+
"""为未找到的gloss提供相似建议"""
|
| 162 |
+
gloss_upper = gloss.upper()
|
| 163 |
+
similar_videos = []
|
| 164 |
+
|
| 165 |
+
# 查找包含部分字符的video_id
|
| 166 |
+
for video_id in self.metadata['video_index'].keys():
|
| 167 |
+
score = 0
|
| 168 |
+
for char in gloss_upper:
|
| 169 |
+
if char in video_id.upper():
|
| 170 |
+
score += 1
|
| 171 |
+
|
| 172 |
+
if score >= len(gloss_upper) * 0.5: # 至少50%字符匹配
|
| 173 |
+
similar_videos.append(video_id)
|
| 174 |
+
|
| 175 |
+
if similar_videos:
|
| 176 |
+
print(f" 💡 相似的video_id: {similar_videos[:5]}")
|
| 177 |
+
|
| 178 |
+
# 如果有映射文件,显示可用的gloss
|
| 179 |
+
if self.gloss_mapping:
|
| 180 |
+
available_glosses = list(self.gloss_mapping.keys())
|
| 181 |
+
similar_glosses = [g for g in available_glosses if
|
| 182 |
+
any(char in g for char in gloss_upper)]
|
| 183 |
+
if similar_glosses:
|
| 184 |
+
print(f" 💡 相似的gloss: {similar_glosses[:5]}")
|
| 185 |
+
|
| 186 |
+
def create_pose_frame(self, frame_data, width=480, height=480):
|
| 187 |
+
"""创建单帧pose图像"""
|
| 188 |
+
try:
|
| 189 |
+
processed_pred = process_pose_data(frame_data, height, width)
|
| 190 |
+
|
| 191 |
+
vis_img = draw_pose(
|
| 192 |
+
pose=processed_pred,
|
| 193 |
+
H=height,
|
| 194 |
+
W=width,
|
| 195 |
+
include_body=True,
|
| 196 |
+
include_hand=True,
|
| 197 |
+
include_face=True
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
return vis_img.transpose(1, 2, 0)
|
| 201 |
+
|
| 202 |
+
except Exception as e:
|
| 203 |
+
print(f"⚠️ 创建pose帧失败: {e}")
|
| 204 |
+
return None
|
| 205 |
+
|
| 206 |
+
def generate_video(self, frame_indices, output_path, video_info, fps=30, width=480, height=480,
|
| 207 |
+
smoothing_frames=5, smoothing_method='none'):
|
| 208 |
+
"""生成pose视频
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
frame_indices: 帧索引列表
|
| 212 |
+
output_path: 输出路径
|
| 213 |
+
video_info: 视频信息列表
|
| 214 |
+
fps: 帧率
|
| 215 |
+
width: 宽度
|
| 216 |
+
height: 高度
|
| 217 |
+
smoothing_frames: 平滑过渡帧数
|
| 218 |
+
smoothing_method: 平滑方法 ('fade', 'blend', 'pause', 'none')
|
| 219 |
+
"""
|
| 220 |
+
if not frame_indices:
|
| 221 |
+
return False
|
| 222 |
+
|
| 223 |
+
# 创建输出目录
|
| 224 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 225 |
+
|
| 226 |
+
# 设置视频编码器
|
| 227 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 228 |
+
video_writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 229 |
+
|
| 230 |
+
if not video_writer.isOpened():
|
| 231 |
+
print("❌ 无法创建视频文件")
|
| 232 |
+
return False
|
| 233 |
+
|
| 234 |
+
original_keys = self.metadata['original_keys']
|
| 235 |
+
successful_frames = 0
|
| 236 |
+
|
| 237 |
+
print(f"🎬 正在生成视频 (平滑方式: {smoothing_method})...")
|
| 238 |
+
|
| 239 |
+
# 按gloss分组生成pose帧
|
| 240 |
+
all_pose_frame_groups = []
|
| 241 |
+
|
| 242 |
+
print("🔄 渲染pose帧...")
|
| 243 |
+
current_frame_idx = 0
|
| 244 |
+
|
| 245 |
+
for info in video_info:
|
| 246 |
+
gloss_frames = []
|
| 247 |
+
frame_count = info['frame_count']
|
| 248 |
+
|
| 249 |
+
for _ in range(frame_count):
|
| 250 |
+
if current_frame_idx < len(frame_indices):
|
| 251 |
+
frame_idx = frame_indices[current_frame_idx]
|
| 252 |
+
frame_key = f"frame_{frame_idx:08d}"
|
| 253 |
+
frame_data = {}
|
| 254 |
+
|
| 255 |
+
for key in original_keys:
|
| 256 |
+
combined_key = f"{frame_key}_{key}"
|
| 257 |
+
if combined_key in self.data:
|
| 258 |
+
frame_data[key] = self.data[combined_key]
|
| 259 |
+
|
| 260 |
+
if frame_data:
|
| 261 |
+
pose_frame = self.create_pose_frame(frame_data, width, height)
|
| 262 |
+
if pose_frame is not None:
|
| 263 |
+
gloss_frames.append(pose_frame)
|
| 264 |
+
|
| 265 |
+
current_frame_idx += 1
|
| 266 |
+
|
| 267 |
+
if gloss_frames:
|
| 268 |
+
all_pose_frame_groups.append(gloss_frames)
|
| 269 |
+
print(f" ✅ {info['gloss']}: {len(gloss_frames)} 帧")
|
| 270 |
+
|
| 271 |
+
if not all_pose_frame_groups:
|
| 272 |
+
print("❌ 没有成功生成任何帧")
|
| 273 |
+
video_writer.release()
|
| 274 |
+
return False
|
| 275 |
+
|
| 276 |
+
# 应用平滑处理
|
| 277 |
+
if smoothing_method != 'none' and len(all_pose_frame_groups) > 1:
|
| 278 |
+
final_frames = self.apply_group_smoothing(all_pose_frame_groups, smoothing_frames, smoothing_method)
|
| 279 |
+
else:
|
| 280 |
+
# 直接拼接所有帧
|
| 281 |
+
final_frames = []
|
| 282 |
+
for group in all_pose_frame_groups:
|
| 283 |
+
final_frames.extend(group)
|
| 284 |
+
|
| 285 |
+
# 写入视频
|
| 286 |
+
print("💾 写入视频文件...")
|
| 287 |
+
for pose_frame in tqdm(final_frames, desc="写入帧"):
|
| 288 |
+
pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
|
| 289 |
+
video_writer.write(pose_frame_bgr)
|
| 290 |
+
successful_frames += 1
|
| 291 |
+
|
| 292 |
+
video_writer.release()
|
| 293 |
+
|
| 294 |
+
if successful_frames > 0:
|
| 295 |
+
print(f"✅ 视频生成成功!")
|
| 296 |
+
print(f" 📁 文件: {output_path}")
|
| 297 |
+
print(f" 📊 {successful_frames} 帧, {fps}fps, {width}x{height}")
|
| 298 |
+
if output_path.exists():
|
| 299 |
+
print(f" 💾 大小: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
|
| 300 |
+
return True
|
| 301 |
+
else:
|
| 302 |
+
print(f"❌ 视频生成失败")
|
| 303 |
+
return False
|
| 304 |
+
|
| 305 |
+
def apply_group_smoothing(self, frame_groups, smoothing_frames, method):
|
| 306 |
+
"""对gloss分组应用平滑过渡效果"""
|
| 307 |
+
if len(frame_groups) <= 1 or smoothing_frames <= 0:
|
| 308 |
+
final_frames = []
|
| 309 |
+
for group in frame_groups:
|
| 310 |
+
final_frames.extend(group)
|
| 311 |
+
return final_frames
|
| 312 |
+
|
| 313 |
+
print(f"🌊 应用 {method} 平滑过渡 ({smoothing_frames} 帧)...")
|
| 314 |
+
|
| 315 |
+
if method == 'fade':
|
| 316 |
+
return self.apply_group_fade_smoothing(frame_groups, smoothing_frames)
|
| 317 |
+
elif method == 'blend':
|
| 318 |
+
return self.apply_group_blend_smoothing(frame_groups, smoothing_frames)
|
| 319 |
+
elif method == 'pause':
|
| 320 |
+
return self.apply_group_pause_smoothing(frame_groups, smoothing_frames)
|
| 321 |
+
else:
|
| 322 |
+
final_frames = []
|
| 323 |
+
for group in frame_groups:
|
| 324 |
+
final_frames.extend(group)
|
| 325 |
+
return final_frames
|
| 326 |
+
|
| 327 |
+
def apply_group_fade_smoothing(self, frame_groups, fade_frames):
|
| 328 |
+
"""对gloss分组应用淡入淡出平滑"""
|
| 329 |
+
smoothed_frames = []
|
| 330 |
+
|
| 331 |
+
for i, group in enumerate(frame_groups):
|
| 332 |
+
if i == 0:
|
| 333 |
+
# 第一组:淡入
|
| 334 |
+
for f in range(fade_frames):
|
| 335 |
+
alpha = f / fade_frames
|
| 336 |
+
black_frame = np.zeros_like(group[0])
|
| 337 |
+
faded_frame = (black_frame * (1 - alpha) + group[0] * alpha).astype(np.uint8)
|
| 338 |
+
smoothed_frames.append(faded_frame)
|
| 339 |
+
|
| 340 |
+
# 添加当前组的所有帧
|
| 341 |
+
smoothed_frames.extend(group)
|
| 342 |
+
|
| 343 |
+
if i < len(frame_groups) - 1:
|
| 344 |
+
# 组间过渡:当前组最后一帧淡出到下一组第一帧淡入
|
| 345 |
+
next_group = frame_groups[i + 1]
|
| 346 |
+
current_last = group[-1]
|
| 347 |
+
next_first = next_group[0]
|
| 348 |
+
|
| 349 |
+
for f in range(fade_frames):
|
| 350 |
+
alpha = f / fade_frames
|
| 351 |
+
blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
|
| 352 |
+
smoothed_frames.append(blended_frame)
|
| 353 |
+
|
| 354 |
+
return smoothed_frames
|
| 355 |
+
|
| 356 |
+
def apply_group_blend_smoothing(self, frame_groups, blend_frames):
|
| 357 |
+
"""对gloss分组应用混合平滑"""
|
| 358 |
+
smoothed_frames = []
|
| 359 |
+
|
| 360 |
+
for i, group in enumerate(frame_groups):
|
| 361 |
+
smoothed_frames.extend(group)
|
| 362 |
+
|
| 363 |
+
if i < len(frame_groups) - 1:
|
| 364 |
+
next_group = frame_groups[i + 1]
|
| 365 |
+
current_last = group[-1]
|
| 366 |
+
next_first = next_group[0]
|
| 367 |
+
|
| 368 |
+
# 在两组之间插入混合帧
|
| 369 |
+
for f in range(1, blend_frames + 1):
|
| 370 |
+
alpha = f / (blend_frames + 1)
|
| 371 |
+
blended_frame = (current_last * (1 - alpha) + next_first * alpha).astype(np.uint8)
|
| 372 |
+
smoothed_frames.append(blended_frame)
|
| 373 |
+
|
| 374 |
+
return smoothed_frames
|
| 375 |
+
|
| 376 |
+
def apply_group_pause_smoothing(self, frame_groups, pause_frames):
|
| 377 |
+
"""对gloss分组应用暂停平滑"""
|
| 378 |
+
smoothed_frames = []
|
| 379 |
+
|
| 380 |
+
for i, group in enumerate(frame_groups):
|
| 381 |
+
smoothed_frames.extend(group)
|
| 382 |
+
|
| 383 |
+
# 在每组后添加暂停帧(重复最后一帧)
|
| 384 |
+
if i < len(frame_groups) - 1:
|
| 385 |
+
last_frame = group[-1]
|
| 386 |
+
for _ in range(pause_frames):
|
| 387 |
+
smoothed_frames.append(last_frame.copy())
|
| 388 |
+
|
| 389 |
+
return smoothed_frames
|
| 390 |
+
|
| 391 |
+
def show_available_glosses(self, limit=20):
|
| 392 |
+
"""显示可用的gloss或video_id"""
|
| 393 |
+
if self.gloss_mapping:
|
| 394 |
+
glosses = list(self.gloss_mapping.keys())
|
| 395 |
+
print(f"\n📋 可用的Gloss ({len(glosses)}个):")
|
| 396 |
+
for i, gloss in enumerate(glosses[:limit]):
|
| 397 |
+
videos = self.gloss_mapping[gloss]
|
| 398 |
+
if isinstance(videos, list):
|
| 399 |
+
print(f" {gloss} -> {len(videos)} 个视频")
|
| 400 |
+
else:
|
| 401 |
+
print(f" {gloss} -> {videos}")
|
| 402 |
+
if len(glosses) > limit:
|
| 403 |
+
print(f" ... 还有 {len(glosses) - limit} 个")
|
| 404 |
+
else:
|
| 405 |
+
video_ids = list(self.metadata['video_index'].keys())
|
| 406 |
+
print(f"\n📋 可用的Video ID ({len(video_ids)}个):")
|
| 407 |
+
for i, vid in enumerate(video_ids[:limit]):
|
| 408 |
+
frame_count = (self.metadata['video_index'][vid]['end_frame'] -
|
| 409 |
+
self.metadata['video_index'][vid]['start_frame'] + 1)
|
| 410 |
+
print(f" {vid} ({frame_count} 帧)")
|
| 411 |
+
if len(video_ids) > limit:
|
| 412 |
+
print(f" ... 还有 {len(video_ids) - limit} 个")
|
| 413 |
+
|
| 414 |
+
def run_qa_system(self):
|
| 415 |
+
"""运行QA系统"""
|
| 416 |
+
print("\n" + "=" * 60)
|
| 417 |
+
print("🤖 手语Gloss问答系统")
|
| 418 |
+
print("=" * 60)
|
| 419 |
+
print("💬 输入想要转换的gloss,用空格分隔多个词")
|
| 420 |
+
print("📋 输入 'list' 查看可用的gloss/video")
|
| 421 |
+
print("🔧 输入 'help' 查看帮助")
|
| 422 |
+
print("👋 输入 'quit' 退出系统")
|
| 423 |
+
print("=" * 60)
|
| 424 |
+
|
| 425 |
+
while True:
|
| 426 |
+
try:
|
| 427 |
+
user_input = input("\n🤖 请输入gloss: ").strip()
|
| 428 |
+
|
| 429 |
+
if not user_input:
|
| 430 |
+
continue
|
| 431 |
+
elif user_input.lower() == 'quit':
|
| 432 |
+
print("👋 感谢使用!")
|
| 433 |
+
break
|
| 434 |
+
elif user_input.lower() == 'list':
|
| 435 |
+
self.show_available_glosses()
|
| 436 |
+
continue
|
| 437 |
+
elif user_input.lower() == 'help':
|
| 438 |
+
self.show_help()
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
# 解析输入的gloss
|
| 442 |
+
gloss_list = user_input.upper().split()
|
| 443 |
+
print(f"\n🎯 查询: {' + '.join(gloss_list)}")
|
| 444 |
+
|
| 445 |
+
# 获取对应的帧(每个gloss只选一个视频)
|
| 446 |
+
frame_indices, video_info = self.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)
|
| 447 |
+
|
| 448 |
+
if not frame_indices:
|
| 449 |
+
print("❌ 没有找到任何匹配的视频帧")
|
| 450 |
+
continue
|
| 451 |
+
|
| 452 |
+
print(f"\n📊 总共找到 {len(frame_indices)} 帧,来自 {len(video_info)} 个视频")
|
| 453 |
+
|
| 454 |
+
# 如果有多个视频,询问平滑选项
|
| 455 |
+
smoothing_method = 'none'
|
| 456 |
+
smoothing_frames = 0
|
| 457 |
+
|
| 458 |
+
if len(video_info) > 1:
|
| 459 |
+
print(f"\n🌊 检测到多个视频片段,选择平滑过渡方式:")
|
| 460 |
+
print(f" 1. none - 无平滑 (直接拼接)")
|
| 461 |
+
print(f" 2. fade - 淡入淡出过渡")
|
| 462 |
+
print(f" 3. blend - 帧间混合过渡")
|
| 463 |
+
print(f" 4. pause - 增加暂停间隔")
|
| 464 |
+
|
| 465 |
+
smooth_choice = input(f"选择平滑方式 [1-4, 默认1]: ").strip()
|
| 466 |
+
|
| 467 |
+
if smooth_choice == '2':
|
| 468 |
+
smoothing_method = 'fade'
|
| 469 |
+
smoothing_frames = int(input("淡入淡出帧数 [默认5]: ").strip() or "5")
|
| 470 |
+
elif smooth_choice == '3':
|
| 471 |
+
smoothing_method = 'blend'
|
| 472 |
+
smoothing_frames = int(input("混合帧数 [默认3]: ").strip() or "3")
|
| 473 |
+
elif smooth_choice == '4':
|
| 474 |
+
smoothing_method = 'pause'
|
| 475 |
+
smoothing_frames = int(input("暂停帧数 [默认10]: ").strip() or "10")
|
| 476 |
+
|
| 477 |
+
# 生成输出文件名
|
| 478 |
+
gloss_str = "_".join(gloss_list)
|
| 479 |
+
timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 480 |
+
suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
|
| 481 |
+
output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"
|
| 482 |
+
|
| 483 |
+
# 询问用户是否生成视频
|
| 484 |
+
confirm = input(f"\n❓ 生成视频到 {output_file}? [y/n]: ").strip().lower()
|
| 485 |
+
|
| 486 |
+
if confirm in ['y', 'yes', '']:
|
| 487 |
+
success = self.generate_video(
|
| 488 |
+
frame_indices, output_file, video_info,
|
| 489 |
+
smoothing_frames=smoothing_frames,
|
| 490 |
+
smoothing_method=smoothing_method
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
if success:
|
| 494 |
+
print(f"\n🎉 视频已生成: {output_file}")
|
| 495 |
+
|
| 496 |
+
# 显示视频详情
|
| 497 |
+
print(f"\n📈 视频详情:")
|
| 498 |
+
for info in video_info:
|
| 499 |
+
print(f" {info['gloss']}: {info['video_id']} ({info['frame_count']} 帧)")
|
| 500 |
+
else:
|
| 501 |
+
print("⏭️ 跳过视频生成")
|
| 502 |
+
|
| 503 |
+
except KeyboardInterrupt:
|
| 504 |
+
print("\n\n👋 系统已退出")
|
| 505 |
+
break
|
| 506 |
+
except Exception as e:
|
| 507 |
+
print(f"❌ 发生错误: {e}")
|
| 508 |
+
|
| 509 |
+
def show_help(self):
|
| 510 |
+
"""显示帮助信息"""
|
| 511 |
+
print("\n" + "=" * 50)
|
| 512 |
+
print("📖 帮助信息")
|
| 513 |
+
print("=" * 50)
|
| 514 |
+
print("🔹 输入单个gloss: HELLO")
|
| 515 |
+
print("🔹 输入多个gloss: HELLO WORLD GOODBYE")
|
| 516 |
+
print("🔹 查看可用内容: list")
|
| 517 |
+
print("🔹 系统会自动匹配对应的手语视频")
|
| 518 |
+
print(f"🔹 生成的视频保存在 {OUTPUT_DIR}/ 目录")
|
| 519 |
+
print("🔹 支持的映射文件格式 (gloss_mapping.json):")
|
| 520 |
+
print(' {"HELLO": ["video1", "video2"], "WORLD": "video3"}')
|
| 521 |
+
print("🔹 平滑过渡选项:")
|
| 522 |
+
print(" - fade: 淡入淡出过渡")
|
| 523 |
+
print(" - blend: 帧间混合过渡")
|
| 524 |
+
print(" - pause: 增加暂停间隔")
|
| 525 |
+
print("=" * 50)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def main():
|
| 529 |
+
parser = argparse.ArgumentParser(description='手语Gloss问答系统')
|
| 530 |
+
parser.add_argument('--gloss', '-g',
|
| 531 |
+
help='直接输入gloss生成视频,用空格分隔')
|
| 532 |
+
parser.add_argument('--fps', type=int, default=30,
|
| 533 |
+
help='视频帧率 (默认: 30)')
|
| 534 |
+
parser.add_argument('--width', type=int, default=480,
|
| 535 |
+
help='视频宽度 (默认: 480)')
|
| 536 |
+
parser.add_argument('--height', type=int, default=480,
|
| 537 |
+
help='视频高度 (默认: 480)')
|
| 538 |
+
parser.add_argument('--smoothing', choices=['none', 'fade', 'blend', 'pause'],
|
| 539 |
+
default='none', help='平滑过渡方式 (默认: none)')
|
| 540 |
+
parser.add_argument('--smoothing-frames', type=int, default=5,
|
| 541 |
+
help='平滑过渡帧数 (默认: 5)')
|
| 542 |
+
|
| 543 |
+
args = parser.parse_args()
|
| 544 |
+
|
| 545 |
+
# 初始化QA系统
|
| 546 |
+
qa_system = SignLanguageQA()
|
| 547 |
+
|
| 548 |
+
# 如果提供了gloss参数,直接处理
|
| 549 |
+
if args.gloss:
|
| 550 |
+
gloss_list = args.gloss.upper().split()
|
| 551 |
+
print(f"🎯 处理gloss: {' + '.join(gloss_list)}")
|
| 552 |
+
|
| 553 |
+
frame_indices, video_info = qa_system.get_frames_for_glosses(gloss_list, one_video_per_gloss=True)
|
| 554 |
+
|
| 555 |
+
if frame_indices:
|
| 556 |
+
gloss_str = "_".join(gloss_list)
|
| 557 |
+
timestamp = __import__('datetime').datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 558 |
+
suffix = f"_{args.smoothing}" if args.smoothing != 'none' else ""
|
| 559 |
+
output_file = Path(OUTPUT_DIR) / f"{gloss_str}_{timestamp}{suffix}.mp4"
|
| 560 |
+
|
| 561 |
+
print(f"📊 找到 {len(frame_indices)} 帧,来自 {len(video_info)} 个视频")
|
| 562 |
+
if args.smoothing != 'none':
|
| 563 |
+
print(f"🌊 使用 {args.smoothing} 平滑过渡 ({args.smoothing_frames} 帧)")
|
| 564 |
+
|
| 565 |
+
success = qa_system.generate_video(
|
| 566 |
+
frame_indices, output_file, video_info, args.fps, args.width, args.height,
|
| 567 |
+
args.smoothing_frames, args.smoothing
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
if success:
|
| 571 |
+
print(f"🎉 视频已生成: {output_file}")
|
| 572 |
+
print(f"\n📈 视频详情:")
|
| 573 |
+
for info in video_info:
|
| 574 |
+
print(f" {info['gloss']}: {info['video_id']} ({info['frame_count']} 帧)")
|
| 575 |
+
else:
|
| 576 |
+
print("❌ 没有找到匹配的视频")
|
| 577 |
+
else:
|
| 578 |
+
# 启动交互式QA系统
|
| 579 |
+
qa_system.run_qa_system()
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
if __name__ == "__main__":
|
| 583 |
+
main()
|
quick_vis_controlnext_style_dwpose_from_npz_or_input_img.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import numpy as np
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
from easy_dwpose import DWposeDetector
|
| 7 |
+
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
| 8 |
+
|
| 9 |
+
#####---------Setup init
|
| 10 |
+
# You can use a different GPU, e.g. "cuda:1"
|
| 11 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
detector = DWposeDetector(device=device)
|
| 13 |
+
input_image = Image.open("assets/pose.png").convert("RGB")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
#####---------Custom ControlNext drawing style
|
| 18 |
+
# Get pose data for custom drawing
|
| 19 |
+
#pose_data = detector(input_image, draw_pose=False)
|
| 20 |
+
# or
|
| 21 |
+
pose_data = dict(np.load('assets/WLASL_01214/results_dwpose/npz/00000011.npz'))
|
| 22 |
+
|
| 23 |
+
# Get image dimensions
|
| 24 |
+
#width, height = input_image.size
|
| 25 |
+
# or
|
| 26 |
+
width, 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.
|
| 27 |
+
|
| 28 |
+
# Process the pose data for custom drawing
|
| 29 |
+
processed_pred = process_pose_data(pose_data, height, width)
|
| 30 |
+
|
| 31 |
+
# Draw pose using custom ControlNext style
|
| 32 |
+
vis_img = draw_pose(
|
| 33 |
+
pose=processed_pred,
|
| 34 |
+
H=height,
|
| 35 |
+
W=width,
|
| 36 |
+
include_body=True,
|
| 37 |
+
include_hand=True,
|
| 38 |
+
include_face=True
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Convert to PIL Image and save (vis_img is in CHW format)
|
| 42 |
+
custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))
|
| 43 |
+
custom_skeleton.save("skeleton_controlnext.png")
|
requirements.txt
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
antlr4-python3-runtime==4.9.3
|
| 2 |
+
av==14.4.0
|
| 3 |
+
certifi==2025.4.26
|
| 4 |
+
charset-normalizer==3.4.2
|
| 5 |
+
click==8.2.1
|
| 6 |
+
coloredlogs==15.0.1
|
| 7 |
+
contourpy==1.3.2
|
| 8 |
+
cycler==0.12.1
|
| 9 |
+
easy_dwpose==1.0.2
|
| 10 |
+
filelock==3.18.0
|
| 11 |
+
flatbuffers==25.2.10
|
| 12 |
+
fonttools==4.58.0
|
| 13 |
+
fsspec==2025.5.1
|
| 14 |
+
hf-xet==1.1.2
|
| 15 |
+
huggingface-hub==0.24.7
|
| 16 |
+
humanfriendly==10.0
|
| 17 |
+
idna==3.10
|
| 18 |
+
imageio==2.37.0
|
| 19 |
+
imageio-ffmpeg==0.6.0
|
| 20 |
+
Jinja2==3.1.6
|
| 21 |
+
kiwisolver==1.4.8
|
| 22 |
+
loguru==0.7.3
|
| 23 |
+
MarkupSafe==3.0.2
|
| 24 |
+
matplotlib==3.10.3
|
| 25 |
+
mpmath==1.3.0
|
| 26 |
+
natsort==8.4.0
|
| 27 |
+
networkx==3.4.2
|
| 28 |
+
numpy==1.26.4
|
| 29 |
+
nvidia-cublas-cu12==12.6.4.1
|
| 30 |
+
nvidia-cuda-cupti-cu12==12.6.80
|
| 31 |
+
nvidia-cuda-nvrtc-cu12==12.6.77
|
| 32 |
+
nvidia-cuda-runtime-cu12==12.6.77
|
| 33 |
+
nvidia-cudnn-cu12==9.5.1.17
|
| 34 |
+
nvidia-cufft-cu12==11.3.0.4
|
| 35 |
+
nvidia-cufile-cu12==1.11.1.6
|
| 36 |
+
nvidia-curand-cu12==10.3.7.77
|
| 37 |
+
nvidia-cusolver-cu12==11.7.1.2
|
| 38 |
+
nvidia-cusparse-cu12==12.5.4.2
|
| 39 |
+
nvidia-cusparselt-cu12==0.6.3
|
| 40 |
+
nvidia-nccl-cu12==2.26.2
|
| 41 |
+
nvidia-nvjitlink-cu12==12.6.85
|
| 42 |
+
nvidia-nvtx-cu12==12.6.77
|
| 43 |
+
omegaconf==2.3.0
|
| 44 |
+
onnxruntime==1.22.0
|
| 45 |
+
onnxruntime-gpu==1.16.2
|
| 46 |
+
opencv-python==4.11.0.86
|
| 47 |
+
packaging==25.0
|
| 48 |
+
pandas==2.2.3
|
| 49 |
+
pillow==11.2.1
|
| 50 |
+
pose_format==0.9.1
|
| 51 |
+
protobuf==6.31.1
|
| 52 |
+
psutil==7.0.0
|
| 53 |
+
pyparsing==3.2.3
|
| 54 |
+
python-dateutil==2.9.0.post0
|
| 55 |
+
pytz==2025.2
|
| 56 |
+
PyYAML==6.0.2
|
| 57 |
+
requests==2.32.3
|
| 58 |
+
scipy==1.15.3
|
| 59 |
+
simplemma==1.1.2
|
| 60 |
+
six==1.17.0
|
| 61 |
+
-e git+https://github.com/sign-language-processing/spoken-to-signed-translation.git@21a34fbb7ae6439eb8ed54b0c4a2a5c4538a7977#egg=spoken_to_signed
|
| 62 |
+
svgwrite==1.4.3
|
| 63 |
+
sympy==1.14.0
|
| 64 |
+
torch==2.7.0
|
| 65 |
+
tqdm==4.67.1
|
| 66 |
+
Tree==0.2.4
|
| 67 |
+
triton==3.3.0
|
| 68 |
+
typing_extensions==4.13.2
|
| 69 |
+
tzdata==2025.2
|
| 70 |
+
urllib3==2.4.0
|
step0_learn_quick_vis_controlnext_style_dwpose_from_npz_or_input_img.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import numpy as np
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
from easy_dwpose import DWposeDetector
|
| 7 |
+
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
#####---------Setup init
|
| 11 |
+
# You can use a different GPU, e.g. "cuda:1"
|
| 12 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 13 |
+
detector = DWposeDetector(device=device)
|
| 14 |
+
input_image = Image.open("assets/pose.png").convert("RGB")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
#####---------Custom ControlNext drawing style
|
| 19 |
+
# Get pose data for custom drawing
|
| 20 |
+
#pose_data = detector(input_image, draw_pose=False)
|
| 21 |
+
# or
|
| 22 |
+
pose_data = dict(np.load('assets/WLASL_01214/results_dwpose/npz/00000003.npz'))
|
| 23 |
+
|
| 24 |
+
# Get image dimensions
|
| 25 |
+
#width, height = input_image.size
|
| 26 |
+
# or
|
| 27 |
+
width, 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.
|
| 28 |
+
|
| 29 |
+
# Process the pose data for custom drawing
|
| 30 |
+
processed_pred = process_pose_data(pose_data, height, width)
|
| 31 |
+
|
| 32 |
+
# Draw pose using custom ControlNext style
|
| 33 |
+
vis_img = draw_pose(
|
| 34 |
+
pose=processed_pred,
|
| 35 |
+
H=height,
|
| 36 |
+
W=width,
|
| 37 |
+
include_body=True,
|
| 38 |
+
include_hand=True,
|
| 39 |
+
include_face=True
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Convert to PIL Image and save (vis_img is in CHW format)
|
| 43 |
+
custom_skeleton = Image.fromarray(vis_img.transpose(1, 2, 0))
|
| 44 |
+
custom_skeleton.save("skeleton_controlnext3.png")
|
step1_run_step1_from_csv.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import csv
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
import os
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
def read_csv_for_gloss(csv_path, gloss_key):
|
| 9 |
+
results = []
|
| 10 |
+
with open(csv_path, 'r', encoding='utf-8') as f:
|
| 11 |
+
reader = csv.DictReader(f)
|
| 12 |
+
for row in reader:
|
| 13 |
+
if row['gloss'].strip().lower() == gloss_key.strip().lower():
|
| 14 |
+
results.append((row['video_id'], row['npz_dir']))
|
| 15 |
+
return results
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def run_merge(npz_dir, output_dir="posedict"):
|
| 19 |
+
cmd = [sys.executable, "step2_merge_npz.py", npz_dir, "--output", output_dir]
|
| 20 |
+
ret = subprocess.run(cmd, capture_output=True, text=True)
|
| 21 |
+
if ret.returncode != 0:
|
| 22 |
+
print(f"❌ 合并失败:{npz_dir}")
|
| 23 |
+
print("stderr:")
|
| 24 |
+
print(ret.stderr)
|
| 25 |
+
print("stdout:")
|
| 26 |
+
print(ret.stdout)
|
| 27 |
+
return ret.returncode == 0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
parser = argparse.ArgumentParser(description="从CSV中查gloss并合并npz,仅提示成功video_id")
|
| 32 |
+
parser.add_argument("--gloss", required=True, help="gloss关键词")
|
| 33 |
+
parser.add_argument("--csv", default="assets/WLASL_small_results/gloss_npz_mapping.csv", help="映射CSV路径")
|
| 34 |
+
parser.add_argument("--output", default="posedict", help="合并输出目录")
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
|
| 37 |
+
mapping = read_csv_for_gloss(args.csv, args.gloss)
|
| 38 |
+
print("合并成功的文件id名称:")
|
| 39 |
+
for vid, npz_dir in mapping:
|
| 40 |
+
if not os.path.isdir(npz_dir):
|
| 41 |
+
continue
|
| 42 |
+
if run_merge(npz_dir, args.output):
|
| 43 |
+
print(vid)
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
main()
|
step2_merge_npz.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
NPZ文件合并脚本
|
| 4 |
+
用法: python merge.py <npz_folder_path>
|
| 5 |
+
例如: python merge.py ./assets/WLASL_01214/results_dwpose/npz
|
| 6 |
+
|
| 7 |
+
将指定文件夹下的所有npz文件合并成一个大的npz文件,
|
| 8 |
+
以视频名称命名并保存到./posedict文件夹下。
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import numpy as np
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import argparse
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
|
| 18 |
+
def extract_frame_number(filename):
|
| 19 |
+
"""从文件名中提取帧号"""
|
| 20 |
+
# 假设文件名格式为 00000001.npz, 00000002.npz 等
|
| 21 |
+
name = Path(filename).stem
|
| 22 |
+
try:
|
| 23 |
+
return int(name)
|
| 24 |
+
except ValueError:
|
| 25 |
+
print(f"警告: 无法从文件名 '{filename}' 中提取帧号")
|
| 26 |
+
return 0
|
| 27 |
+
|
| 28 |
+
def get_video_name_from_path(npz_folder_path):
|
| 29 |
+
"""从路径中提取视频名称"""
|
| 30 |
+
# 路径格式: ./assets/WLASL_01214/results_dwpose/npz
|
| 31 |
+
# 提取 WLASL_01214 作为视频名称
|
| 32 |
+
path_parts = Path(npz_folder_path).parts
|
| 33 |
+
for part in reversed(path_parts):
|
| 34 |
+
if part != 'npz' and part != 'results_dwpose':
|
| 35 |
+
return part
|
| 36 |
+
return "unknown_video"
|
| 37 |
+
|
| 38 |
+
def merge_npz_files(npz_folder_path, output_folder="./posedict"):
|
| 39 |
+
"""
|
| 40 |
+
合并指定文件夹下的所有npz文件
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
npz_folder_path: 包含npz文件的文件夹路径
|
| 44 |
+
output_folder: 输出文件夹路径
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# 确保输入路径存在
|
| 48 |
+
npz_folder = Path(npz_folder_path)
|
| 49 |
+
if not npz_folder.exists():
|
| 50 |
+
print(f"错误: 文件夹 '{npz_folder_path}' 不存在")
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
# 获取所有npz文件
|
| 54 |
+
npz_files = list(npz_folder.glob("*.npz"))
|
| 55 |
+
if not npz_files:
|
| 56 |
+
print(f"错误: 在文件夹 '{npz_folder_path}' 中未找到npz文件")
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
print(f"找到 {len(npz_files)} 个npz文件")
|
| 60 |
+
|
| 61 |
+
# 按帧号排序
|
| 62 |
+
npz_files.sort(key=lambda x: extract_frame_number(x.name))
|
| 63 |
+
|
| 64 |
+
# 创建输出文件夹
|
| 65 |
+
output_path = Path(output_folder)
|
| 66 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
|
| 68 |
+
# 获取视频名称
|
| 69 |
+
video_name = get_video_name_from_path(npz_folder_path)
|
| 70 |
+
output_file = output_path / f"{video_name}.npz"
|
| 71 |
+
|
| 72 |
+
# 合并所有npz文件的数据
|
| 73 |
+
merged_data = {}
|
| 74 |
+
|
| 75 |
+
for npz_file in npz_files:
|
| 76 |
+
frame_number = extract_frame_number(npz_file.name)
|
| 77 |
+
frame_key = f"frame_{frame_number:08d}" # 格式化为8位数字,如 frame_00000001
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
# 加载npz文件
|
| 81 |
+
data = np.load(npz_file, allow_pickle=True)
|
| 82 |
+
|
| 83 |
+
# 将数据存储到合并字典中
|
| 84 |
+
frame_data = {}
|
| 85 |
+
for key in data.files:
|
| 86 |
+
frame_data[key] = data[key]
|
| 87 |
+
|
| 88 |
+
merged_data[frame_key] = frame_data
|
| 89 |
+
|
| 90 |
+
print(f"处理完成: {npz_file.name} -> {frame_key}")
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"错误: 无法加载文件 '{npz_file}': {e}")
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
if not merged_data:
|
| 97 |
+
print("错误: 没有成功加载任何npz文件")
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
# 保存合并后的数据
|
| 101 |
+
try:
|
| 102 |
+
# 由于npz格式的限制,我们需要特殊处理嵌套字典
|
| 103 |
+
# 将嵌套数据扁平化保存
|
| 104 |
+
flattened_data = {}
|
| 105 |
+
|
| 106 |
+
for frame_key, frame_data in merged_data.items():
|
| 107 |
+
for data_key, data_value in frame_data.items():
|
| 108 |
+
combined_key = f"{frame_key}_{data_key}"
|
| 109 |
+
flattened_data[combined_key] = data_value
|
| 110 |
+
|
| 111 |
+
# 另外保存一个元数据,包含帧信息
|
| 112 |
+
frame_info = {
|
| 113 |
+
'frame_count': len(merged_data),
|
| 114 |
+
'frame_keys': list(merged_data.keys()),
|
| 115 |
+
'video_name': video_name,
|
| 116 |
+
'original_keys': list(next(iter(merged_data.values())).keys()) if merged_data else []
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
flattened_data['_metadata'] = frame_info
|
| 120 |
+
|
| 121 |
+
np.savez_compressed(output_file, **flattened_data)
|
| 122 |
+
|
| 123 |
+
print(f"\n成功合并 {len(merged_data)} 帧数据")
|
| 124 |
+
print(f"输出文件: {output_file}")
|
| 125 |
+
print(f"文件大小: {output_file.stat().st_size / 1024 / 1024:.2f} MB")
|
| 126 |
+
|
| 127 |
+
return True
|
| 128 |
+
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"错误: 保存合并文件时出错: {e}")
|
| 131 |
+
return False
|
| 132 |
+
|
| 133 |
+
def load_merged_npz(npz_file_path):
|
| 134 |
+
"""
|
| 135 |
+
加载合并后的npz文件的辅助函数
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
npz_file_path: 合并后的npz文件路径
|
| 139 |
+
|
| 140 |
+
Returns:
|
| 141 |
+
dict: 重构的帧数据字典
|
| 142 |
+
"""
|
| 143 |
+
data = np.load(npz_file_path, allow_pickle=True)
|
| 144 |
+
metadata = data['_metadata'].item()
|
| 145 |
+
|
| 146 |
+
# 重构原始数据结构
|
| 147 |
+
frames_data = {}
|
| 148 |
+
original_keys = metadata['original_keys']
|
| 149 |
+
|
| 150 |
+
for frame_key in metadata['frame_keys']:
|
| 151 |
+
frame_data = {}
|
| 152 |
+
for orig_key in original_keys:
|
| 153 |
+
combined_key = f"{frame_key}_{orig_key}"
|
| 154 |
+
if combined_key in data:
|
| 155 |
+
frame_data[orig_key] = data[combined_key]
|
| 156 |
+
frames_data[frame_key] = frame_data
|
| 157 |
+
|
| 158 |
+
return frames_data, metadata
|
| 159 |
+
|
| 160 |
+
def main():
|
| 161 |
+
parser = argparse.ArgumentParser(description='合并NPZ文件')
|
| 162 |
+
parser.add_argument('npz_folder', help='包含npz文件的文件夹路径')
|
| 163 |
+
parser.add_argument('--output', '-o', default='./posedict',
|
| 164 |
+
help='输出文件夹路径 (默认: ./posedict)')
|
| 165 |
+
|
| 166 |
+
args = parser.parse_args()
|
| 167 |
+
|
| 168 |
+
success = merge_npz_files(args.npz_folder, args.output)
|
| 169 |
+
|
| 170 |
+
if success:
|
| 171 |
+
print("\n✅ 合并完成!")
|
| 172 |
+
|
| 173 |
+
# 演示如何读取合并后的文件
|
| 174 |
+
video_name = get_video_name_from_path(args.npz_folder)
|
| 175 |
+
output_file = Path(args.output) / f"{video_name}.npz"
|
| 176 |
+
|
| 177 |
+
print(f"\n💡 读取示例:")
|
| 178 |
+
print(f"frames_data, metadata = load_merged_npz('{output_file}')")
|
| 179 |
+
print(f"# 访问第11帧数据: frames_data['frame_00000011']")
|
| 180 |
+
|
| 181 |
+
else:
|
| 182 |
+
print("\n❌ 合并失败!")
|
| 183 |
+
sys.exit(1)
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
main()
|
step3_read_and_vis_merge_npz_to_pose_video.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
NPZ转Pose视频脚本
|
| 4 |
+
用法: python step2_read_and_vis_merge_npz_to_pose_video.py <merged_npz_path>
|
| 5 |
+
例如: python step2_read_and_vis_merge_npz_to_pose_video.py ./posedict/WLASL_01214.npz
|
| 6 |
+
|
| 7 |
+
将合并后的多帧npz文件可视化成pose视频
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import numpy as np
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import argparse
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import cv2
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
from easy_dwpose import DWposeDetector
|
| 22 |
+
from easy_dwpose.draw.controlnext import draw_pose, process_pose_data
|
| 23 |
+
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
def load_merged_npz(npz_file_path):
|
| 28 |
+
"""
|
| 29 |
+
加载合并后的npz文件的辅助函数
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
frames_data: dict[str, dict[str, np.ndarray]]
|
| 33 |
+
metadata: dict
|
| 34 |
+
"""
|
| 35 |
+
try:
|
| 36 |
+
path = Path(npz_file_path)
|
| 37 |
+
if not path.exists():
|
| 38 |
+
print(f"错误: 文件 '{npz_file_path}' 不存在")
|
| 39 |
+
return None, None
|
| 40 |
+
if not path.is_file():
|
| 41 |
+
print(f"错误: 路径 '{npz_file_path}' 不是一个有效的 .npz 文件")
|
| 42 |
+
return None, None
|
| 43 |
+
|
| 44 |
+
data = np.load(path, allow_pickle=True)
|
| 45 |
+
metadata = data['_metadata'].item()
|
| 46 |
+
|
| 47 |
+
frames_data = {}
|
| 48 |
+
original_keys = metadata['original_keys']
|
| 49 |
+
|
| 50 |
+
for frame_key in metadata['frame_keys']:
|
| 51 |
+
frame_data = {}
|
| 52 |
+
for orig_key in original_keys:
|
| 53 |
+
combined_key = f"{frame_key}_{orig_key}"
|
| 54 |
+
if combined_key in data:
|
| 55 |
+
frame_data[orig_key] = data[combined_key]
|
| 56 |
+
frames_data[frame_key] = frame_data
|
| 57 |
+
|
| 58 |
+
return frames_data, metadata
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"错误: 无法加载合并的npz文件 '{npz_file_path}': {e}")
|
| 62 |
+
return None, None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def create_pose_frame(pose_data, width=480, height=480):
|
| 66 |
+
"""
|
| 67 |
+
从pose数据创建单帧pose图像
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
pose_data: 单帧的pose数据字典
|
| 71 |
+
width: 图像宽度
|
| 72 |
+
height: 图像高度
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
numpy.ndarray: RGB格式的图像数组
|
| 76 |
+
"""
|
| 77 |
+
try:
|
| 78 |
+
# Process the pose data for custom drawing
|
| 79 |
+
processed_pred = process_pose_data(pose_data, height, width)
|
| 80 |
+
|
| 81 |
+
# Draw pose using custom ControlNext style
|
| 82 |
+
vis_img = draw_pose(
|
| 83 |
+
pose=processed_pred,
|
| 84 |
+
H=height,
|
| 85 |
+
W=width,
|
| 86 |
+
include_body=True,
|
| 87 |
+
include_hand=True,
|
| 88 |
+
include_face=True
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Convert from CHW to HWC format
|
| 92 |
+
pose_frame = vis_img.transpose(1, 2, 0)
|
| 93 |
+
|
| 94 |
+
return pose_frame
|
| 95 |
+
|
| 96 |
+
except Exception as e:
|
| 97 |
+
print(f"错误: 创建pose帧时出错: {e}")
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
def create_pose_video(merged_npz_path, output_folder="./output_pose_video", fps=30, width=480, height=480):
|
| 101 |
+
"""
|
| 102 |
+
从合并的npz文件创建pose视频
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
merged_npz_path: 合并后的npz文件路径
|
| 106 |
+
output_folder: 输出文件夹
|
| 107 |
+
fps: 视频帧率
|
| 108 |
+
width: 视频宽度
|
| 109 |
+
height: 视频高度
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
# 检查输入文件是否存在
|
| 113 |
+
npz_path = Path(merged_npz_path)
|
| 114 |
+
if not npz_path.exists():
|
| 115 |
+
print(f"错误: 文件 '{merged_npz_path}' 不存在")
|
| 116 |
+
return False
|
| 117 |
+
|
| 118 |
+
# 加载合并的npz数据
|
| 119 |
+
print(f"正在加载合并的npz文件: {merged_npz_path}")
|
| 120 |
+
frames_data, metadata = load_merged_npz(merged_npz_path)
|
| 121 |
+
|
| 122 |
+
if frames_data is None:
|
| 123 |
+
print("错误: 无法加载npz数据")
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
print(f"成功加载 {metadata['frame_count']} 帧数据")
|
| 127 |
+
|
| 128 |
+
# 创建输出文件夹
|
| 129 |
+
output_path = Path(output_folder)
|
| 130 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
|
| 132 |
+
# 生成输出视频文件名
|
| 133 |
+
video_name = npz_path.stem # 获取文件名(不含扩展名)
|
| 134 |
+
output_video_path = output_path / f"{video_name}_pose_video.mp4"
|
| 135 |
+
|
| 136 |
+
# 设置视频编码器
|
| 137 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 138 |
+
video_writer = cv2.VideoWriter(str(output_video_path), fourcc, fps, (width, height))
|
| 139 |
+
|
| 140 |
+
if not video_writer.isOpened():
|
| 141 |
+
print("错误: 无法创建视频文件")
|
| 142 |
+
return False
|
| 143 |
+
|
| 144 |
+
# 按帧号排序
|
| 145 |
+
sorted_frame_keys = sorted(frames_data.keys(), key=lambda x: int(x.split('_')[1]))
|
| 146 |
+
|
| 147 |
+
print(f"正在生成pose视频...")
|
| 148 |
+
|
| 149 |
+
# 生成每一帧
|
| 150 |
+
for frame_key in tqdm(sorted_frame_keys, desc="处理帧"):
|
| 151 |
+
pose_data = frames_data[frame_key]
|
| 152 |
+
|
| 153 |
+
# 创建pose帧
|
| 154 |
+
pose_frame = create_pose_frame(pose_data, width, height)
|
| 155 |
+
|
| 156 |
+
if pose_frame is not None:
|
| 157 |
+
# 转换为BGR格式(OpenCV格式)
|
| 158 |
+
pose_frame_bgr = cv2.cvtColor(pose_frame, cv2.COLOR_RGB2BGR)
|
| 159 |
+
|
| 160 |
+
# 写入视频
|
| 161 |
+
video_writer.write(pose_frame_bgr)
|
| 162 |
+
else:
|
| 163 |
+
print(f"警告: 跳过帧 {frame_key}(处理失败)")
|
| 164 |
+
|
| 165 |
+
# 释放视频写入器
|
| 166 |
+
video_writer.release()
|
| 167 |
+
|
| 168 |
+
print(f"\n✅ Pose视频生成完成!")
|
| 169 |
+
print(f"输出文件: {output_video_path}")
|
| 170 |
+
print(f"视频信息: {len(sorted_frame_keys)} 帧, {fps} fps, {width}x{height}")
|
| 171 |
+
print(f"文件大小: {output_video_path.stat().st_size / 1024 / 1024:.2f} MB")
|
| 172 |
+
|
| 173 |
+
return True
|
| 174 |
+
|
| 175 |
+
def create_pose_images(merged_npz_path, output_folder="./output_pose_images", width=480, height=480):
|
| 176 |
+
"""
|
| 177 |
+
从合并的npz文件创建pose图像序列(可选功能)
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
merged_npz_path: 合并后的npz文件路径
|
| 181 |
+
output_folder: 输出文件夹
|
| 182 |
+
width: 图像宽度
|
| 183 |
+
height: 图像高度
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
# 检查输入文件是否存在
|
| 187 |
+
npz_path = Path(merged_npz_path)
|
| 188 |
+
if not npz_path.exists():
|
| 189 |
+
print(f"错误: 文件 '{merged_npz_path}' 不存在")
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
# 加载合并的npz数据
|
| 193 |
+
print(f"正在加载合并的npz文件: {merged_npz_path}")
|
| 194 |
+
frames_data, metadata = load_merged_npz(merged_npz_path)
|
| 195 |
+
|
| 196 |
+
if frames_data is None:
|
| 197 |
+
print("错误: 无法加载npz数据")
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
# 创建输出文件夹
|
| 201 |
+
video_name = npz_path.stem
|
| 202 |
+
output_path = Path(output_folder) / video_name
|
| 203 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
|
| 205 |
+
# 按帧号排序
|
| 206 |
+
sorted_frame_keys = sorted(frames_data.keys(), key=lambda x: int(x.split('_')[1]))
|
| 207 |
+
|
| 208 |
+
print(f"正在生成pose图像序列...")
|
| 209 |
+
|
| 210 |
+
# 生成每一帧图像
|
| 211 |
+
for i, frame_key in enumerate(tqdm(sorted_frame_keys, desc="处理帧")):
|
| 212 |
+
pose_data = frames_data[frame_key]
|
| 213 |
+
|
| 214 |
+
# 创建pose帧
|
| 215 |
+
pose_frame = create_pose_frame(pose_data, width, height)
|
| 216 |
+
|
| 217 |
+
if pose_frame is not None:
|
| 218 |
+
# 保存为PNG图像
|
| 219 |
+
frame_number = int(frame_key.split('_')[1])
|
| 220 |
+
output_image_path = output_path / f"pose_{frame_number:08d}.png"
|
| 221 |
+
|
| 222 |
+
pose_image = Image.fromarray(pose_frame)
|
| 223 |
+
pose_image.save(output_image_path)
|
| 224 |
+
else:
|
| 225 |
+
print(f"警告: 跳过帧 {frame_key}(处理失败)")
|
| 226 |
+
|
| 227 |
+
print(f"\n✅ Pose图像序列生成完成!")
|
| 228 |
+
print(f"输出文件夹: {output_path}")
|
| 229 |
+
print(f"生成图像数: {len(sorted_frame_keys)} 张")
|
| 230 |
+
|
| 231 |
+
return True
|
| 232 |
+
|
| 233 |
+
def main():
|
| 234 |
+
parser = argparse.ArgumentParser(description='将合并的NPZ文件转换为Pose视频')
|
| 235 |
+
parser.add_argument('merged_npz_path', help='合并后的npz文件路径')
|
| 236 |
+
parser.add_argument('--output', '-o', default='./output_pose_video',
|
| 237 |
+
help='输出文件夹路径 (默认: ./output_pose_video)')
|
| 238 |
+
parser.add_argument('--fps', type=int, default=30,
|
| 239 |
+
help='视频帧率 (默认: 30)')
|
| 240 |
+
parser.add_argument('--width', type=int, default=480,
|
| 241 |
+
help='视频宽度 (默认: 480)')
|
| 242 |
+
parser.add_argument('--height', type=int, default=480,
|
| 243 |
+
help='视频高度 (默认: 480)')
|
| 244 |
+
parser.add_argument('--images', action='store_true',
|
| 245 |
+
help='同时生成图像序列')
|
| 246 |
+
|
| 247 |
+
args = parser.parse_args()
|
| 248 |
+
|
| 249 |
+
# 生成pose视频
|
| 250 |
+
success = create_pose_video(
|
| 251 |
+
args.merged_npz_path,
|
| 252 |
+
args.output,
|
| 253 |
+
args.fps,
|
| 254 |
+
args.width,
|
| 255 |
+
args.height
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
if not success:
|
| 259 |
+
print("\n❌ 视频生成失败!")
|
| 260 |
+
sys.exit(1)
|
| 261 |
+
|
| 262 |
+
# 如果指定了--images选项,同时生成图像序列
|
| 263 |
+
if args.images:
|
| 264 |
+
print("\n" + "="*50)
|
| 265 |
+
print("生成图像序列...")
|
| 266 |
+
create_pose_images(
|
| 267 |
+
args.merged_npz_path,
|
| 268 |
+
args.output.replace('video', 'images'),
|
| 269 |
+
args.width,
|
| 270 |
+
args.height
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
main()
|