FangSen9000 commited on
Commit
0ebe26e
·
1 Parent(s): 9a3b4f8

Discard the npz frames that cause black screen during generation

Browse files
README.md CHANGED
@@ -8,6 +8,8 @@ The entire project is divided into two parts: `text_or_gloss2pose` and `pose2vid
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`
 
8
 
9
  # For Users
10
 
11
+ **Note:** It seems that the first time using pose2vid will result in poor quality and speed, and some kind of warm-up is necessary.
12
+
13
  1. cd StableSigner
14
  2. conda env create -f env/environment02_controlnext.yml
15
  3. run `conda activate controlnext`
text2pose.py CHANGED
@@ -90,6 +90,105 @@ class SignLanguageQA:
90
  except Exception as e:
91
  print(f" ⚠️ Failed to load NPZ: {e}")
92
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  def get_frame_data(self, npz_data, frame_num):
95
  """Extract frame data from NPZ"""
@@ -149,21 +248,40 @@ class SignLanguageQA:
149
 
150
  print(f"🎯 '{gloss}' -> Found {len(matched_videos)} videos")
151
 
152
- # Use first available video
153
- for video_id in matched_videos:
 
154
  npz_data = self.load_video_npz(video_id)
155
  if npz_data is not None:
156
  total_frames = self.get_total_frames(npz_data)
157
  print(f" 📹 {video_id}: {total_frames} frames")
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  # Store NPZ data for potential interpolation
160
  all_npz_data.append(npz_data)
161
 
162
- # Extract all frames for this video
163
  gloss_frames = []
164
- for frame_num in range(1, total_frames + 1):
165
  frame_data = self.get_frame_data(npz_data, frame_num)
166
- if frame_data:
167
  pose_frame = self.create_pose_frame(frame_data, width, height)
168
  if pose_frame is not None:
169
  gloss_frames.append(pose_frame)
@@ -174,10 +292,16 @@ class SignLanguageQA:
174
  'gloss': gloss,
175
  'video_id': video_id,
176
  'frame_count': len(gloss_frames),
177
- 'npz_data': npz_data
 
 
178
  })
179
  print(f" ✅ Generated {len(gloss_frames)} pose frames")
 
180
  break # Use only first valid video per gloss
 
 
 
181
 
182
  if not all_pose_frames:
183
  print("❌ No frames generated")
@@ -198,11 +322,17 @@ class SignLanguageQA:
198
  npz1 = video_info[i]['npz_data']
199
  npz2 = video_info[i + 1]['npz_data']
200
 
 
 
 
 
201
  # Interpolate between the two NPZ files
202
  interpolated_npz_frames = interpolate_pose_npz(
203
  npz1, npz2,
204
  num_frames=npz_interpolation_frames,
205
- method='catmull-rom'
 
 
206
  )
207
 
208
  # Convert interpolated NPZ frames to visual frames
 
90
  except Exception as e:
91
  print(f" ⚠️ Failed to load NPZ: {e}")
92
  return None
