FangSen9000 commited on
Commit
cfb7d5a
·
1 Parent(s): 84dd14c

Add the modified openpose and add confidence level filtering.

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. README_v1.md +199 -0
  3. text2pose.py +196 -9
README.md CHANGED
@@ -16,11 +16,11 @@ The entire project is divided into two parts: `text_or_gloss2pose` and `pose2vid
16
  first, change `good morning afternoon`, and run:
17
 
18
  ```python
19
- python text2pose.py --gloss "good morning afternoon" --scale-y 1.3 --scale-x 1.2 --npz-interpolation 20 --width 512 --height 768 --fps 30 --hide-torso-lines true --ref-image-path ref_img_dict/01.jpeg
20
 
21
  or
22
 
23
- python text2pose.py --gloss "where is my cat" --scale-y 1.4 --scale-x 1.3 --npz-interpolation 20 --width 512 --height 768 --fps 30 --hide-torso-lines false
24
  ```
25
 
26
  second, change `generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832.mp4` & `ref_img_dict/03.jpeg`, and run:
 
16
  first, change `good morning afternoon`, and run:
17
 
18
  ```python
19
+ python text2pose.py --gloss "good morning afternoon" --scale-y 1.4 --scale-x 1.3 --npz-interpolation 20 --width 512 --height 768 --fps 30 --hide-torso-lines true --ref-image-path ref_img_dict/01.jpeg
20
 
21
  or
22
 
