Spaces:
Paused
Paused
File size: 4,212 Bytes
73828b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | """Pull a mask boundary onto the nearest real edge in the photograph.
Why
---
Surface masks pass through several morphological stages -- closing gaps, opening
away noise, dilating to cover the wall/floor join. Those kernels are ellipses,
and pushing a straight architectural line through a few ellipse close/open/dilate
passes scallops it. On a 1200x1600 photo the cumulative rounding radius is
10-15 px, which reads as a wobbly boundary along what should be a dead-straight
wall/ceiling or wall/floor join. Floors get it worst, having the largest kernels.
Shrinking the kernels is not the answer: they exist to close holes and cover
joins, and making them smaller trades wobble for gaps.
How
---
A guided filter (He et al., "Guided Image Filtering") using the photo itself as
the guide. Where the image has an edge, the filter's local linear model follows
it and the mask boundary snaps onto it; where the image is flat, it just
smooths. That both removes the morphological scalloping and improves accuracy,
and it needs no per-surface tuning because the photo supplies the geometry.
Implemented with box filters rather than cv2.ximgproc.guidedFilter, which lives
in opencv-contrib and is not in opencv-python-headless.
Limits
------
It can only snap to an edge that is visible. A white wall meeting a white
ceiling has almost no gradient, so the boundary there is smoothed but not
relocated. Callers must still re-apply their own exclusions afterwards: the
filter knows about image edges, not about semantics, so nothing stops it
drifting a few pixels into a neighbouring class.
"""
from __future__ import annotations
import cv2
import numpy as np
def guided_filter(guide: np.ndarray, source: np.ndarray, radius: int, eps: float) -> np.ndarray:
"""Single-channel guided filter. `guide` and `source` are float32 in [0, 1]."""
window = (radius, radius)
mean_guide = cv2.boxFilter(guide, -1, window)
mean_source = cv2.boxFilter(source, -1, window)
mean_guide_source = cv2.boxFilter(guide * source, -1, window)
covariance = mean_guide_source - mean_guide * mean_source
mean_guide_sq = cv2.boxFilter(guide * guide, -1, window)
variance = mean_guide_sq - mean_guide * mean_guide
scale = covariance / (variance + eps)
offset = mean_source - scale * mean_guide
return cv2.boxFilter(scale, -1, window) * guide + cv2.boxFilter(offset, -1, window)
def snap_mask_to_image_edges(
mask: np.ndarray,
image_rgb: np.ndarray | None,
radius_ratio: float = 0.05,
eps: float = 1e-4,
threshold: float = 0.5,
) -> np.ndarray:
"""Return `mask` with its boundary pulled onto nearby edges in `image_rgb`.
Interior pixels are untouched -- the filter only moves boundaries, so a
reclaimed television sitting well inside the mask stays filled even though
it has strong edges of its own.
Returns the mask unchanged when no image is supplied, so callers that lack
one keep working.
radius_ratio is the important parameter and it must exceed the wobble it is
meant to remove -- the filter can only move a boundary about `radius` px.
Measured on a synthetic straight edge with a +/-6 px wobble, boundary
std-dev came out at:
ratio 0.01 (r=5) 3.69 px barely better than the 3.88 px input
ratio 0.03 (r=13) 2.11 px
ratio 0.05 (r=21) 0.24 px lands exactly on the true edge
ratio 0.08 (r=33) 0.00 px
A large radius does not cost detail, because detail that matters has an
image edge for the filter to follow: a 40 px doorframe notch survived
intact at every ratio up to 0.08. eps barely matters between 1e-6 and 1e-4.
"""
mask_u8 = mask.astype(np.uint8, copy=False)
if image_rgb is None or not mask_u8.any() or mask_u8.all():
return mask_u8
height, width = mask_u8.shape[:2]
if image_rgb.shape[:2] != (height, width):
return mask_u8
radius = max(4, int(round(min(height, width) * radius_ratio))) | 1
guide = cv2.cvtColor(image_rgb.astype(np.uint8), cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0
filtered = guided_filter(guide, mask_u8.astype(np.float32), radius, eps)
return (filtered > threshold).astype(np.uint8)
|