93
+
94
+ def check_frame_quality(self, frame_data):
95
+ """Check if a frame has valid pose data based on confidence scores"""
96
+ if not frame_data:
97
+ return False
98
+
99
+ # Check hand scores (most critical for sign language)
100
+ if 'hands_scores' in frame_data:
101
+ hands_scores = frame_data['hands_scores']
102
+ if hands_scores is not None and len(hands_scores) > 0:
103
+ # Check if more than 80% of hand points have negative confidence
104
+ valid_scores = hands_scores[hands_scores >= 0]
105
+ if len(valid_scores) < len(hands_scores) * 0.2:
106
+ return False
107
+
108
+ # Check body scores
109
+ if 'body_scores' in frame_data:
110
+ body_scores = frame_data['body_scores']
111
+ if body_scores is not None and len(body_scores) > 0:
112
+ valid_scores = body_scores[body_scores >= 0]
113
+ if len(valid_scores) < len(body_scores) * 0.2:
114
+ return False
115
+
116
+ return True
117
+
118
+ def check_video_quality(self, npz_data, check_frames=5, extended_check_frames=30):
119
+ """Check video quality by examining start and end frames"""
120
+ total_frames = self.get_total_frames(npz_data)
121
+ if total_frames == 0:
122
+ return False, "No frames found"
123
+
124
+ # Check first and last N frames
125
+ problematic_start = 0
126
+ problematic_end = 0
127
+
128
+ # Check start frames
129
+ for i in range(1, min(check_frames + 1, total_frames + 1)):
130
+ frame_data = self.get_frame_data(npz_data, i)
131
+ if not self.check_frame_quality(frame_data):
132
+ problematic_start += 1
133
+
134
+ # Check end frames
135
+ for i in range(max(1, total_frames - check_frames + 1), total_frames + 1):
136
+ frame_data = self.get_frame_data(npz_data, i)
137
+ if not self.check_frame_quality(frame_data):
138
+ problematic_end += 1
139
+
140
+ # If more than 3 frames are problematic, do extended check
141
+ if problematic_start >= 3 or problematic_end >= 3:
142
+ print(f" ⚠️ Initial check found {problematic_start} bad start frames, {problematic_end} bad end frames")
143
+
144
+ # Extended check
145
+ problematic_start_extended = 0
146
+ problematic_end_extended = 0
147
+
148
+ for i in range(1, min(extended_check_frames + 1, total_frames + 1)):
149
+ frame_data = self.get_frame_data(npz_data, i)
150
+ if not self.check_frame_quality(frame_data):
151
+ problematic_start_extended += 1
152
+
153
+ for i in range(max(1, total_frames - extended_check_frames + 1), total_frames + 1):
154
+ frame_data = self.get_frame_data(npz_data, i)
155
+ if not self.check_frame_quality(frame_data):
156
+ problematic_end_extended += 1
157
+
158
+ # If too many bad frames, reject video
159
+ if problematic_start_extended > extended_check_frames * 0.5 or \
160
+ problematic_end_extended > extended_check_frames * 0.5:
161
+ return False, f"Too many bad frames: {problematic_start_extended} start, {problematic_end_extended} end"
162
+
163
+ return True, f"Quality check passed (bad frames: {problematic_start} start, {problematic_end} end)"
164
+
165
+ def get_valid_frame_range(self, npz_data, margin=5):
166
+ """Get the range of valid frames, excluding bad frames at start/end"""
167
+ total_frames = self.get_total_frames(npz_data)
168
+ if total_frames == 0:
169
+ return 1, 0
170
+
171
+ # Find first valid frame
172
+ start_frame = 1
173
+ for i in range(1, min(margin + 1, total_frames + 1)):
174
+ frame_data = self.get_frame_data(npz_data, i)
175
+ if self.check_frame_quality(frame_data):
176
+ start_frame = i
177
+ break
178
+ else:
179
+ start_frame = i + 1
180
+
181
+ # Find last valid frame
182
+ end_frame = total_frames
183
+ for i in range(total_frames, max(0, total_frames - margin), -1):
184
+ frame_data = self.get_frame_data(npz_data, i)
185
+ if self.check_frame_quality(frame_data):
186
+ end_frame = i
187
+ break
188
+ else:
189
+ end_frame = i - 1
190
+
191
+ return start_frame, end_frame
192
 
193
  def get_frame_data(self, npz_data, frame_num):
194
  """Extract frame data from NPZ"""
 
248
 
249
  print(f"🎯 '{gloss}' -> Found {len(matched_videos)} videos")
250
 
251
+ # Try each video until we find one with good quality
252
+ video_found = False
253
+ for idx, video_id in enumerate(matched_videos):
254
  npz_data = self.load_video_npz(video_id)
255
  if npz_data is not None:
256
  total_frames = self.get_total_frames(npz_data)
257
  print(f" 📹 {video_id}: {total_frames} frames")
258
 