23
+ python text2pose.py --gloss "where is my cat" --scale-y 1.5 --scale-x 1.5 --npz-interpolation 20 --width 512 --height 512 --fps 30 --hide-torso-lines false
24
  ```
25
 
26
  second, change `generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832.mp4` & `ref_img_dict/03.jpeg`, and run:
README_v1.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Intro
2
+
3
+ The entire project is divided into two parts: `text_or_gloss2pose` and `pose2video`. "Pose" here refers to the skeleton pose video after drawing.
4
+
5
+ - In the text2pose section (`Expected 4 seconds / one video`), I first used the DWpose tool to extract the npz format pose information for each word video frame by frame, and then merged each frame's npz into a large npz file. That is to say, we know the consecutive poses corresponding to each word. These consecutive poses are stored in the merged npz file. (We can also use deep learning models to generate these poses, but for commercial-level accuracy, this original data Dict method will be much more accurate.)
6
+
7
+ - In the pose2video section (`Expected 6 minutes / one video`), we render the visualized poses of the skeletons generated by each word. I used the ControlNext-SVD model for this.
8
+
9
+ # For Users
10
+
11
+ 1. cd StableSigner
12
+ 2. conda env create -f env/environment02_controlnext.yml
13
+ 3. run `conda activate controlnext`
14
+ 4. run `pip install -r env/requirements02_controlnext.txt`
15
+
16
+ first, change `good morning afternoon`, and run:
17
+
18
+ ```python
19
+ python text2pose.py --gloss "good morning afternoon" --scale-y 1.3 --scale-x 1.2 --npz-interpolation 20 --width 512 --height 768 --fps 30 --hide-torso-lines true --ref-image-path ref_img_dict/01.jpeg
20
+
21
+ or
22
+
23
+ python text2pose.py --gloss "where is my cat" --scale-y 1.4 --scale-x 1.3 --npz-interpolation 20 --width 512 --height 768 --fps 30 --hide-torso-lines false
24
+ ```
25
+
26
+ second, change `generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832.mp4` & `ref_img_dict/03.jpeg`, and run:
27
+
28
+ ```python
29
+ CUDA_VISIBLE_DEVICES=0 python ControlNeXt-SVD-v2/run_controlnext_optimized.py \
30
+ --pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
31
+ --output_dir generated_sign_video \
32
+ --max_frame_num 240 \
33
+ --guidance_scale 3 \
34
+ --batch_frames 24 \
35
+ --sample_stride 2 \
36
+ --overlap 4 \
37
+ --height 768 \
38
+ --width 512 \
39
+ --controlnext_path ControlNeXt-SVD-v2/pretrained/controlnet.bin \
40
+ --unet_path ControlNeXt-SVD-v2/pretrained/unet.bin \
41
+ --pose_video_path generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832.mp4 \
42
+ --ref_image_path ref_img_dict/03.jpeg \
43
+ --precision fp16 \
44
+ --decode_chunk_size 2 \
45
+ --enable_geglu_optimization \
46
+ --enable_xformers
47
+ ```
48
+
49
+ **Note:** In fact, I haven't installed xformer and haven't conducted a comprehensive test of it. If not installed, it will not affect the normal operation.
50
+
51
+ **Note:** It seems that the first time using pose2vid will result in poor quality and speed, and some kind of warm-up is necessary.
52
+
53
+ **Note:** I have tried running two stages with a resolution of `512*512`, but it seems that it causes instability in the background.
54
+
55
+ **Note:** In some cases, `512w*768h` can cause abnormalities in the torso. In rare instances, the torso may be mistaken for a hand. This issue should be able to be resolved by hiding the torso.
56
+
57
+ **BUG:** For some unknown reason, the current robustness is not as good as before (24.12 of the demos I tried were better than the current pose2video). The background is relatively prone to change, and the bottom part of the upper body is prone to become blurry. I have taken two or three improvements to solve this problem, but so far, it seems to still occur strangely and persistently. If this phenomenon continues, I am considering directly using Docker in 24.12 as a replacement. (Later, I discovered that simply using Docker did not lead to any significant improvement: Just the background and the hands became a little more stable. I felt that I needed to try to find the most stable configuration.)
58
+
59
+
60
+ ## Demo Gallery
61
+
62
+ <details>
63
+ <summary>🎬 Click to view generated examples</summary>
64
+
65
+ ### Example 1: "good morning afternoon"
66
+
67
+ <div align="center">
68
+ <h4>Pose Video & Final Video</h4>
69
+ <video width="80%" controls>
70
+ <source src="https://huggingface.co/datasets/FangSen9000/StableSigner/resolve/main/generated_sign_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832_combined.mp4" type="video/mp4">
71
+ Your browser does not support the video tag.
72
+ </video>
73
+ </div>
74
+
75
+ ---
76
+
77
+ ### Example 2: "hello world"
78
+
79
+ <div align="center">
80
+ <h4>Pose Video & Final Video</h4>
81
+ <video width="80%" controls>
82
+ <source src="https://huggingface.co/datasets/FangSen9000/StableSigner/resolve/main/generated_sign_video/HELLO_WORLD_27184_63831_20250804_163910_combined.mp4" type="video/mp4">
83
+ Your browser does not support the video tag.
84
+ </video>
85
+ </div>
86
+
87
+ ---
88
+
89
+ ### Example 3: "I will attend this dinner party"
90
+
91
+ <div align="center">
92
+ <h4>Pose Video & Final Video</h4>
93
+ <video width="80%" controls>
94
+ <source src="https://huggingface.co/datasets/FangSen9000/StableSigner/resolve/main/generated_sign_video/I_WILL_ATTEND_THIS_DINNER_PARTY_28794_63364_04007_66628_16327_41325_20250804_164010_combined.mp4" type="video/mp4">
95
+ Your browser does not support the video tag.
96
+ </video>
97
+ </div>
98
+
99
+ ---
100
+
101
+ ### Example 4: "not find yet"
102
+
103
+ <div align="center">
104
+ <h4>Pose Video & Final Video</h4>
105
+ <video width="80%" controls>
106
+ <source src="https://huggingface.co/datasets/FangSen9000/StableSigner/resolve/main/generated_sign_video/NOT_FIND_YET_38868_21853_18535_20250804_164149_combined.mp4" type="video/mp4">
107
+ Your browser does not support the video tag.
108
+ </video>
109
+ </div>
110
+
111
+ ---
112
+
113
+ ### Example 5: "where is my cat"
114
+
115
+ <div align="center">
116
+ <h4>Pose Video & Final Video</h4>
117
+ <video width="80%" controls>
118
+ <source src="https://huggingface.co/datasets/FangSen9000/StableSigner/resolve/main/generated_sign_video/WHERE_IS_MY_CAT_63084_57261_37469_65313_20250804_164233_combined.mp4" type="video/mp4">
119
+ Your browser does not support the video tag.
120
+ </video>
121
+ </div>
122
+
123
+ ### Note on video types:
124
+ - **Pose video**: Shows the skeleton/pose generated from input text/gloss
125
+ - **Final video**: The rendered sign language video with a virtual signer
126
+ - **Combined view**: Side-by-side comparison of pose and final video
127
+
128
+ </details>
129
+ <br>
130
+
131
+ # For developers
132
+
133
+ 1. git clone https://huggingface.co/datasets/FangSen9000/StableSigner
134
+ 2. cd StableSigner
135
+
136
+ ## tutorial00 Use DWpose to preprocess the original sign language video
137
+
138
+ `tools-new-2025` is a tool that can extract the original video into a npz file containing dwpose skeleton posture information (a type of skeleton posture that is almost compatible with all current pose2video models).
139
+
140
+ 1. conda env create -f env/environment01_dwpose.yml
141
+ 2. run `conda activate dwpose`
142
+ 3. run `pip install -r env/requirements01_dwpose.txt`
143
+ 4. put raw sign viseos, like `tools-new-2025/input/test_dataset`
144
+ 5. cd `StableSigner/tools-new-2025/main`
145
+ 6. run `python pipeline00_extract_split_video_to_image.py` (Default frame rate is 30fps, and the video will be automatically cropped to a square shape.)
146
+ 7. run `python pipeline01_extract_dwpose_from_video.py` (It will generate files other than npz. We usually don't need them and can comment out the relevant code.)
147
+ 8. run `conda deactivate`, we finish the preprocess.
148
+
149
+ ## tutorial01 prepare pose dict
150
+
151
+ 1. cd StableSigner
152
+ 2. run `python utils/pipeline01_merge_frame_level_npz_from_video_dir.py tools-new-2025/output/test_dataset_results`
153
+ 3. Place the corresponding "gloss-videoID" mapping in the pose dict
154
+
155
+ ## tutorial02 get pose video from text input
156
+
157
+ ```python
158
+
159
+ # Default
160
+ python text2pose.py --gloss "good morning afternoon" --npz-interpolation 20 --width 512 --height 768 --fps 30
161
+
162
+ # Single gloss
163
+ python text2pose.py --gloss "hello"
164
+
165
+ # Multiple glosses with smoothing
166
+ python text2pose.py --gloss "hello world" --smoothing fade --smoothing-frames 5
167
+
168
+ # Custom video parameters
169
+ python text2pose.py --gloss "good afternoon" --width 512 --height 768 --fps 30
170
+ ```
171
+
172
+ ## tutorial03 render pose video
173
+
174
+ 1. cd StableSigner
175
+ 2. conda env create -f env/environment02_controlnext.yml
176
+ 3. run `conda activate controlnext`
177
+ 4. run `pip install -r env/requirements02_controlnext.txt`
178
+
179
+ ```python
180
+ CUDA_VISIBLE_DEVICES=0 python ControlNeXt-SVD-v2/run_controlnext_optimized.py \
181
+ --pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
182
+ --output_dir generated_sign_video \
183
+ --max_frame_num 240 \
184
+ --guidance_scale 3 \
185
+ --batch_frames 24 \
186
+ --sample_stride 2 \
187
+ --overlap 4 \
188
+ --height 768 \
189
+ --width 512 \
190
+ --controlnext_path ControlNeXt-SVD-v2/pretrained/controlnet.bin \
191
+ --unet_path ControlNeXt-SVD-v2/pretrained/unet.bin \
192
+ --pose_video_path generated_pose_video/GOOD_MORNING_AFTERNOON_25073_36863_01435_20250804_160832.mp4 \
193
+ --ref_image_path ref_img_dict/03.jpeg \
194
+ --precision fp16 \
195
+ --decode_chunk_size 2 \
196
+ --enable_geglu_optimization \
197
+ --enable_xformers
198
+ ```
199
+
text2pose.py CHANGED
@@ -88,8 +88,10 @@ class SignLanguageQA:
88
  return None
89
 
90
  try:
91
- data = np.load(npz_path, allow_pickle=True)
92
- return data
 
 
93
  except Exception as e:
94
  print(f" ⚠️ Failed to load NPZ: {e}")
95
  return None
@@ -411,26 +413,198 @@ class SignLanguageQA:
411
  def apply_y_offset(self, frame_data, y_offset):
412
  """Apply vertical offset to all pose points"""
413
  offset_data = copy.deepcopy(frame_data)
414
-
415
  # Apply offset to bodies
416
  if 'bodies' in offset_data and offset_data['bodies'] is not None:
417
  offset_data['bodies'][:, 1] += y_offset
418
-
419
  # Apply offset to hands
420
  if 'hands' in offset_data and offset_data['hands'] is not None:
421
  if len(offset_data['hands'].shape) == 3:
422
  offset_data['hands'][:, :, 1] += y_offset
423
  else:
424
  offset_data['hands'][:, 1] += y_offset
425
-
426
  # Apply offset to faces
427
  if 'faces' in offset_data and offset_data['faces'] is not None:
428
  if len(offset_data['faces'].shape) == 3:
429
  offset_data['faces'][:, :, 1] += y_offset
430
  else:
431
  offset_data['faces'][:, 1] += y_offset
432
-
433
  return offset_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
 
435
  def get_reference_head_top(self, ref_image_path, width, height):
436
  """Get the top of head position from reference image"""
@@ -560,11 +734,13 @@ class SignLanguageQA:
560
 
561
  def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
562
  smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
563
- scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None, draw_style='controlnext'):
 
564
  """Generate video from gloss list with optional progressive scaling and head alignment
565
 
566
  Args:
567
  draw_style: 'controlnext' (default) or 'openpose' - drawing style for pose visualization
 
568
  """
569
  # Create output directory
570
  output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -642,6 +818,10 @@ class SignLanguageQA:
642
  print(f" 🎯 Centrality score: {centrality_score:.2f} (selected from {len(candidate_videos)} candidates)")
643
  print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")
644
 
 
 
 
 
645
  # Store NPZ data for potential interpolation
646
  all_npz_data.append(npz_data)
647
 
@@ -1057,6 +1237,8 @@ def main():
1057
  help='Reference image path for head alignment')
1058
  parser.add_argument('--draw-style', type=str, choices=['controlnext', 'openpose'], default='controlnext',
1059
  help='Drawing style for pose visualization. controlnext: advanced features with confidence-based coloring. openpose: simpler classic style. (default: controlnext)')
 
 
1060
 
1061
  args = parser.parse_args()
1062
 
@@ -1091,11 +1273,16 @@ def main():
1091
  if args.draw_style != 'controlnext':
1092
  print(f"🎨 Using {args.draw_style} drawing style")
1093
 
 
 
 
 
 
1094
  success = qa_system.generate_video_from_glosses(
1095
  gloss_list, output_file, args.fps, args.width, args.height,
1096
  args.smoothing_frames, args.smoothing, args.npz_interpolation,
1097
  args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
1098
- args.ref_image_path, args.draw_style
1099
  )
1100
 
1101
  if not success:
@@ -1106,4 +1293,4 @@ def main():
1106
 
1107
 
1108
  if __name__ == "__main__":
1109
- main()
 
88
  return None
89
 
90
  try:
91
+ npz_file = np.load(npz_path, allow_pickle=True)
92
+ npz_dict = {key: npz_file[key] for key in npz_file.files}
93
+ npz_file.close()
94
+ return npz_dict
95
  except Exception as e:
96
  print(f" ⚠️ Failed to load NPZ: {e}")
97
  return None
 
413
  def apply_y_offset(self, frame_data, y_offset):
414
  """Apply vertical offset to all pose points"""
415
  offset_data = copy.deepcopy(frame_data)
416
+
417
  # Apply offset to bodies
418
  if 'bodies' in offset_data and offset_data['bodies'] is not None:
419
  offset_data['bodies'][:, 1] += y_offset
420
+
421
  # Apply offset to hands
422
  if 'hands' in offset_data and offset_data['hands'] is not None:
423
  if len(offset_data['hands'].shape) == 3:
424
  offset_data['hands'][:, :, 1] += y_offset
425
  else:
426
  offset_data['hands'][:, 1] += y_offset
427
+
428
  # Apply offset to faces
429
  if 'faces' in offset_data and offset_data['faces'] is not None:
430
  if len(offset_data['faces'].shape) == 3:
431
  offset_data['faces'][:, :, 1] += y_offset
432
  else:
433
  offset_data['faces'][:, 1] += y_offset
434
+
435
  return offset_data
436
+
437
+ def normalize_pose_data(self, npz_data, reference_point='neck', scale_by='shoulders',
438
+ target_shoulder_width=0.35, target_shoulder_y=0.45):
439
+ """
440
+ Normalize pose data to a standard coordinate system
441
+ This ensures different videos are in the same coordinate space
442
+
443
+ Args:
444
+ npz_data: NPZ data containing pose information
445
+ reference_point: 'neck' or 'hips' - point to center on (default: 'neck')
446
+ scale_by: 'shoulders' or 'height' - measure for scaling (default: 'shoulders')
447
+ target_shoulder_width: Desired horizontal distance between shoulders after normalization
448
+ target_shoulder_y: Desired Y coordinate for the shoulder line
449
+
450
+ Returns:
451
+ Normalized NPZ data (modifies in-place)
452
+ """
453
+ total_frames = self.get_total_frames(npz_data)
454
+ if total_frames == 0:
455
+ return npz_data
456
+
457
+ # Collect reference points, scale factors, and shoulder heights across all frames
458
+ reference_positions = []
459
+ scale_factors = []
460
+ shoulder_y_positions = []
461
+
462
+ for frame_num in range(1, total_frames + 1):
463
+ frame_data = self.get_frame_data(npz_data, frame_num)
464
+ if not frame_data or 'bodies' not in frame_data:
465
+ continue
466
+
467
+ bodies = frame_data['bodies']
468
+ if bodies is None or len(bodies) == 0:
469
+ continue
470
+
471
+ # Calculate reference point
472
+ if reference_point == 'neck':
473
+ # Neck is typically index 1 in body keypoints
474
+ if len(bodies) > 1 and bodies[1, 0] > 0 and bodies[1, 1] > 0:
475
+ ref_pos = bodies[1, :2].copy()
476
+ else:
477
+ continue
478
+ elif reference_point == 'hips':
479
+ # Hip center: average of left hip (11) and right hip (12)
480
+ if len(bodies) > 12:
481
+ left_hip = bodies[11, :2]
482
+ right_hip = bodies[12, :2]
483
+ if left_hip[0] > 0 and right_hip[0] > 0:
484
+ ref_pos = (left_hip + right_hip) / 2
485
+ else:
486
+ continue
487
+ else:
488
+ continue
489
+ else:
490
+ continue
491
+
492
+ reference_positions.append(ref_pos)
493
+
494
+ # Calculate scale factor
495
+ if scale_by == 'shoulders':
496
+ # Shoulder width: distance between left shoulder (5) and right shoulder (2)
497
+ if len(bodies) > 5:
498
+ left_shoulder = bodies[5, :2]
499
+ right_shoulder = bodies[2, :2]
500
+ if left_shoulder[0] > 0 and right_shoulder[0] > 0:
501
+ shoulder_width = np.linalg.norm(left_shoulder - right_shoulder)
502
+ if shoulder_width > 0.01: # Avoid division by very small numbers
503
+ scale_factors.append(shoulder_width)
504
+ shoulder_mid_y = (left_shoulder[1] + right_shoulder[1]) / 2
505
+ shoulder_y_positions.append(shoulder_mid_y)
506
+ elif scale_by == 'height':
507
+ # Approximate height: distance from neck to hip center
508
+ if len(bodies) > 12:
509
+ neck = bodies[1, :2]
510
+ left_hip = bodies[11, :2]
511
+ right_hip = bodies[12, :2]
512
+ if neck[1] > 0 and left_hip[0] > 0 and right_hip[0] > 0:
513
+ hip_center = (left_hip + right_hip) / 2
514
+ height = np.linalg.norm(neck - hip_center)
515
+ if height > 0.01:
516
+ scale_factors.append(height)
517
+
518
+ if not reference_positions or not scale_factors:
519
+ print(" ⚠️ Normalization skipped: insufficient valid frames")
520
+ return npz_data
521
+
522
+ # Use median reference position and scale factor for robustness
523
+ median_ref_pos = np.median(reference_positions, axis=0)
524
+ median_scale = np.median(scale_factors)
525
+
526
+ median_shoulder_y = np.median(shoulder_y_positions) if shoulder_y_positions else median_ref_pos[1]
527
+
528
+ print(f" 📏 Normalization: ref={reference_point}, scale={scale_by}")
529
+ print(f" Reference position: ({median_ref_pos[0]:.3f}, {median_ref_pos[1]:.3f})")
530
+ print(f" Median shoulder y: {median_shoulder_y:.3f}")
531
+ print(f" Median shoulder width: {median_scale:.3f} → target {target_shoulder_width:.3f}")
532
+
533
+ # Determine uniform scaling factor so shoulders match the desired width
534
+ width_scale = target_shoulder_width / median_scale if median_scale > 0 else 1.0
535
+
536
+ # Neck-centered offset already moves the neck to 0.5; compute extra offset so shoulders sit at desired y
537
+ shoulder_delta_from_neck = median_shoulder_y - median_ref_pos[1]
538
+ normalized_shoulder_y = 0.5 + shoulder_delta_from_neck * width_scale
539
+ vertical_offset = target_shoulder_y - normalized_shoulder_y
540
+
541
+ # Apply normalization to all frames
542
+ for frame_num in range(1, total_frames + 1):
543
+ frame_key = f"frame_{frame_num:08d}"
544
+
545
+ # Normalize bodies
546
+ bodies_key = f"{frame_key}_bodies"
547
+ if bodies_key in npz_data:
548
+ bodies = npz_data[bodies_key].copy()
549
+ if bodies is not None and len(bodies) > 0:
550
+ # Center on reference point
551
+ for i in range(len(bodies)):
552
+ if bodies[i, 0] > 0 and bodies[i, 1] > 0:
553
+ bodies[i, :2] = (bodies[i, :2] - median_ref_pos) * width_scale + 0.5
554
+ bodies[i, 1] += vertical_offset
555
+
556
+ # Clamp to drawing range
557
+ bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
558
+ bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
559
+ npz_data[bodies_key] = bodies
560
+
561
+ # Normalize hands
562
+ hands_key = f"{frame_key}_hands"
563
+ if hands_key in npz_data:
564
+ hands = npz_data[hands_key].copy()
565
+ if hands is not None:
566
+ if len(hands.shape) == 3:
567
+ # Multiple hands
568
+ for h in range(hands.shape[0]):
569
+ for i in range(hands.shape[1]):
570
+ if hands[h, i, 0] > 0 and hands[h, i, 1] > 0:
571
+ hands[h, i, :2] = (hands[h, i, :2] - median_ref_pos) * width_scale + 0.5
572
+ hands[h, i, 1] += vertical_offset
573
+ else:
574
+ # Single array
575
+ for i in range(len(hands)):
576
+ if hands[i, 0] > 0 and hands[i, 1] > 0:
577
+ hands[i, :2] = (hands[i, :2] - median_ref_pos) * width_scale + 0.5
578
+ hands[i, 1] += vertical_offset
579
+
580
+ hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0)
581
+ hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0)
582
+ npz_data[hands_key] = hands
583
+
584
+ # Normalize faces
585
+ faces_key = f"{frame_key}_faces"
586
+ if faces_key in npz_data:
587
+ faces = npz_data[faces_key].copy()
588
+ if faces is not None:
589
+ if len(faces.shape) == 3:
590
+ # Multiple faces
591
+ for f in range(faces.shape[0]):
592
+ for i in range(faces.shape[1]):
593
+ if faces[f, i, 0] > 0 and faces[f, i, 1] > 0:
594
+ faces[f, i, :2] = (faces[f, i, :2] - median_ref_pos) * width_scale + 0.5
595
+ faces[f, i, 1] += vertical_offset
596
+ else:
597
+ # Single array
598
+ for i in range(len(faces)):
599
+ if faces[i, 0] > 0 and faces[i, 1] > 0:
600
+ faces[i, :2] = (faces[i, :2] - median_ref_pos) * width_scale + 0.5
601
+ faces[i, 1] += vertical_offset
602
+
603
+ faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
604
+ faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
605
+ npz_data[faces_key] = faces
606
+
607
+ return npz_data
608
 
609
  def get_reference_head_top(self, ref_image_path, width, height):
610
  """Get the top of head position from reference image"""
 
734
 
735
  def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
736
  smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
737
+ scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None, draw_style='controlnext',
738
+ normalize_pose=True):
739
  """Generate video from gloss list with optional progressive scaling and head alignment
740
 
741
  Args:
742
  draw_style: 'controlnext' (default) or 'openpose' - drawing style for pose visualization
743
+ normalize_pose: Whether to normalize pose data to standard coordinate system (default: True)
744
  """
745
  # Create output directory
746
  output_path.parent.mkdir(parents=True, exist_ok=True)
 
818
  print(f" 🎯 Centrality score: {centrality_score:.2f} (selected from {len(candidate_videos)} candidates)")
819
  print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")
820
 
821
+ # Apply normalization if enabled
822
+ if normalize_pose:
823
+ npz_data = self.normalize_pose_data(npz_data, reference_point='neck', scale_by='shoulders')
824
+
825
  # Store NPZ data for potential interpolation
826
  all_npz_data.append(npz_data)
827
 
 
1237
  help='Reference image path for head alignment')
1238
  parser.add_argument('--draw-style', type=str, choices=['controlnext', 'openpose'], default='controlnext',
1239
  help='Drawing style for pose visualization. controlnext: advanced features with confidence-based coloring. openpose: simpler classic style. (default: controlnext)')
1240
+ parser.add_argument('--normalize-pose', type=str, choices=['true', 'false'], default='true',
1241
+ help='Normalize pose data to standard coordinate system. This ensures different videos are in the same coordinate space, reducing inconsistency from different video sources. (default: true)')
1242
 
1243
  args = parser.parse_args()
1244
 
 
1273
  if args.draw_style != 'controlnext':
1274
  print(f"🎨 Using {args.draw_style} drawing style")
1275
 
1276
+ if args.normalize_pose == 'true':
1277
+ print(f"📏 Pose normalization enabled")
1278
+ else:
1279
+ print(f"⚠️ Pose normalization disabled")
1280
+
1281
  success = qa_system.generate_video_from_glosses(
1282
  gloss_list, output_file, args.fps, args.width, args.height,
1283
  args.smoothing_frames, args.smoothing, args.npz_interpolation,
1284
  args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
1285
+ args.ref_image_path, args.draw_style, args.normalize_pose == 'true'
1286
  )
1287
 
1288
  if not success:
 
1293
 
1294
 
1295
  if __name__ == "__main__":
1296
+ main()