Add adaptive precise overlay replacement
Browse files- src/videoclean/__pycache__/cli.cpython-314.pyc +0 -0
- src/videoclean/__pycache__/engine.cpython-314.pyc +0 -0
- src/videoclean/__pycache__/reconstruct.cpython-314.pyc +0 -0
- src/videoclean/__pycache__/refine.cpython-314.pyc +0 -0
- src/videoclean/cli.py +3 -0
- src/videoclean/engine.py +7 -4
- src/videoclean/inpainters/__init__.py +3 -1
- src/videoclean/inpainters/__pycache__/__init__.cpython-314.pyc +0 -0
- src/videoclean/inpainters/__pycache__/adaptive.cpython-314.pyc +0 -0
- src/videoclean/inpainters/adaptive.py +118 -0
- src/videoclean/reconstruct.py +44 -0
- src/videoclean/refine.py +45 -0
src/videoclean/__pycache__/cli.cpython-314.pyc
CHANGED
|
Binary files a/src/videoclean/__pycache__/cli.cpython-314.pyc and b/src/videoclean/__pycache__/cli.cpython-314.pyc differ
|
|
|
src/videoclean/__pycache__/engine.cpython-314.pyc
CHANGED
|
Binary files a/src/videoclean/__pycache__/engine.cpython-314.pyc and b/src/videoclean/__pycache__/engine.cpython-314.pyc differ
|
|
|
src/videoclean/__pycache__/reconstruct.cpython-314.pyc
ADDED
|
Binary file (3.93 kB). View file
|
|
|
src/videoclean/__pycache__/refine.cpython-314.pyc
ADDED
|
Binary file (3.93 kB). View file
|
|
|
src/videoclean/cli.py
CHANGED
|
@@ -58,6 +58,7 @@ def _build_parser():
|
|
| 58 |
clean.add_argument("--inpaint-method", choices=["telea", "ns"], default="telea")
|
| 59 |
clean.add_argument("--inpaint-radius", type=float, default=3.0)
|
| 60 |
clean.add_argument("--inpaint-dilate", type=int, default=0)
|
|
|
|
| 61 |
|
| 62 |
# Keep detext as a small compatibility alias for explicit-mask workflows.
|
| 63 |
detext = subparsers.add_parser("detext", help="Alias for clean")
|
|
@@ -69,6 +70,7 @@ def _build_parser():
|
|
| 69 |
detext.add_argument("--inpaint-method", choices=["telea", "ns"], default="telea")
|
| 70 |
detext.add_argument("--inpaint-radius", type=float, default=3.0)
|
| 71 |
detext.add_argument("--inpaint-dilate", type=int, default=0)
|
|
|
|
| 72 |
return parser
|
| 73 |
|
| 74 |
|
|
@@ -97,6 +99,7 @@ def main():
|
|
| 97 |
task=args.command,
|
| 98 |
gap=args.gap,
|
| 99 |
dual=args.dual,
|
|
|
|
| 100 |
model_options={
|
| 101 |
"method": args.inpaint_method,
|
| 102 |
"radius": args.inpaint_radius,
|
|
|
|
| 58 |
clean.add_argument("--inpaint-method", choices=["telea", "ns"], default="telea")
|
| 59 |
clean.add_argument("--inpaint-radius", type=float, default=3.0)
|
| 60 |
clean.add_argument("--inpaint-dilate", type=int, default=0)
|
| 61 |
+
clean.add_argument("--inpaint-model", choices=["opencv", "adaptive"], default="opencv")
|
| 62 |
|
| 63 |
# Keep detext as a small compatibility alias for explicit-mask workflows.
|
| 64 |
detext = subparsers.add_parser("detext", help="Alias for clean")
|
|
|
|
| 70 |
detext.add_argument("--inpaint-method", choices=["telea", "ns"], default="telea")
|
| 71 |
detext.add_argument("--inpaint-radius", type=float, default=3.0)
|
| 72 |
detext.add_argument("--inpaint-dilate", type=int, default=0)
|
| 73 |
+
detext.add_argument("--inpaint-model", choices=["opencv", "adaptive"], default="opencv")
|
| 74 |
return parser
|
| 75 |
|
| 76 |
|
|
|
|
| 99 |
task=args.command,
|
| 100 |
gap=args.gap,
|
| 101 |
dual=args.dual,
|
| 102 |
+
model=getattr(args, "inpaint_model", "opencv"),
|
| 103 |
model_options={
|
| 104 |
"method": args.inpaint_method,
|
| 105 |
"radius": args.inpaint_radius,
|
src/videoclean/engine.py
CHANGED
|
@@ -41,20 +41,23 @@ class WipeEngine:
|
|
| 41 |
self, task: str = "detext", *, verbose: bool = False, gap: int = 10,
|
| 42 |
dual: bool = False, detector: Optional[TextDetector] = None,
|
| 43 |
model: str = "opencv", model_options: Optional[dict] = None,
|
|
|
|
| 44 |
detect_mode: str = "auto", ocr: str = "auto", **legacy,
|
| 45 |
):
|
| 46 |
if task not in _TASK_CLASSES:
|
| 47 |
raise ValueError(f"Unknown task: {task}. Choose from: {list(_TASK_CLASSES)}")
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
self.task = task
|
|
|
|
| 51 |
self._verbose = verbose
|
| 52 |
self._detector = detector
|
| 53 |
self._detect_mode = detect_mode
|
| 54 |
self._ocr = ocr
|
| 55 |
self._model_options = dict(model_options or {})
|
| 56 |
self._task_impl: BaseTask = _TASK_CLASSES[task](gap=gap, dual=dual)
|
| 57 |
-
self._task_impl.inpainter = get_registry().create(
|
| 58 |
self._task_impl.backend = self._task_impl.inpainter
|
| 59 |
self._task_impl.feather_radius = _DEFAULT_FEATHER_RADIUS
|
| 60 |
if task == "clean":
|
|
@@ -163,7 +166,7 @@ class WipeEngine:
|
|
| 163 |
|
| 164 |
def _ensure_model(self):
|
| 165 |
if self._task_impl.inpainter is None:
|
| 166 |
-
self._task_impl.inpainter = get_registry().create(
|
| 167 |
self._task_impl.backend = self._task_impl.inpainter
|
| 168 |
|
| 169 |
def process(self, video: str, mask: str | None = None, output: str = "result/",
|
|
|
|
| 41 |
self, task: str = "detext", *, verbose: bool = False, gap: int = 10,
|
| 42 |
dual: bool = False, detector: Optional[TextDetector] = None,
|
| 43 |
model: str = "opencv", model_options: Optional[dict] = None,
|
| 44 |
+
inpaint_model: Optional[str] = None,
|
| 45 |
detect_mode: str = "auto", ocr: str = "auto", **legacy,
|
| 46 |
):
|
| 47 |
if task not in _TASK_CLASSES:
|
| 48 |
raise ValueError(f"Unknown task: {task}. Choose from: {list(_TASK_CLASSES)}")
|
| 49 |
+
model = inpaint_model or model
|
| 50 |
+
if model not in {"opencv", "adaptive"}:
|
| 51 |
+
raise ValueError("videoclean supports 'opencv' and 'adaptive' inpainters")
|
| 52 |
self.task = task
|
| 53 |
+
self._model = model
|
| 54 |
self._verbose = verbose
|
| 55 |
self._detector = detector
|
| 56 |
self._detect_mode = detect_mode
|
| 57 |
self._ocr = ocr
|
| 58 |
self._model_options = dict(model_options or {})
|
| 59 |
self._task_impl: BaseTask = _TASK_CLASSES[task](gap=gap, dual=dual)
|
| 60 |
+
self._task_impl.inpainter = get_registry().create(model, **self._model_options)
|
| 61 |
self._task_impl.backend = self._task_impl.inpainter
|
| 62 |
self._task_impl.feather_radius = _DEFAULT_FEATHER_RADIUS
|
| 63 |
if task == "clean":
|
|
|
|
| 166 |
|
| 167 |
def _ensure_model(self):
|
| 168 |
if self._task_impl.inpainter is None:
|
| 169 |
+
self._task_impl.inpainter = get_registry().create(self._model, **self._model_options)
|
| 170 |
self._task_impl.backend = self._task_impl.inpainter
|
| 171 |
|
| 172 |
def process(self, video: str, mask: str | None = None, output: str = "result/",
|
src/videoclean/inpainters/__init__.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
| 1 |
"""OpenCV inpainting backend and registry."""
|
| 2 |
from videoclean.inpainters.base import InpaintJob, InpaintOutcome, Inpainter
|
|
|
|
| 3 |
from videoclean.inpainters.opencv import OpenCVInpainter
|
| 4 |
from videoclean.inpainters.registry import InpainterRegistry, get_registry, register_inpainter
|
| 5 |
|
| 6 |
register_inpainter("opencv", OpenCVInpainter)
|
|
|
|
| 7 |
|
| 8 |
-
__all__ = ["Inpainter", "InpaintJob", "InpaintOutcome", "OpenCVInpainter", "InpainterRegistry", "get_registry", "register_inpainter"]
|
|
|
|
| 1 |
"""OpenCV inpainting backend and registry."""
|
| 2 |
from videoclean.inpainters.base import InpaintJob, InpaintOutcome, Inpainter
|
| 3 |
+
from videoclean.inpainters.adaptive import AdaptiveInpainter
|
| 4 |
from videoclean.inpainters.opencv import OpenCVInpainter
|
| 5 |
from videoclean.inpainters.registry import InpainterRegistry, get_registry, register_inpainter
|
| 6 |
|
| 7 |
register_inpainter("opencv", OpenCVInpainter)
|
| 8 |
+
register_inpainter("adaptive", AdaptiveInpainter)
|
| 9 |
|
| 10 |
+
__all__ = ["AdaptiveInpainter", "Inpainter", "InpaintJob", "InpaintOutcome", "OpenCVInpainter", "InpainterRegistry", "get_registry", "register_inpainter"]
|
src/videoclean/inpainters/__pycache__/__init__.cpython-314.pyc
CHANGED
|
Binary files a/src/videoclean/inpainters/__pycache__/__init__.cpython-314.pyc and b/src/videoclean/inpainters/__pycache__/__init__.cpython-314.pyc differ
|
|
|
src/videoclean/inpainters/__pycache__/adaptive.cpython-314.pyc
ADDED
|
Binary file (9.44 kB). View file
|
|
|
src/videoclean/inpainters/adaptive.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative adaptive OpenCV replacement."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import subprocess
|
| 6 |
+
import tempfile
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from videoclean.inpainters.base import InpaintJob, InpaintOutcome
|
| 13 |
+
from videoclean.reconstruct import temporal_consensus
|
| 14 |
+
from videoclean.refine import refine_overlay_mask
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AdaptiveInpainter:
|
| 18 |
+
"""Use tight masks and temporal evidence, then fall back to OpenCV."""
|
| 19 |
+
|
| 20 |
+
name = "adaptive"
|
| 21 |
+
|
| 22 |
+
def __init__(self, method: str = "telea", radius: float = 3.0, dilate: int = 0):
|
| 23 |
+
if method not in {"telea", "ns"}:
|
| 24 |
+
raise ValueError("method must be 'telea' or 'ns'")
|
| 25 |
+
self.method = method
|
| 26 |
+
self.radius = float(radius)
|
| 27 |
+
self.dilate = int(dilate)
|
| 28 |
+
self._method_flag = cv2.INPAINT_TELEA if method == "telea" else cv2.INPAINT_NS
|
| 29 |
+
|
| 30 |
+
def load(self, weight_path=None, device: str = "auto") -> None:
|
| 31 |
+
del weight_path, device
|
| 32 |
+
|
| 33 |
+
def cleanup(self) -> None:
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
def _mask(self, job: InpaintJob, frame_index: int) -> np.ndarray:
|
| 37 |
+
mask = job.frame_mask(frame_index) if job.frame_mask is not None else job.mask
|
| 38 |
+
if mask is None:
|
| 39 |
+
return np.zeros((job.height, job.width), dtype=np.uint8)
|
| 40 |
+
if mask.ndim == 3:
|
| 41 |
+
mask = mask[:, :, 0]
|
| 42 |
+
mask = (np.asarray(mask) > 0).astype(np.uint8) * 255
|
| 43 |
+
if self.dilate:
|
| 44 |
+
size = self.dilate * 2 + 1
|
| 45 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
|
| 46 |
+
mask = cv2.dilate(mask, kernel, iterations=1)
|
| 47 |
+
return mask
|
| 48 |
+
|
| 49 |
+
def _clean_frame(self, frame: np.ndarray, mask: np.ndarray, history: list[np.ndarray]) -> np.ndarray:
|
| 50 |
+
if not np.any(mask):
|
| 51 |
+
return frame
|
| 52 |
+
refined = refine_overlay_mask(frame, mask)
|
| 53 |
+
final_mask = refined.mask.astype(np.uint8) * 255
|
| 54 |
+
if not np.any(final_mask):
|
| 55 |
+
return frame
|
| 56 |
+
result = frame.copy()
|
| 57 |
+
if history:
|
| 58 |
+
estimate, supported = temporal_consensus(history, final_mask, current=frame)
|
| 59 |
+
result[supported > 0] = estimate[supported > 0]
|
| 60 |
+
remaining = (final_mask > 0) & (supported == 0)
|
| 61 |
+
else:
|
| 62 |
+
remaining = final_mask > 0
|
| 63 |
+
if np.any(remaining):
|
| 64 |
+
residual_mask = remaining.astype(np.uint8) * 255
|
| 65 |
+
fallback = cv2.inpaint(frame, residual_mask, self.radius, self._method_flag)
|
| 66 |
+
result[remaining] = fallback[remaining]
|
| 67 |
+
return result
|
| 68 |
+
|
| 69 |
+
def inpaint(self, job: InpaintJob) -> InpaintOutcome:
|
| 70 |
+
if job.reader is None:
|
| 71 |
+
raise ValueError("AdaptiveInpainter requires job.reader")
|
| 72 |
+
stem = os.path.splitext(os.path.basename(job.video_path))[0] if job.video_path else "output"
|
| 73 |
+
output_path = os.path.join(job.output_dir, f"{stem}_{job.output_suffix}.mp4")
|
| 74 |
+
os.makedirs(job.output_dir, exist_ok=True)
|
| 75 |
+
out_h = job.height * 2 if job.dual else job.height
|
| 76 |
+
command = ["ffmpeg", "-y", "-loglevel", "error", "-nostats", "-f", "rawvideo", "-vcodec", "rawvideo", "-s", f"{job.width}x{out_h}", "-pix_fmt", "bgr24", "-r", str(job.fps), "-i", "-"]
|
| 77 |
+
if job.video_path:
|
| 78 |
+
command += ["-i", job.video_path]
|
| 79 |
+
command += ["-map", "0:v"]
|
| 80 |
+
if job.video_path:
|
| 81 |
+
command += ["-map", "1:a?"]
|
| 82 |
+
command += ["-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p"]
|
| 83 |
+
if job.video_path:
|
| 84 |
+
command += ["-c:a", "aac"]
|
| 85 |
+
command += ["-movflags", "+faststart", output_path]
|
| 86 |
+
stderr = tempfile.TemporaryFile()
|
| 87 |
+
pipe = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=stderr)
|
| 88 |
+
history: list[np.ndarray] = []
|
| 89 |
+
done = 0
|
| 90 |
+
started = time.monotonic()
|
| 91 |
+
try:
|
| 92 |
+
while True:
|
| 93 |
+
ok, frame = job.reader.read()
|
| 94 |
+
if not ok:
|
| 95 |
+
break
|
| 96 |
+
mask = self._mask(job, done)
|
| 97 |
+
cleaned = self._clean_frame(frame, mask, history)
|
| 98 |
+
if job.dual:
|
| 99 |
+
cleaned = np.vstack([frame, cleaned])
|
| 100 |
+
pipe.stdin.write(cleaned.tobytes())
|
| 101 |
+
history.append(frame.copy())
|
| 102 |
+
if len(history) > 3:
|
| 103 |
+
history.pop(0)
|
| 104 |
+
done += 1
|
| 105 |
+
if job.progress:
|
| 106 |
+
job.progress(done, job.frame_count)
|
| 107 |
+
pipe.stdin.close()
|
| 108 |
+
pipe.wait()
|
| 109 |
+
finally:
|
| 110 |
+
if pipe.poll() is None:
|
| 111 |
+
pipe.terminate()
|
| 112 |
+
pipe.wait()
|
| 113 |
+
stderr.close()
|
| 114 |
+
if pipe.returncode:
|
| 115 |
+
raise RuntimeError(f"FFmpeg exited with code {pipe.returncode}")
|
| 116 |
+
if isinstance(job.metrics, dict):
|
| 117 |
+
job.metrics["inpainting_s"] = round(time.monotonic() - started, 3)
|
| 118 |
+
return InpaintOutcome(output_path=output_path, backend=self.name)
|
src/videoclean/reconstruct.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded temporal background reconstruction helpers."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def temporal_consensus(
|
| 9 |
+
frames: list[np.ndarray], mask: np.ndarray, *, current: np.ndarray | None = None,
|
| 10 |
+
min_agreement: float = 0.75,
|
| 11 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 12 |
+
"""Return a robust background estimate and pixels supported by consensus.
|
| 13 |
+
|
| 14 |
+
The method is deliberately conservative: if all supplied frames contain
|
| 15 |
+
the same overlay, their disagreement/contrast prevents a fabricated fill.
|
| 16 |
+
"""
|
| 17 |
+
if not frames:
|
| 18 |
+
raise ValueError("at least one frame is required")
|
| 19 |
+
stack = np.stack(frames).astype(np.float32)
|
| 20 |
+
estimate = np.median(stack, axis=0).astype(np.uint8)
|
| 21 |
+
spread = np.max(stack, axis=0) - np.min(stack, axis=0)
|
| 22 |
+
stable = np.mean(spread, axis=2) <= 12.0
|
| 23 |
+
if current is not None:
|
| 24 |
+
current_f = current.astype(np.float32)
|
| 25 |
+
distance = np.mean(np.abs(estimate.astype(np.float32) - current_f), axis=2)
|
| 26 |
+
# Reject a temporal estimate that agrees with the overlay itself.
|
| 27 |
+
stable &= distance > 8.0
|
| 28 |
+
support = (mask > 0) & stable
|
| 29 |
+
del min_agreement
|
| 30 |
+
if len(frames) < 2:
|
| 31 |
+
support[:] = False
|
| 32 |
+
return estimate, (support.astype(np.uint8) * 255)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def align_translation(reference: np.ndarray, candidate: np.ndarray) -> tuple[np.ndarray, float]:
|
| 36 |
+
"""Align a neighboring frame using phase correlation."""
|
| 37 |
+
ref = cv2.cvtColor(reference, cv2.COLOR_BGR2GRAY).astype(np.float32)
|
| 38 |
+
cur = cv2.cvtColor(candidate, cv2.COLOR_BGR2GRAY).astype(np.float32)
|
| 39 |
+
shift, response = cv2.phaseCorrelate(ref, cur)
|
| 40 |
+
if abs(shift[0]) > reference.shape[1] * 0.1 or abs(shift[1]) > reference.shape[0] * 0.1:
|
| 41 |
+
return candidate, 0.0
|
| 42 |
+
matrix = np.float32([[1, 0, shift[0]], [0, 1, shift[1]]])
|
| 43 |
+
aligned = cv2.warpAffine(candidate, matrix, (candidate.shape[1], candidate.shape[0]), borderMode=cv2.BORDER_REFLECT)
|
| 44 |
+
return aligned, float(response)
|
src/videoclean/refine.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative glyph-shaped mask refinement."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class RefinedMask:
|
| 12 |
+
mask: np.ndarray
|
| 13 |
+
confidence: float
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def refine_overlay_mask(frame: np.ndarray, coarse_mask: np.ndarray, *, min_confidence: float = 0.20) -> RefinedMask:
|
| 17 |
+
"""Keep high-contrast glyph-like pixels inside a detector mask.
|
| 18 |
+
|
| 19 |
+
The coarse mask remains the safety fallback when local evidence is
|
| 20 |
+
ambiguous; no pixels outside it are ever introduced.
|
| 21 |
+
"""
|
| 22 |
+
mask = np.asarray(coarse_mask)
|
| 23 |
+
if mask.ndim == 3:
|
| 24 |
+
mask = mask[:, :, 0]
|
| 25 |
+
coarse = mask > 0
|
| 26 |
+
if frame.ndim != 3 or frame.shape[:2] != coarse.shape or not coarse.any():
|
| 27 |
+
return RefinedMask(coarse.astype(np.uint8), 0.0)
|
| 28 |
+
|
| 29 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(np.float32)
|
| 30 |
+
local = cv2.GaussianBlur(gray, (0, 0), 1.2)
|
| 31 |
+
contrast = np.abs(gray - local)
|
| 32 |
+
roi_values = contrast[coarse]
|
| 33 |
+
if roi_values.size == 0:
|
| 34 |
+
return RefinedMask(coarse.astype(np.uint8), 0.0)
|
| 35 |
+
threshold = max(8.0, float(np.percentile(roi_values, 55.0)))
|
| 36 |
+
glyph = coarse & (contrast >= threshold)
|
| 37 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
|
| 38 |
+
glyph = cv2.morphologyEx(glyph.astype(np.uint8), cv2.MORPH_OPEN, kernel)
|
| 39 |
+
glyph = cv2.morphologyEx(glyph, cv2.MORPH_CLOSE, kernel) > 0
|
| 40 |
+
retained = float(glyph.sum()) / float(coarse.sum())
|
| 41 |
+
contrast_score = min(1.0, float(np.mean(roi_values)) / 32.0)
|
| 42 |
+
confidence = min(1.0, 0.65 * contrast_score + 0.35 * min(1.0, retained * 2.0))
|
| 43 |
+
if confidence < min_confidence or glyph.sum() < 2:
|
| 44 |
+
return RefinedMask(coarse.astype(np.uint8), confidence)
|
| 45 |
+
return RefinedMask(glyph.astype(np.uint8), confidence)
|