FangSen9000 commited on
Commit ·
0ebe26e
1
Parent(s): 9a3b4f8
Discard the npz frames that cause black screen during generation
Browse filesFiles changed (4)
7 unmodified lines89101112137 unmodified lines# For Users1. cd StableSigner2. conda env create -f env/environment02_controlnext.yml3. run `conda activate controlnext`7 unmodified lines891011121314157 unmodified lines# For Users**Note:** It seems that the first time using pose2vid will result in poor quality and speed, and some kind of warm-up is necessary.1. cd StableSigner2. conda env create -f env/environment02_controlnext.yml3. run `conda activate controlnext`
89 unmodified lines90919293949553 unmodified lines1491501511521531541551561571581591601611621631641651661671681694 unmodified lines17417517617717817918018118218314 unmodified lines19819920020120220320420520620720889 unmodified linesexcept Exception as e:print(f" ⚠️ Failed to load NPZ: {e}")return Nonedef get_frame_data(self, npz_data, frame_num):"""Extract frame data from NPZ"""53 unmodified linesprint(f"🎯 '{gloss}' -> Found {len(matched_videos)} videos")# Use first available videofor video_id in matched_videos:npz_data = self.load_video_npz(video_id)if npz_data is not None:total_frames = self.get_total_frames(npz_data)print(f" 📹 {video_id}: {total_frames} frames")# Store NPZ data for potential interpolationall_npz_data.append(npz_data)# Extract all frames for this videogloss_frames = []for frame_num in range(1, total_frames + 1):frame_data = self.get_frame_data(npz_data, frame_num)if frame_data:pose_frame = self.create_pose_frame(frame_data, width, height)if pose_frame is not None:gloss_frames.append(pose_frame)4 unmodified lines'gloss': gloss,'video_id': video_id,'frame_count': len(gloss_frames),'npz_data': npz_data})print(f" ✅ Generated {len(gloss_frames)} pose frames")break # Use only first valid video per glossif not all_pose_frames:print("❌ No frames generated")14 unmodified linesnpz1 = video_info[i]['npz_data']npz2 = video_info[i + 1]['npz_data']# Interpolate between the two NPZ filesinterpolated_npz_frames = interpolate_pose_npz(npz1, npz2,num_frames=npz_interpolation_frames,method='catmull-rom')# Convert interpolated NPZ frames to visual frames89 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319453 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862874 unmodified lines29229329429529629729829930030130230330430530630714 unmodified lines32232332432532632732832933033133233333433533633733889 unmodified linesexcept Exception as e:print(f" ⚠️ Failed to load NPZ: {e}")return Nonedef check_frame_quality(self, frame_data):"""Check if a frame has valid pose data based on confidence scores"""if not frame_data:return False# Check hand scores (most critical for sign language)if 'hands_scores' in frame_data:hands_scores = frame_data['hands_scores']if hands_scores is not None and len(hands_scores) > 0:# Check if more than 80% of hand points have negative confidencevalid_scores = hands_scores[hands_scores >= 0]if len(valid_scores) < len(hands_scores) * 0.2:return False# Check body scoresif 'body_scores' in frame_data:body_scores = frame_data['body_scores']if body_scores is not None and len(body_scores) > 0:valid_scores = body_scores[body_scores >= 0]if len(valid_scores) < len(body_scores) * 0.2:return Falsereturn Truedef check_video_quality(self, npz_data, check_frames=5, extended_check_frames=30):"""Check video quality by examining start and end frames"""total_frames = self.get_total_frames(npz_data)if total_frames == 0:return False, "No frames found"# Check first and last N framesproblematic_start = 0problematic_end = 0# Check start framesfor i in range(1, min(check_frames + 1, total_frames + 1)):frame_data = self.get_frame_data(npz_data, i)if not self.check_frame_quality(frame_data):problematic_start += 1# Check end framesfor i in range(max(1, total_frames - check_frames + 1), total_frames + 1):frame_data = self.get_frame_data(npz_data, i)if not self.check_frame_quality(frame_data):problematic_end += 1# If more than 3 frames are problematic, do extended checkif problematic_start >= 3 or problematic_end >= 3:print(f" ⚠️ Initial check found {problematic_start} bad start frames, {problematic_end} bad end frames")# Extended checkproblematic_start_extended = 0problematic_end_extended = 0for i in range(1, min(extended_check_frames + 1, total_frames + 1)):frame_data = self.get_frame_data(npz_data, i)if not self.check_frame_quality(frame_data):problematic_start_extended += 1for i in range(max(1, total_frames - extended_check_frames + 1), total_frames + 1):frame_data = self.get_frame_data(npz_data, i)if not self.check_frame_quality(frame_data):problematic_end_extended += 1# If too many bad frames, reject videoif problematic_start_extended > extended_check_frames * 0.5 or \problematic_end_extended > extended_check_frames * 0.5:return False, f"Too many bad frames: {problematic_start_extended} start, {problematic_end_extended} end"return True, f"Quality check passed (bad frames: {problematic_start} start, {problematic_end} end)"def get_valid_frame_range(self, npz_data, margin=5):"""Get the range of valid frames, excluding bad frames at start/end"""total_frames = self.get_total_frames(npz_data)if total_frames == 0:return 1, 0# Find first valid framestart_frame = 1for i in range(1, min(margin + 1, total_frames + 1)):frame_data = self.get_frame_data(npz_data, i)if self.check_frame_quality(frame_data):start_frame = ibreakelse:start_frame = i + 1# Find last valid frameend_frame = total_framesfor i in range(total_frames, max(0, total_frames - margin), -1):frame_data = self.get_frame_data(npz_data, i)if self.check_frame_quality(frame_data):end_frame = ibreakelse:end_frame = i - 1return start_frame, end_framedef get_frame_data(self, npz_data, frame_num):"""Extract frame data from NPZ"""53 unmodified linesprint(f"🎯 '{gloss}' -> Found {len(matched_videos)} videos")# Try each video until we find one with good qualityvideo_found = Falsefor idx, video_id in enumerate(matched_videos):npz_data = self.load_video_npz(video_id)if npz_data is not None:total_frames = self.get_total_frames(npz_data)print(f" 📹 {video_id}: {total_frames} frames")# Check video qualityis_good_quality, quality_msg = self.check_video_quality(npz_data)if not is_good_quality:print(f" ❌ Video quality check failed: {quality_msg}")if idx < len(matched_videos) - 1:print(f" 🔄 Trying next video for '{gloss}'...")continue# Get valid frame rangestart_frame, end_frame = self.get_valid_frame_range(npz_data)if start_frame > end_frame:print(f" ❌ No valid frames found in video")continueprint(f" ✅ {quality_msg}")print(f" 📊 Using frames {start_frame} to {end_frame} (out of {total_frames})")# Store NPZ data for potential interpolationall_npz_data.append(npz_data)# Extract frames within valid rangegloss_frames = []for frame_num in range(start_frame, end_frame + 1):frame_data = self.get_frame_data(npz_data, frame_num)if frame_data and self.check_frame_quality(frame_data):pose_frame = self.create_pose_frame(frame_data, width, height)if pose_frame is not None:gloss_frames.append(pose_frame)4 unmodified lines'gloss': gloss,'video_id': video_id,'frame_count': len(gloss_frames),'npz_data': npz_data,'start_frame': start_frame,'end_frame': end_frame})print(f" ✅ Generated {len(gloss_frames)} pose frames")video_found = Truebreak # Use only first valid video per glossif not video_found:print(f" ❌ No suitable video found for '{gloss}' after checking {len(matched_videos)} candidates")if not all_pose_frames:print("❌ No frames generated")14 unmodified linesnpz1 = video_info[i]['npz_data']npz2 = video_info[i + 1]['npz_data']# Get valid frame ranges for interpolationend_frame1 = video_info[i].get('end_frame', self.get_total_frames(npz1))start_frame2 = video_info[i + 1].get('start_frame', 1)# Interpolate between the two NPZ filesinterpolated_npz_frames = interpolate_pose_npz(npz1, npz2,num_frames=npz_interpolation_frames,method='catmull-rom',frame1_num=end_frame1,frame2_num=start_frame2)# Convert interpolated NPZ frames to visual frames
63 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101112 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414537 unmodified lines1831841851861871881891901911924 unmodified lines19719819920020120220320420520620720820921021121221321421521621721821922022122222322422522663 unmodified lines"""points = []# Check for invalid points (coordinates that are 0, -1, or out of reasonable bounds)def is_valid_point(p):if isinstance(p, np.ndarray):# Check if any coordinate is -1, 0, or unreasonably largereturn np.all(p > 0) and np.all(p < 2000) # Assuming 2000 is max reasonable coordinatereturn False# If endpoints are invalid, fall back to linear interpolationif not is_valid_point(p1) or not is_valid_point(p2):# Simple linear interpolation for invalid pointsfor i in range(num_points):t = i / (num_points - 1)point = p1 * (1 - t) + p2 * tpoints.append(point)return np.array(points)for i in range(num_points):t = i / (num_points - 1)t2 = t * tt3 = t2 * t# Catmull-Rom basis functions with clamping to prevent overshootv0 = -tension * t + 2 * tension * t2 - tension * t3v1 = 1 + (tension - 3) * t2 + (2 - tension) * t3v2 = tension * t + (3 - 2 * tension) * t2 + (tension - 2) * t3v3 = -tension * t2 + tension * t3# Use valid control points or fall back to endpointsp0_safe = p0 if is_valid_point(p0) else p1p3_safe = p3 if is_valid_point(p3) else p2point = v0 * p0_safe + v1 * p1 + v2 * p2 + v3 * p3_safe# Clamp to reasonable bounds to prevent extreme valuespoint = np.clip(point, 0, 2000)points.append(point)return np.array(points)def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom'):"""Interpolate between two pose NPZ data structures2 unmodified linesnpz2_data: Dictionary containing pose data from second NPZnum_frames: Number of transition frames to generatemethod: Interpolation method ('linear', 'cubic', 'catmull-rom')Returns:List of interpolated pose data dictionaries"""interpolated_frames = []# Extract keypoints from the last frame of first video and first frame of second# Assume format: frame_XXXXXXXX_bodies, frame_XXXXXXXX_hands, etc.# Get the last frame from npz1frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])if not frame_keys1:return []last_frame_key1 = frame_keys1[-1]frame_num1 = last_frame_key1.split('_')[1]# Get the first frame from npz2frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])if not frame_keys2:return []first_frame_key2 = frame_keys2[0]frame_num2 = first_frame_key2.split('_')[1]# For catmull-rom, we also need one frame before and afterprev_frame_key1 = frame_keys1[-2] if len(frame_keys1) > 1 else frame_keys1[-1]next_frame_key2 = frame_keys2[1] if len(frame_keys2) > 1 else frame_keys2[0]# Extract all componentscomponents = ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']37 unmodified linest_eased = ease_in_out_sine(t)interpolated = data1 * (1 - t_eased) + data2 * t_easedelse:# For keypoints, use spline interpolation with validation# Get control pointsprev_key = f"frame_{prev_frame_key1.split('_')[1]}_{component}"next_key = f"frame_{next_frame_key2.split('_')[1]}_{component}"p0 = npz1_data.get(prev_key, data1)p1 = data14 unmodified linesinterpolated = np.zeros_like(data1)for person_idx in range(data1.shape[0]):for joint_idx in range(data1.shape[1]):# Check if both keypoints are valid (not -1 or 0)kp1 = p1[person_idx, joint_idx]kp2 = p2[person_idx, joint_idx]# Skip interpolation for invalid keypointsif np.any(kp1 <= 0) or np.any(kp2 <= 0):# Use the valid keypoint or zeroif np.any(kp1 > 0):interpolated[person_idx, joint_idx] = kp1elif np.any(kp2 > 0):interpolated[person_idx, joint_idx] = kp2else:interpolated[person_idx, joint_idx] = 0else:# Only interpolate valid keypointspoints = catmull_rom_spline(p0[person_idx, joint_idx],p1[person_idx, joint_idx],p2[person_idx, joint_idx],p3[person_idx, joint_idx],num_points=num_frames,tension=0.3 # Lower tension for less overshoot)interpolated[person_idx, joint_idx] = points[i]else:# Single dimension datat_eased = ease_in_out_sine(t)63 unmodified lines6465666768697071727374757677787980818283848586872 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813937 unmodified lines1771781791801811821831841851864 unmodified lines19119219319419519619719819920020120220320420563 unmodified lines"""points = []for i in range(num_points):t = i / (num_points - 1)t2 = t * tt3 = t2 * t# Catmull-Rom basis functionsv0 = -tension * t + 2 * tension * t2 - tension * t3v1 = 1 + (tension - 3) * t2 + (2 - tension) * t3v2 = tension * t + (3 - 2 * tension) * t2 + (tension - 2) * t3v3 = -tension * t2 + tension * t3point = v0 * p0 + v1 * p1 + v2 * p2 + v3 * p3points.append(point)return np.array(points)def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom', frame1_num=None, frame2_num=None):"""Interpolate between two pose NPZ data structures2 unmodified linesnpz2_data: Dictionary containing pose data from second NPZnum_frames: Number of transition frames to generatemethod: Interpolation method ('linear', 'cubic', 'catmull-rom')frame1_num: Specific frame number to use from npz1 (default: last frame)frame2_num: Specific frame number to use from npz2 (default: first frame)Returns:List of interpolated pose data dictionaries"""interpolated_frames = []# Extract keypoints from the specified frames# Assume format: frame_XXXXXXXX_bodies, frame_XXXXXXXX_hands, etc.# Get the frame from npz1if frame1_num is None:frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])if not frame_keys1:return []last_frame_key1 = frame_keys1[-1]frame_num1 = last_frame_key1.split('_')[1]else:frame_num1 = f"{frame1_num:08d}"# Get the frame from npz2if frame2_num is None:frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])if not frame_keys2:return []first_frame_key2 = frame_keys2[0]frame_num2 = first_frame_key2.split('_')[1]else:frame_num2 = f"{frame2_num:08d}"# For catmull-rom, we need frames before and after for control points# Get frame keys if not already obtainedif frame1_num is not None or frame2_num is not None:frame_keys1 = sorted([k for k in npz1_data.keys() if k.endswith('_bodies')])frame_keys2 = sorted([k for k in npz2_data.keys() if k.endswith('_bodies')])# Find previous frame for npz1prev_frame_num1 = max(1, int(frame_num1) - 1)prev_frame_key1 = f"frame_{prev_frame_num1:08d}"# Find next frame for npz2next_frame_num2 = min(int(frame_num2) + 1, len(frame_keys2))next_frame_key2 = f"frame_{next_frame_num2:08d}"# Extract all componentscomponents = ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores']37 unmodified linest_eased = ease_in_out_sine(t)interpolated = data1 * (1 - t_eased) + data2 * t_easedelse:# For keypoints, use spline interpolation# Get control pointsprev_key = f"{prev_frame_key1}_{component}"next_key = f"{next_frame_key2}_{component}"p0 = npz1_data.get(prev_key, data1)p1 = data14 unmodified linesinterpolated = np.zeros_like(data1)for person_idx in range(data1.shape[0]):for joint_idx in range(data1.shape[1]):# Interpolate each jointpoints = catmull_rom_spline(p0[person_idx, joint_idx],p1[person_idx, joint_idx],p2[person_idx, joint_idx],p3[person_idx, joint_idx],num_points=num_frames)interpolated[person_idx, joint_idx] = points[i]else:# Single dimension datat_eased = ease_in_out_sine(t)
README.md+2
text2pose.py+137-7
utils/__pycache__/npz_interpolation.cpython-310.pyc
utils/npz_interpolation.py+49-70