259
+ # Check video quality
260
+ is_good_quality, quality_msg = self.check_video_quality(npz_data)
261
+
262
+ if not is_good_quality:
263
+ print(f" ❌ Video quality check failed: {quality_msg}")
264
+ if idx < len(matched_videos) - 1:
265
+ print(f" 🔄 Trying next video for '{gloss}'...")
266
+ continue
267
+
268
+ # Get valid frame range
269
+ start_frame, end_frame = self.get_valid_frame_range(npz_data)
270
+ if start_frame > end_frame:
271
+ print(f" ❌ No valid frames found in video")
272
+ continue
273
+
274
+ print(f" ✅ {quality_msg}")
275
+ print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")
276
+
277
  # Store NPZ data for potential interpolation
278
  all_npz_data.append(npz_data)
279
 
280
+ # Extract frames within valid range
281
  gloss_frames = []
282
+ for frame_num in range(start_frame, end_frame + 1):
283
  frame_data = self.get_frame_data(npz_data, frame_num)
284
+ if frame_data and self.check_frame_quality(frame_data):
285
  pose_frame = self.create_pose_frame(frame_data, width, height)
286
  if pose_frame is not None:
287
  gloss_frames.append(pose_frame)
 
292
  'gloss': gloss,
293
  'video_id': video_id,
294
  'frame_count': len(gloss_frames),
295
+ 'npz_data': npz_data,
296
+ 'start_frame': start_frame,
297
+ 'end_frame': end_frame
298
  })
299
  print(f" ✅ Generated {len(gloss_frames)} pose frames")
300
+ video_found = True
301
  break # Use only first valid video per gloss
302
+
303
+ if not video_found:
304
+ print(f" ❌ No suitable video found for '{gloss}' after checking {len(matched_videos)} candidates")
305
 
306
  if not all_pose_frames:
307
  print("❌ No frames generated")
 
322
  npz1 = video_info[i]['npz_data']
323
  npz2 = video_info[i + 1]['npz_data']
324
 
325
+ # Get valid frame ranges for interpolation
326
+ end_frame1 = video_info[i].get('end_frame', self.get_total_frames(npz1))
327
+ start_frame2 = video_info[i + 1].get('start_frame', 1)
328
+
329
  # Interpolate between the two NPZ files
330
  interpolated_npz_frames = interpolate_pose_npz(
331
  npz1, npz2,
332
  num_frames=npz_interpolation_frames,
333
+ method='catmull-rom',
334
+ frame1_num=end_frame1,
335
+ frame2_num=start_frame2
336
  )
337
 
338
  # Convert interpolated NPZ frames to visual frames
utils/__pycache__/npz_interpolation.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/npz_interpolation.cpython-310.pyc and b/utils/__pycache__/npz_interpolation.cpython-310.pyc differ
 
utils/npz_interpolation.py CHANGED
@@ -64,48 +64,24 @@ def catmull_rom_spline(p0, p1, p2, p3, num_points, tension=0.5):
64
  """
65
  points = []
66
 
67
- # Check for invalid points (coordinates that are 0, -1, or out of reasonable bounds)
68
- def is_valid_point(p):
69
- if isinstance(p, np.ndarray):
70
- # Check if any coordinate is -1, 0, or unreasonably large
71
- return np.all(p > 0) and np.all(p < 2000) # Assuming 2000 is max reasonable coordinate
72
- return False
73
-
74
- # If endpoints are invalid, fall back to linear interpolation
75
- if not is_valid_point(p1) or not is_valid_point(p2):
76
- # Simple linear interpolation for invalid points
77
- for i in range(num_points):
78
- t = i / (num_points - 1)
79
- point = p1 * (1 - t) + p2 * t
80
- points.append(point)
81
- return np.array(points)
82
-
83
  for i in range(num_points):
84
  t = i / (num_points - 1)
85
  t2 = t * t
86
  t3 = t2 * t
87
 
88
- # Catmull-Rom basis functions with clamping to prevent overshoot
89
  v0 = -tension * t + 2 * tension * t2 - tension * t3
90
  v1 = 1 + (tension - 3) * t2 + (2 - tension) * t3
91
  v2 = tension * t + (3 - 2 * tension) * t2 + (tension - 2) * t3
92
  v3 = -tension * t2 + tension * t3
93
 
94
- # Use valid control points or fall back to endpoints
95
- p0_safe = p0 if is_valid_point(p0) else p1
96
- p3_safe = p3 if is_valid_point(p3) else p2
97
-
98
- point = v0 * p0_safe + v1 * p1 + v2 * p2 + v3 * p3_safe
99
-
100
- # Clamp to reasonable bounds to prevent extreme values
101
- point = np.clip(point, 0, 2000)
102
-
103
  points.append(point)
104
 
105
  return np.array(points)
106
 
107
 
108
- def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom'):
109
  """
