Download utils/npz_interpolation.py from SignerX/StableSigner: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/utils/npz_interpolation.py
- Command line
-
hf download hf://datasets/SignerX/StableSigner/utils/npz_interpolation.py
-
curl -L -o npz_interpolation.py https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/utils/npz_interpolation.py
19.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| NPZ-level interpolation for smooth pose transitions | |
| Implements various interpolation methods for creating natural transitions between poses | |
| """ | |
| import numpy as np | |
| from scipy import interpolate | |
| from scipy.spatial.transform import Slerp, Rotation | |
| import cv2 | |
| def ease_in_out_cubic(t): | |
| """Cubic easing function for smooth acceleration and deceleration""" | |
| if t < 0.5: | |
| return 4 * t * t * t | |
| else: | |
| p = 2 * t - 2 | |
| return 1 + p * p * p / 2 | |
| def ease_in_out_sine(t): | |
| """Sine easing function for very smooth transitions""" | |
| return -(np.cos(np.pi * t) - 1) / 2 | |
| def interpolate_keypoints(kp1, kp2, num_frames, easing_func=ease_in_out_cubic): | |
| """ | |
| Interpolate between two sets of keypoints using easing functions | |
| Args: | |
| kp1: Starting keypoints (N, 2) or (N, 3) | |
| kp2: Ending keypoints (N, 2) or (N, 3) | |
| num_frames: Number of interpolated frames | |
| easing_func: Easing function to use | |
| Returns: | |
| List of interpolated keypoints | |
| """ | |
| interpolated = [] | |
| for i in range(num_frames): | |
| t = i / (num_frames - 1) if num_frames > 1 else 0 | |
| t_eased = easing_func(t) | |
| # Linear interpolation with easing | |
| interp_kp = kp1 * (1 - t_eased) + kp2 * t_eased | |
| interpolated.append(interp_kp) | |
| return interpolated | |
| def catmull_rom_spline(p0, p1, p2, p3, num_points, tension=0.5): | |
| """ | |
| Catmull-Rom spline interpolation for smooth curves through control points | |
| Args: | |
| p0, p1, p2, p3: Control points (start from p1 to p2, p0 and p3 for curvature) | |
| num_points: Number of points to generate | |
| tension: Tension parameter (0.5 is standard Catmull-Rom) | |
| Returns: | |
| Array of interpolated points | |
| """ | |
| points = [] | |
| for i in range(num_points): | |
| t = i / (num_points - 1) | |
| t2 = t * t | |
| t3 = t2 * t | |
| # Catmull-Rom basis functions | |
| v0 = -tension * t + 2 * tension * t2 - tension * t3 | |
| v1 = 1 + (tension - 3) * t2 + (2 - tension) * t3 | |
| v2 = tension * t + (3 - 2 * tension) * t2 + (tension - 2) * t3 | |
| v3 = -tension * t2 + tension * t3 | |
| point = v0 * p0 + v1 * p1 + v2 * p2 + v3 * p3 | |
| points.append(point) | |
| return np.array(points) | |
| BODY_TREE = [ | |
| (1, 2), (2, 3), (3, 4), | |
| (1, 5), (5, 6), (6, 7), | |
| (1, 8), (8, 9), (9, 10), | |
| (1, 11), (11, 12), (12, 13), | |
| (1, 0), (0, 14), (14, 16), (0, 15), (15, 17), | |
| ] | |
| def _valid_xy(points): | |
| return points is not None and points.shape[-1] >= 2 | |
| def _point_valid(point): | |
| return point is not None and len(point) >= 2 and point[0] > 0 and point[1] > 0 | |
| def _canonicalize_body(body, body_a, body_b, blend=0.9): | |
| if body is None or body.shape[0] < 18: | |
| return body | |
| rec = body.copy() | |
| rec[1, :2] = body[1, :2] | |
| for parent, child in BODY_TREE: | |
| if parent >= len(body) or child >= len(body): | |
| continue | |
| if not (_point_valid(body[parent]) and _point_valid(body[child])): | |
| continue | |
| lengths = [] | |
| for ref in (body_a, body_b): | |
| if ref is not None and parent < len(ref) and child < len(ref): | |
| if _point_valid(ref[parent]) and _point_valid(ref[child]): | |
| length = np.linalg.norm(ref[child, :2] - ref[parent, :2]) | |
| if 0.002 < length < 0.8: | |
| lengths.append(length) | |
| if not lengths: | |
| continue | |
| target_len = float(np.median(lengths)) | |
| direction = body[child, :2] - body[parent, :2] | |
| current_len = np.linalg.norm(direction) | |
| if current_len <= 1e-6: | |
| continue | |
| rec[child, :2] = rec[parent, :2] + direction / current_len * target_len | |
| out = body.copy() | |
| out[:, :2] = body[:, :2] * (1.0 - blend) + rec[:, :2] * blend | |
| out[:, 0] = np.clip(out[:, 0], 0.0, 1.0) | |
| out[:, 1] = np.clip(out[:, 1], 0.0, 1.0) | |
| return out | |
| def _attach_hands_to_body(hands_a, hands_b, body_a, body_b, body_t, alpha): | |
| if hands_a is None and hands_b is None: | |
| return None | |
| if hands_a is None: | |
| hands_a = hands_b | |
| body_a = body_b | |
| if hands_b is None: | |
| hands_b = hands_a | |
| body_b = body_a | |
| if hands_a is None or hands_b is None or hands_a.shape != hands_b.shape: | |
| return hands_a if alpha < 0.5 else hands_b | |
| out_a = np.array(hands_a, copy=True) | |
| out_b = np.array(hands_b, copy=True) | |
| wrist_ids = [4, 7] | |
| def attach(src_hands, src_body): | |
| attached = np.array(src_hands, copy=True) | |
| if src_body is None or body_t is None or len(src_body) <= 7 or len(body_t) <= 7: | |
| return attached | |
| if src_hands.ndim == 3: | |
| for hand_idx in range(src_hands.shape[0]): | |
| root = src_hands[hand_idx, 0] | |
| if not _point_valid(root): | |
| continue | |
| choices = [] | |
| for wid in wrist_ids: | |
| if _point_valid(src_body[wid]) and _point_valid(body_t[wid]): | |
| choices.append((np.linalg.norm(root[:2] - src_body[wid, :2]), wid)) | |
| if not choices: | |
| continue | |
| wid = min(choices, key=lambda item: item[0])[1] | |
| delta = body_t[wid, :2] - src_body[wid, :2] | |
| valid = (attached[hand_idx, :, 0] > 0) & (attached[hand_idx, :, 1] > 0) | |
| attached[hand_idx, valid, :2] += delta | |
| elif src_hands.ndim == 2 and len(src_hands) > 0: | |
| root = src_hands[0] | |
| choices = [] | |
| for wid in wrist_ids: | |
| if _point_valid(root) and _point_valid(src_body[wid]) and _point_valid(body_t[wid]): | |
| choices.append((np.linalg.norm(root[:2] - src_body[wid, :2]), wid)) | |
| if choices: | |
| wid = min(choices, key=lambda item: item[0])[1] | |
| delta = body_t[wid, :2] - src_body[wid, :2] | |
| valid = (attached[:, 0] > 0) & (attached[:, 1] > 0) | |
| attached[valid, :2] += delta | |
| attached[..., 0] = np.clip(attached[..., 0], 0.0, 1.0) | |
| attached[..., 1] = np.clip(attached[..., 1], 0.0, 1.0) | |
| return attached | |
| a = attach(out_a, body_a) | |
| b = attach(out_b, body_b) | |
| out = a * (1.0 - alpha) + b * alpha | |
| return out | |
| def _attach_faces_to_body(face_a, face_b, body_a, body_b, body_t, alpha): | |
| if face_a is None and face_b is None: | |
| return None | |
| if face_a is None: | |
| face_a = face_b | |
| body_a = body_b | |
| if face_b is None: | |
| face_b = face_a | |
| body_b = body_a | |
| if face_a is None or face_b is None or face_a.shape != face_b.shape: | |
| return face_a if alpha < 0.5 else face_b | |
| def attach(src_face, src_body): | |
| attached = np.array(src_face, copy=True) | |
| if src_body is None or body_t is None or len(src_body) <= 1 or len(body_t) <= 1: | |
| return attached | |
| if not (_point_valid(src_body[1]) and _point_valid(body_t[1])): | |
| return attached | |
| delta = body_t[1, :2] - src_body[1, :2] | |
| valid = (attached[..., 0] > 0) & (attached[..., 1] > 0) | |
| attached[..., :2][valid] += delta | |
| attached[..., 0] = np.clip(attached[..., 0], 0.0, 1.0) | |
| attached[..., 1] = np.clip(attached[..., 1], 0.0, 1.0) | |
| return attached | |
| a = attach(face_a, body_a) | |
| b = attach(face_b, body_b) | |
| return a * (1.0 - alpha) + b * alpha | |
| 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 structures | |
| Args: | |
| npz1_data: Dictionary containing pose data from first NPZ | |
| npz2_data: Dictionary containing pose data from second NPZ | |
| num_frames: Number of transition frames to generate | |
| method: 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 npz1 | |
| if 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 npz2 | |
| if 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 obtained | |
| if 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 npz1 | |
| prev_frame_num1 = max(1, int(frame_num1) - 1) | |
| prev_frame_key1 = f"frame_{prev_frame_num1:08d}" | |
| # Find next frame for npz2 | |
| next_frame_num2 = min(int(frame_num2) + 1, len(frame_keys2)) | |
| next_frame_key2 = f"frame_{next_frame_num2:08d}" | |
| # Extract all components | |
| components = ['bodies', 'body_scores', 'hands', 'hands_scores', 'faces', 'faces_scores'] | |
| conf_threshold = 0.3 | |
| score_component_map = { | |
| 'bodies': 'body_scores', | |
| 'hands': 'hands_scores', | |
| 'faces': 'faces_scores' | |
| } | |
| validity_masks = {} | |
| def compute_valid_mask(component_name): | |
| score_component = score_component_map.get(component_name) | |
| if not score_component: | |
| return None | |
| score_key1 = f"frame_{frame_num1}_{score_component}" | |
| score_key2 = f"frame_{frame_num2}_{score_component}" | |
| if score_key1 not in npz1_data or score_key2 not in npz2_data: | |
| return None | |
| score1 = np.array(npz1_data[score_key1]) | |
| score2 = np.array(npz2_data[score_key2]) | |
| if score1.shape != score2.shape: | |
| return None | |
| return (score1 >= conf_threshold) & (score2 >= conf_threshold) | |
| def apply_mask_to_data(data, mask, invalid_value=0.0, treat_scores=False): | |
| if mask is None: | |
| return data | |
| data = np.array(data, copy=True) | |
| valid_mask = np.array(mask, dtype=bool) | |
| if treat_scores: | |
| try: | |
| valid_mask = np.broadcast_to(valid_mask, data.shape) | |
| except ValueError: | |
| valid_mask = np.squeeze(valid_mask) | |
| valid_mask = np.broadcast_to(valid_mask, data.shape) | |
| data = np.where(valid_mask, data, invalid_value) | |
| return data | |
| # Coordinates: ensure mask matches all dims except the last coordinate axis | |
| target_mask_shape = data.shape[:-1] | |
| try: | |
| valid_mask = np.broadcast_to(valid_mask, target_mask_shape) | |
| except ValueError: | |
| valid_mask = np.squeeze(valid_mask) | |
| valid_mask = np.broadcast_to(valid_mask, target_mask_shape) | |
| valid_mask = np.expand_dims(valid_mask, axis=-1) | |
| data = np.where(valid_mask, data, invalid_value) | |
| return data | |
| for i in range(num_frames): | |
| t = i / (num_frames - 1) if num_frames > 1 else 0 | |
| interpolated_data = {} | |
| for component in components: | |
| key1 = f"frame_{frame_num1}_{component}" | |
| key2 = f"frame_{frame_num2}_{component}" | |
| if key1 in npz1_data and key2 in npz2_data: | |
| data1 = npz1_data[key1] | |
| data2 = npz2_data[key2] | |
| if method == 'body-anchor': | |
| t_eased = ease_in_out_sine(t) | |
| if component == 'bodies': | |
| prev_key = f"{prev_frame_key1}_{component}" | |
| next_key = f"{next_frame_key2}_{component}" | |
| p0 = npz1_data.get(prev_key, data1) | |
| p1 = data1 | |
| p2 = data2 | |
| p3 = npz2_data.get(next_key, data2) | |
| interpolated = catmull_rom_spline(p0, p1, p2, p3, num_frames)[i] | |
| interpolated = _canonicalize_body(interpolated, data1, data2, blend=0.9) | |
| elif component == 'hands': | |
| body1 = npz1_data.get(f"frame_{frame_num1}_bodies") | |
| body2 = npz2_data.get(f"frame_{frame_num2}_bodies") | |
| body_key = f"frame_{i+1:08d}_bodies" | |
| body_t = interpolated_data.get(body_key) | |
| interpolated = _attach_hands_to_body(data1, data2, body1, body2, body_t, t_eased) | |
| elif component == 'faces': | |
| body1 = npz1_data.get(f"frame_{frame_num1}_bodies") | |
| body2 = npz2_data.get(f"frame_{frame_num2}_bodies") | |
| body_key = f"frame_{i+1:08d}_bodies" | |
| body_t = interpolated_data.get(body_key) | |
| interpolated = _attach_faces_to_body(data1, data2, body1, body2, body_t, t_eased) | |
| elif component.endswith('_scores'): | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| else: | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| elif method == 'linear': | |
| # Simple linear interpolation with easing | |
| t_eased = ease_in_out_cubic(t) | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| elif method == 'cubic': | |
| # Use scipy's cubic interpolation | |
| if data1.ndim == 3: # Multiple people | |
| interpolated = np.zeros_like(data1) | |
| for person_idx in range(data1.shape[0]): | |
| for joint_idx in range(data1.shape[1]): | |
| for coord_idx in range(data1.shape[2]): | |
| y = [data1[person_idx, joint_idx, coord_idx], | |
| data2[person_idx, joint_idx, coord_idx]] | |
| f = interpolate.interp1d([0, 1], y, kind='cubic') | |
| interpolated[person_idx, joint_idx, coord_idx] = f(t) | |
| else: | |
| t_eased = ease_in_out_cubic(t) | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| elif method == 'catmull-rom': | |
| # Use Catmull-Rom spline for smoother transitions | |
| if component.endswith('_scores'): | |
| # For scores, use simple easing | |
| t_eased = ease_in_out_sine(t) | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| else: | |
| # For keypoints, use spline interpolation | |
| # Get control points | |
| prev_key = f"{prev_frame_key1}_{component}" | |
| next_key = f"{next_frame_key2}_{component}" | |
| p0 = npz1_data.get(prev_key, data1) | |
| p1 = data1 | |
| p2 = data2 | |
| p3 = npz2_data.get(next_key, data2) | |
| if data1.ndim == 3: # Multiple people | |
| interpolated = np.zeros_like(data1) | |
| for person_idx in range(data1.shape[0]): | |
| for joint_idx in range(data1.shape[1]): | |
| # Interpolate each joint | |
| points = 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 data | |
| t_eased = ease_in_out_sine(t) | |
| interpolated = data1 * (1 - t_eased) + data2 * t_eased | |
| # Apply confidence-aware masking so we don't invent joints with low confidence | |
| if component in score_component_map: | |
| if component not in validity_masks: | |
| validity_masks[component] = compute_valid_mask(component) | |
| interpolated = apply_mask_to_data(interpolated, validity_masks.get(component), invalid_value=0.0) | |
| elif component.endswith('_scores'): | |
| base_component = component.replace('_scores', '') | |
| mask = validity_masks.get(base_component) | |
| interpolated = apply_mask_to_data(interpolated, mask, invalid_value=-1.0, treat_scores=True) | |
| # Create frame key for interpolated frame | |
| frame_key = f"frame_{i+1:08d}_{component}" | |
| interpolated_data[frame_key] = interpolated | |
| interpolated_frames.append(interpolated_data) | |
| return interpolated_frames | |
| def apply_motion_blur(frame, prev_frame, blur_strength=0.3): | |
| """Apply motion blur between frames for smoother visual transitions""" | |
| if prev_frame is None: | |
| return frame | |
| # Weighted average with previous frame | |
| blurred = cv2.addWeighted(prev_frame, blur_strength, frame, 1 - blur_strength, 0) | |
| return blurred | |
| def smooth_trajectory(keypoints_sequence, window_size=5): | |
| """ | |
| Apply trajectory smoothing to a sequence of keypoints | |
| Uses a moving average filter to smooth the motion | |
| Args: | |
| keypoints_sequence: List of keypoint arrays | |
| window_size: Size of the smoothing window | |
| Returns: | |
| Smoothed keypoints sequence | |
| """ | |
| if len(keypoints_sequence) <= window_size: | |
| return keypoints_sequence | |
| smoothed = [] | |
| half_window = window_size // 2 | |
| for i in range(len(keypoints_sequence)): | |
| start_idx = max(0, i - half_window) | |
| end_idx = min(len(keypoints_sequence), i + half_window + 1) | |
| # Average keypoints in the window | |
| window_kps = keypoints_sequence[start_idx:end_idx] | |
| avg_kp = np.mean(window_kps, axis=0) | |
| smoothed.append(avg_kp) | |
| return smoothed | |