cmvr-visual/inference/llm_services/video_edit/tracking.py

87 lines
3.1 KiB
Python
Raw Permalink Normal View History

"""Conservative geometric tracking and bounded visible-mask composition."""
import math
def iou(a, b):
area = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(
0, min(a[3], b[3]) - max(a[1], b[1])
)
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - area
return area / union if union else 0
class Tracker:
"""Fail closed on ambiguous association or reappearance after an occlusion.
SAM2 tracks masks temporally; this independent detector gate prevents a lost
SAM object from silently claiming a different person. No face identification.
"""
def __init__(self):
self.boxes = {}
self.next_id = 1
def update(self, boxes):
if not self.boxes:
result = {}
for box in boxes:
result[f"person_{self.next_id:04d}"] = tuple(box)
self.next_id += 1
self.boxes = result
return result
candidates = []
for person, old in self.boxes.items():
ranked = []
for j, box in enumerate(boxes):
scale = max(old[2] - old[0], old[3] - old[1], 1)
distance = (
math.hypot(
(old[0] + old[2] - box[0] - box[2]) / 2,
(old[1] + old[3] - box[1] - box[3]) / 2,
)
/ scale
)
ranked.append((iou(old, box) - distance * 0.25, j))
ranked.sort(reverse=True)
if not ranked or ranked[0][0] < -0.15:
raise ValueError(
"Tracking lost a person; ambiguous occlusion requires a new source"
)
if len(ranked) > 1 and ranked[0][0] - ranked[1][0] < 0.12:
raise ValueError(
"Tracking ambiguous: person identities cannot be separated safely"
)
candidates.append((person, ranked[0][1]))
if len({j for _, j in candidates}) != len(candidates):
raise ValueError("Tracking ambiguous: competing identities")
result = {person: tuple(boxes[j]) for person, j in candidates}
used = {j for _, j in candidates}
for j, box in enumerate(boxes):
if j not in used:
result[f"person_{self.next_id:04d}"] = tuple(box)
self.next_id += 1
self.boxes = result
return result
def composite(source, generated, visible_mask, protected_mask, feather=4):
import numpy as np
from PIL import Image, ImageFilter
allowed = np.asarray(visible_mask, dtype=bool) & ~np.asarray(
protected_mask, dtype=bool
)
alpha = allowed.astype("float32")
if feather:
blur = Image.fromarray(allowed.astype("uint8") * 255).filter(
ImageFilter.GaussianBlur(feather)
)
alpha *= np.asarray(blur, dtype="float32") / 255
# 羽化只向内,原mask之外和未选人物逐像素保持源画面。
return np.where(
allowed[..., None],
np.rint(source * (1 - alpha[..., None]) + generated * alpha[..., None]),
source,
).astype("uint8")