110
  Interpolate between two pose NPZ data structures
111
 
@@ -114,32 +90,50 @@ def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-ro
114
  npz2_data: Dictionary containing pose data from second NPZ
115
  num_frames: Number of transition frames to generate
116
  method: Interpolation method ('linear', 'cubic', 'catmull-rom')
 
 
117
 
118
  Returns:
119
  List of interpolated pose data dictionaries
120
  """
121
  interpolated_frames = []
122
 
123
- # Extract keypoints from the last frame of first video and first frame of second
124
  # Assume format: frame_XXXXXXXX_bodies, frame_XXXXXXXX_hands, etc.
125
 
126
- # Get the last frame from npz1
127
- frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])
128
- if not frame_keys1:
129
- return []
130
- last_frame_key1 = frame_keys1[-1]
131
- frame_num1 = last_frame_key1.split('_')[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- # Get the first frame from npz2
134
- frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])
135
- if not frame_keys2:
136
- return []
137
- first_frame_key2 = frame_keys2[0]
138
- frame_num2 = first_frame_key2.split('_')[1]
139
 
140
- # For catmull-rom, we also need one frame before and after
141
- prev_frame_key1 = frame_keys1[-2] if len(frame_keys1) > 1 else frame_keys1[-1]
142
- next_frame_key2 = frame_keys2[1] if len(frame_keys2) > 1 else frame_keys2[0]
143
 
144
  # Extract all components
145
  components = ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']
@@ -183,10 +177,10 @@ def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-ro
183
  t_eased = ease_in_out_sine(t)
184
  interpolated = data1 * (1 - t_eased) + data2 * t_eased
185
  else:
186
- # For keypoints, use spline interpolation with validation
187
  # Get control points
188
- prev_key = f"frame_{prev_frame_key1.split('_')[1]}_{component}"
189
- next_key = f"frame_{next_frame_key2.split('_')[1]}_{component}"
190
 
191
  p0 = npz1_data.get(prev_key, data1)
192
  p1 = data1
@@ -197,30 +191,15 @@ def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-ro
197
  interpolated = np.zeros_like(data1)
198
  for person_idx in range(data1.shape[0]):
199
  for joint_idx in range(data1.shape[1]):
200
- # Check if both keypoints are valid (not -1 or 0)
201
- kp1 = p1[person_idx, joint_idx]
202
- kp2 = p2[person_idx, joint_idx]
203
-
204
- # Skip interpolation for invalid keypoints
205
- if np.any(kp1 <= 0) or np.any(kp2 <= 0):
206
- # Use the valid keypoint or zero
207
- if np.any(kp1 > 0):
208
- interpolated[person_idx, joint_idx] = kp1
209
- elif np.any(kp2 > 0):
210
- interpolated[person_idx, joint_idx] = kp2
211
- else:
212
- interpolated[person_idx, joint_idx] = 0
213
- else:
214
- # Only interpolate valid keypoints
215
- points = catmull_rom_spline(
216
- p0[person_idx, joint_idx],
217
- p1[person_idx, joint_idx],
218
- p2[person_idx, joint_idx],
219
- p3[person_idx, joint_idx],
220
- num_points=num_frames,
221
- tension=0.3 # Lower tension for less overshoot
222
- )
223
- interpolated[person_idx, joint_idx] = points[i]
224
  else:
225
  # Single dimension data
226
  t_eased = ease_in_out_sine(t)
 
64
  """
