magicmotion / gain_color.py
Qnancy's picture
Upload folder using huggingface_hub
ad44ad4 verified
import cv2
import numpy as np
video_path = "/mnt/prev_nas/qhy/MagicMotion/assets/mask_trajectory/mammoth_rhino.mp4"
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
raise RuntimeError("无法读取第一帧")
# 你给的两个参考颜色(BGR)
pink_bgr = np.array([77, 80, 119], dtype=np.float32) # #77504D
red_bgr = np.array([33, 37, 117], dtype=np.float32) # #752521
# 阈值(可调):单位是“颜色距离”
T_pink = 30.0
T_red = 30.0
# 展平计算距离
img = frame.astype(np.float32)
pixels = img.reshape(-1, 3)
# 距参考颜色的 L2 距离
dist_to_pink = np.linalg.norm(pixels - pink_bgr, axis=1)
dist_to_red = np.linalg.norm(pixels - red_bgr, axis=1)
pink_mask = (dist_to_pink < T_pink).reshape(frame.shape[:2])
red_mask = (dist_to_red < T_red ).reshape(frame.shape[:2])
# 如果有交叉:距离谁近归谁
both = pink_mask & red_mask
if both.any():
closer_to_pink = dist_to_pink[both.reshape(-1)] <= dist_to_red[both.reshape(-1)]
# 把 bool 拉回 2D 时处理稍微麻烦一点,简单写法如下:
pink_idx = np.where(both)
# 使用 zip 遍历坐标
i = 0
for y, x in zip(*pink_idx):
if closer_to_pink[i]:
red_mask[y, x] = False
else:
pink_mask[y, x] = False
i += 1
# 可视化看看
vis = np.zeros_like(frame)
vis[pink_mask] = (255, 0, 255)
vis[red_mask] = (0, 0, 255)
cv2.imwrite("first_frame_bgr_distance.png", vis)
print("已保存: first_frame_bgr_distance.png")