| | import cv2 |
| | import numpy as np |
| | import os |
| |
|
| | |
| | input_path = "/mnt/prev_nas/qhy/MagicMotion/assets/mask_trajectory/mammoth_rhino.mp4" |
| | output_path = "/mnt/prev_nas/qhy/MagicMotion/assets/mask_trajectory/mammoth_rhino_frozen_pink_bgr_range.mp4" |
| |
|
| | |
| | pink_bgr = np.array([77, 80, 119], dtype=np.float32) |
| | red_bgr = np.array([33, 37, 117], dtype=np.float32) |
| |
|
| | |
| | T_pink = 30.0 |
| | T_red = 30.0 |
| |
|
| | def get_color_masks_bgr(frame_bgr): |
| | """ |
| | 输入: frame_bgr: uint8, HxWx3 |
| | 输出: pink_mask, red_mask (bool 的 HxW) |
| | 使用 BGR 空间的欧式距离 + 阈值来划分粉色和红色。 |
| | """ |
| | img = frame_bgr.astype(np.float32) |
| | pixels = img.reshape(-1, 3) |
| |
|
| | dist_to_pink = np.linalg.norm(pixels - pink_bgr, axis=1) |
| | dist_to_red = np.linalg.norm(pixels - red_bgr, axis=1) |
| |
|
| | h, w = frame_bgr.shape[:2] |
| | pink_mask = (dist_to_pink < T_pink).reshape(h, w) |
| | red_mask = (dist_to_red < T_red ).reshape(h, w) |
| |
|
| | |
| | both = pink_mask & red_mask |
| | if both.any(): |
| | idx_flat = np.where(both.ravel())[0] |
| | closer_to_pink = dist_to_pink[idx_flat] <= dist_to_red[idx_flat] |
| |
|
| | both_y, both_x = np.where(both) |
| | for i, (y, x) in enumerate(zip(both_y, both_x)): |
| | if closer_to_pink[i]: |
| | red_mask[y, x] = False |
| | else: |
| | pink_mask[y, x] = False |
| |
|
| | return pink_mask, red_mask |
| |
|
| | def main(): |
| | cap = cv2.VideoCapture(input_path) |
| | if not cap.isOpened(): |
| | raise RuntimeError(f"无法打开视频: {input_path}") |
| |
|
| | fps = cap.get(cv2.CAP_PROP_FPS) |
| | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
| | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
| |
|
| | |
| | fourcc = cv2.VideoWriter_fourcc(*"mp4v") |
| | out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) |
| | if not out.isOpened(): |
| | cap.release() |
| | raise RuntimeError("VideoWriter 打开失败") |
| |
|
| | |
| | ret, first_frame = cap.read() |
| | if not ret: |
| | cap.release() |
| | out.release() |
| | raise RuntimeError("无法读取第一帧") |
| |
|
| | pink_mask_first, _ = get_color_masks_bgr(first_frame) |
| |
|
| | frozen_pink = np.zeros_like(first_frame) |
| | frozen_pink[pink_mask_first] = first_frame[pink_mask_first] |
| |
|
| | |
| | cap.set(cv2.CAP_PROP_POS_FRAMES, 0) |
| |
|
| | frame_idx = 0 |
| | while True: |
| | ret, frame = cap.read() |
| | if not ret: |
| | break |
| |
|
| | _, red_mask = get_color_masks_bgr(frame) |
| |
|
| | |
| | red_part = np.zeros_like(frame) |
| | red_part[red_mask] = frame[red_mask] |
| |
|
| | |
| | combined = np.zeros_like(frame) |
| | combined += frozen_pink |
| | combined += red_part |
| |
|
| | out.write(combined) |
| | frame_idx += 1 |
| | if frame_idx % 50 == 0: |
| | print(f"已处理帧数: {frame_idx}") |
| |
|
| | cap.release() |
| | out.release() |
| | print("处理完成,输出文件:", output_path) |
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|