65
  points = []
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  for i in range(num_points):
68
  t = i / (num_points - 1)
69
  t2 = t * t
70
  t3 = t2 * t
71
 
72
+ # Catmull-Rom basis functions
73
  v0 = -tension * t + 2 * tension * t2 - tension * t3
74
  v1 = 1 + (tension - 3) * t2 + (2 - tension) * t3
75
  v2 = tension * t + (3 - 2 * tension) * t2 + (tension - 2) * t3
76
  v3 = -tension * t2 + tension * t3
77
 
78
+ point = v0 * p0 + v1 * p1 + v2 * p2 + v3 * p3
 
 
 
 
 
 
 
 
79
  points.append(point)
80
 
81
  return np.array(points)
82
 
83
 
84
+ def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom', frame1_num=None, frame2_num=None):
85
  """
86
  Interpolate between two pose NPZ data structures
87
 
 
90
  npz2_data: Dictionary containing pose data from second NPZ
91
  num_frames: Number of transition frames to generate
92
  method: Interpolation method ('linear', 'cubic', 'catmull-rom')
93
+ frame1_num: Specific frame number to use from npz1 (default: last frame)
94
+ frame2_num: Specific frame number to use from npz2 (default: first frame)
95
 
96
  Returns:
97
  List of interpolated pose data dictionaries
98
  """
99
  interpolated_frames = []
100
 
101
+ # Extract keypoints from the specified frames
102
  # Assume format: frame_XXXXXXXX_bodies, frame_XXXXXXXX_hands, etc.
103
 
104
+ # Get the frame from npz1
105
+ if frame1_num is None:
106
+ frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])
107
+ if not frame_keys1:
108
+ return []
109
+ last_frame_key1 = frame_keys1[-1]
110
+ frame_num1 = last_frame_key1.split('_')[1]
111
+ else:
112
+ frame_num1 = f"{frame1_num:08d}"
113
+
114
+ # Get the frame from npz2
115
+ if frame2_num is None:
116
+ frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])
117
+ if not frame_keys2:
118
+ return []
119
+ first_frame_key2 = frame_keys2[0]
120
+ frame_num2 = first_frame_key2.split('_')[1]
121
+ else:
122
+ frame_num2 = f"{frame2_num:08d}"
123
+
124
+ # For catmull-rom, we need frames before and after for control points
125
+ # Get frame keys if not already obtained
126
+ if frame1_num is not None or frame2_num is not None:
127
+ frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])
128
+ frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])
129
 
130
+ # Find previous frame for npz1
131
+ prev_frame_num1 = max(1, int(frame_num1) - 1)
132
+ prev_frame_key1 = f"frame_{prev_frame_num1:08d}"
 
 
 
133
 
134
+ # Find next frame for npz2
135
+ next_frame_num2 = min(int(frame_num2) + 1, len(frame_keys2))
136
+ next_frame_key2 = f"frame_{next_frame_num2:08d}"
137
 
138
  # Extract all components
139
  components = ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']
 
177
  t_eased = ease_in_out_sine(t)
178
  interpolated = data1 * (1 - t_eased) + data2 * t_eased
179
  else:
180
+ # For keypoints, use spline interpolation
181
  # Get control points
182
+ prev_key = f"{prev_frame_key1}_{component}"
183
+ next_key = f"{next_frame_key2}_{component}"
184
 
185
  p0 = npz1_data.get(prev_key, data1)
186
  p1 = data1
 
191
  interpolated = np.zeros_like(data1)
192
  for person_idx in range(data1.shape[0]):
193
  for joint_idx in range(data1.shape[1]):
194
+ # Interpolate each joint
195
+ points = catmull_rom_spline(
196
+ p0[person_idx, joint_idx],
197
+ p1[person_idx, joint_idx],
198
+ p2[person_idx, joint_idx],
199
+ p3[person_idx, joint_idx],
200
+ num_points=num_frames
201
+ )
202
+ interpolated[person_idx, joint_idx] = points[i]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  else:
204
  # Single dimension data
205
  t_eased = ease_in_out_sine(t)