prevision / apps /renderer /services /floor /edge_refinement.py
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
15.6 kB
"""Floor edge refinement: snap the mask edge to the photo and straighten it along walls.
The floor mask is built from segmentation labels at roughly 1/8 of the photo's
resolution, so its edge wobbles 10-20 px around the real baseboard or furniture
foot. Two steps fix that:
1. A colour guided filter (He et al., "Guided Image Filtering") with the photo as
guide moves the edge onto the photo's own edges. Its 0.5 level set, sharpened
by the local gradient, gives a sub-pixel, anti-aliased alpha.
2. Where the floor meets a wall, door or column, the edge is redrawn as straight
lines (the same line fitting walls use) and rasterised with anti-aliasing.
Functions
---------
guided_filter - fast colour guided filter (cv2.boxFilter + numpy)
refine_surface_edges - refined binary mask and per-pixel alpha for the floor
"""
from __future__ import annotations
import time
import cv2
import numpy as np
from config.surface import (
ENABLE_SURFACE_EDGE_REFINEMENT,
SURFACE_EDGE_REFINE_EPS,
SURFACE_EDGE_REFINE_RADIUS_RATIO,
SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO,
SURFACE_EDGE_STRAIGHTEN_RATIO,
)
from services.image.polygons import _contour_depths, _straight_polygon, straighten_polyline
from state import class_ids
from utils import seg_class_mask
# Pixels covered by less than ~10% stay out of the mask (and so get no UVs).
ALPHA_FLOOR = 26
# The floor's edge against these is an architectural straight line.
ARCHITECTURAL_CLASSES = {"wall", "door", "column"}
# Width in px of the anti-aliased transition from tile to photo.
EDGE_TRANSITION_PX = 1.0
# Refinement that changes the floor area more than this is distrusted.
MAX_AREA_CHANGE = 0.15
# Holes the filter punches into confident floor (textured carpet whose light
# specks look like the wall next to it) up to this size, as a fraction of the
# short image side squared, are filled.
SPECK_MAX_AREA_RATIO = 0.02
# Sub-pixel precision for polygon fills (cv2 `shift` bits).
_FILL_SHIFT = 4
# Straightened edges are rasterised at this many samples per pixel side.
_SUPERSAMPLE = 4
def guided_filter(guide: np.ndarray, source: np.ndarray, radius: int, eps: float, subsample: int = 2) -> np.ndarray:
"""Edge-preserving smoothing of `source` that follows the edges of the RGB `guide`.
`guide` is HxWx3 float32 in [0, 1], `source` HxW float32. The linear
coefficients are computed at 1/`subsample` resolution and upsampled
("fast guided filter"), which keeps it to a few tens of ms per megapixel.
"""
h, w = source.shape[:2]
scale = max(1, int(subsample)) if radius >= 4 else 1
if scale > 1:
size = (max(1, w // scale), max(1, h // scale))
guide_small = cv2.resize(guide, size, interpolation=cv2.INTER_AREA)
source_small = cv2.resize(source, size, interpolation=cv2.INTER_AREA)
else:
guide_small, source_small = guide, source
r = max(1, int(round(radius / scale)))
def box(values: np.ndarray) -> np.ndarray:
return cv2.boxFilter(values, -1, (2 * r + 1, 2 * r + 1), borderType=cv2.BORDER_REFLECT)
mean_i = box(guide_small)
mean_p = box(source_small)
cov_ip = box(guide_small * source_small[..., None]) - mean_i * mean_p[..., None]
def var(i: int, j: int) -> np.ndarray:
return box(guide_small[..., i] * guide_small[..., j]) - mean_i[..., i] * mean_i[..., j]
rr, rg, rb = var(0, 0) + eps, var(0, 1), var(0, 2)
gg, gb, bb = var(1, 1) + eps, var(1, 2), var(2, 2) + eps
# Inverse of the symmetric 3x3 covariance (adjugate / determinant), per pixel.
inv_rr = gg * bb - gb * gb
inv_rg = rb * gb - rg * bb
inv_rb = rg * gb - rb * gg
inv_gg = rr * bb - rb * rb
inv_gb = rg * rb - rr * gb
inv_bb = rr * gg - rg * rg
det = rr * inv_rr + rg * inv_rg + rb * inv_rb
c0, c1, c2 = cov_ip[..., 0], cov_ip[..., 1], cov_ip[..., 2]
a = np.stack((
inv_rr * c0 + inv_rg * c1 + inv_rb * c2,
inv_rg * c0 + inv_gg * c1 + inv_gb * c2,
inv_rb * c0 + inv_gb * c1 + inv_bb * c2,
), axis=-1) / det[..., None]
b = mean_p - (a * mean_i).sum(axis=-1)
mean_a, mean_b = box(a), box(b)
if scale > 1:
mean_a = cv2.resize(mean_a, (w, h), interpolation=cv2.INTER_LINEAR)
mean_b = cv2.resize(mean_b, (w, h), interpolation=cv2.INTER_LINEAR)
return (mean_a * guide).sum(axis=-1) + mean_b
def refine_surface_edges(
img_np: np.ndarray,
surface_mask: np.ndarray,
seg_map: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, dict]:
"""Return (mask, alpha, metadata) for the floor surface.
`alpha` is uint8 at full resolution (255 = fully tile); `mask` is every pixel
with visible coverage, so the renderer has UVs and lighting for the whole
anti-aliased edge. Disabled or distrusted refinement returns the input mask
with a hard alpha, which is the previous behaviour.
"""
started = time.perf_counter()
surface = (surface_mask > 0).astype(np.uint8)
before = int(surface.sum())
metadata = {
"edgeRefinementEnabled": ENABLE_SURFACE_EDGE_REFINEMENT,
"edgeRefinementApplied": False,
"edgeRefinementReason": "disabled" if not ENABLE_SURFACE_EDGE_REFINEMENT else "empty-surface",
"edgeRefinementPixelsBefore": before,
"edgeRefinementPixelsAfter": before,
}
if not ENABLE_SURFACE_EDGE_REFINEMENT or before == 0:
return surface, surface * np.uint8(255), metadata
h, w = surface.shape[:2]
short_side = min(h, w)
radius = max(2, int(round(short_side * SURFACE_EDGE_REFINE_RADIUS_RATIO)))
guide = img_np.astype(np.float32) / 255.0
snapped = guided_filter(guide, surface.astype(np.float32), radius, SURFACE_EDGE_REFINE_EPS)
alpha = _crisp_alpha(snapped)
guided_ms = (time.perf_counter() - started) * 1000
straighten_started = time.perf_counter()
straight_stats = {"edgeStraightenedRuns": 0, "edgeStraightenedPixels": 0}
tolerance = SURFACE_EDGE_STRAIGHTEN_RATIO * short_side
if tolerance > 0:
architectural = seg_class_mask(seg_map, class_ids(ARCHITECTURAL_CLASSES))
reach = 2 * (radius + int(np.ceil(tolerance))) + 1
architectural_near = cv2.dilate(
architectural, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (reach, reach)),
)
binary = (alpha >= 0.5).astype(np.uint8)
# Along walls, notches the filter cut into the edge (texture near a light
# wall) are closed first, so the fitted lines run past them.
notch = (2 * int(np.ceil(tolerance)) + 1) | 1
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (notch, notch)))
binary = np.where(architectural_near > 0, closed, binary).astype(np.uint8)
straightened = _straighten_along(
binary,
architectural_near,
tolerance,
min_run=max(8, int(round(short_side * SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO))),
)
if straightened is not None:
coverage, band, straight_stats = straightened
alpha = np.where(band > 0, coverage.astype(np.float32) / 255.0, alpha)
straighten_ms = (time.perf_counter() - straighten_started) * 1000
alpha_u8 = np.clip(np.rint(alpha * 255.0), 0, 255).astype(np.uint8)
alpha_u8, filled_specks = _fill_specks(alpha_u8, surface, int((SPECK_MAX_AREA_RATIO * short_side) ** 2))
refined = _keep_connected_to(alpha_u8 >= ALPHA_FLOOR, surface)
alpha_u8[refined == 0] = 0
after = int(refined.sum())
metadata.update({
"edgeRefinementPixelsAfter": after,
"edgeRefinementRadius": radius,
"edgeRefinementEps": SURFACE_EDGE_REFINE_EPS,
"edgeStraightenTolerance": round(tolerance, 2),
"edgeFilledSpecks": filled_specks,
**straight_stats,
"edgeRefinementTimingMs": {
"guidedFilter": round(guided_ms, 2),
"straighten": round(straighten_ms, 2),
"total": round((time.perf_counter() - started) * 1000, 2),
},
})
if abs(after - before) > MAX_AREA_CHANGE * before:
metadata["edgeRefinementReason"] = "area-change-too-large"
metadata["edgeRefinementPixelsAfter"] = before
return surface, surface * np.uint8(255), metadata
metadata["edgeRefinementApplied"] = True
metadata["edgeRefinementReason"] = "refined"
print(
"[EDGE_REFINEMENT] "
f"pixels {before}->{after} radius={radius} runs={straight_stats['edgeStraightenedRuns']} "
f"guided={guided_ms:.1f}ms straighten={straighten_ms:.1f}ms",
flush=True,
)
return refined, alpha_u8, metadata
def _crisp_alpha(snapped: np.ndarray) -> np.ndarray:
"""Anti-aliased coverage of the guided filter's 0.5 level set.
Dividing by the local gradient turns the filter value into a signed distance
(in px) from that level set, so the edge is ~1 px wide wherever the photo's
edge was weak and the filter output is only a gentle ramp.
"""
grad_x = cv2.Sobel(snapped, cv2.CV_32F, 1, 0, ksize=1) * 0.5
grad_y = cv2.Sobel(snapped, cv2.CV_32F, 0, 1, ksize=1) * 0.5
gradient = np.maximum(np.sqrt(grad_x * grad_x + grad_y * grad_y), 1e-3)
distance = (snapped - 0.5) / gradient
return np.clip(0.5 + distance / EDGE_TRANSITION_PX, 0.0, 1.0).astype(np.float32)
def _straighten_along(
binary: np.ndarray,
architectural_near: np.ndarray,
tolerance: float,
min_run: int,
):
"""Redraw the edge runs that lie along walls as straight lines.
Returns (coverage, band, stats): anti-aliased coverage of the redrawn mask
(uint8), the band around the redrawn runs where it replaces the guided alpha,
and run statistics; or None when no run qualified.
"""
h, w = binary.shape[:2]
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
if hierarchy is None:
return None
depths = _contour_depths(hierarchy[0][:, 3])
band = np.zeros((h, w), np.uint8)
band_width = max(3, int(np.ceil(2 * tolerance)) + 3)
scale = float(1 << _FILL_SHIFT)
runs = 0
run_pixels = 0
polygons: list[tuple[int, np.ndarray]] = []
for index in np.argsort(depths, kind="stable"):
points = contours[index].reshape(-1, 2)
if len(points) < 3:
continue
along = architectural_near[points[:, 1], points[:, 0]] > 0
# The photo's border is already straight; leave it exactly in place.
along &= ~((points[:, 0] == 0) | (points[:, 1] == 0) | (points[:, 0] == w - 1) | (points[:, 1] == h - 1))
if along.all() and len(points) >= min_run:
polygon = _straight_polygon(points, tolerance)
pieces = [(True, polygon)]
runs += 1
run_pixels += len(points)
elif along.all() or not along.any():
pieces = [(False, points.astype(np.float32))]
else:
# Start at an off-wall point so no run wraps around the array end.
start = int(np.flatnonzero(~along)[0])
points, along = np.roll(points, -start, axis=0), np.roll(along, -start)
boundaries = np.flatnonzero(np.diff(along.astype(np.int8))) + 1
pieces = []
for run in np.split(np.arange(len(points)), boundaries):
run_points = points[run]
if along[run[0]] and len(run) >= min_run:
pieces.append((True, straighten_polyline(run_points, tolerance)))
runs += 1
run_pixels += len(run)
else:
pieces.append((False, run_points.astype(np.float32)))
for straight, piece in pieces:
if straight and len(piece) >= 2:
closed = len(pieces) == 1
cv2.polylines(band, [np.round(piece * scale).astype(np.int32)], closed, 1,
thickness=band_width, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
polygons.append((int(depths[index]), np.concatenate([piece for _, piece in pieces])))
if runs == 0:
return None
return _polygon_coverage(polygons, band), band, {"edgeStraightenedRuns": runs, "edgeStraightenedPixels": run_pixels}
def _polygon_coverage(polygons: list[tuple[int, np.ndarray]], band: np.ndarray) -> np.ndarray:
"""Exact pixel coverage of the redrawn mask inside the band's bounding box.
The contours run through the centres of the outermost mask pixels, half a
pixel inside the mask's real outline, so the polygons are filled at
`_SUPERSAMPLE`x resolution, grown by half a pixel and box-averaged back down.
"""
h, w = band.shape[:2]
coverage = np.zeros((h, w), np.uint8)
ys, xs = np.nonzero(band)
if not len(ys):
return coverage
y0, y1, x0, x1 = int(ys.min()), int(ys.max()) + 1, int(xs.min()), int(xs.max()) + 1
ss = _SUPERSAMPLE
fine = np.zeros(((y1 - y0) * ss, (x1 - x0) * ss), np.uint8)
scale = float(1 << _FILL_SHIFT)
origin = np.array([x0, y0], np.float32)
for depth, polygon in polygons:
if len(polygon) < 3:
continue
# Pixel centre (x, y) is fine pixel (x * ss + (ss - 1) / 2).
fine_points = (polygon - origin) * ss + (ss - 1) / 2.0
# Outer edges fill, holes (furniture cut-outs) clear: nesting parity.
cv2.fillPoly(fine, [np.round(fine_points * scale).astype(np.int32)], 255 if depth % 2 == 0 else 0,
lineType=cv2.LINE_8, shift=_FILL_SHIFT)
grow = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ss + 1, ss + 1))
fine = cv2.dilate(fine, grow)
coverage[y0:y1, x0:x1] = cv2.resize(fine, (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA)
return coverage
def _fill_specks(alpha: np.ndarray, original: np.ndarray, max_area: int) -> tuple[np.ndarray, int]:
"""Fill the small holes the filter punched into floor the segmentation was sure of.
On textured floors (speckled carpet) next to a light wall, light specks look
like the wall to the guided filter and turn into holes where the photo shows
through the tile. A hole is filled when it is small, enclosed by tile and
mostly floor in the original mask; real cut-outs (a table base, a chair leg)
were never floor there. A small grey closing then removes partial specks.
"""
holes = (alpha < 128).astype(np.uint8)
count, labels, stats, _ = cv2.connectedComponentsWithStats(holes, connectivity=4)
filled = 0
if count > 1:
area = stats[:, cv2.CC_STAT_AREA].astype(np.float64)
floor_share = np.bincount(labels.ravel(), weights=(original > 0).ravel(), minlength=count) / np.maximum(area, 1)
fill = (area <= max_area) & (floor_share > 0.5)
fill[0] = False
filled = int(fill.sum())
if filled:
alpha = alpha.copy()
alpha[fill[labels]] = 255
closed = cv2.morphologyEx(alpha, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
# Closing only fills: it never takes tile away from the original floor's outline.
return np.where(original > 0, closed, alpha), filled
def _keep_connected_to(candidate: np.ndarray, original: np.ndarray) -> np.ndarray:
"""Drop islands the filter created away from the original surface."""
candidate = candidate.astype(np.uint8)
count, labels = cv2.connectedComponents(candidate, connectivity=8)
if count <= 2:
return candidate
keep = np.zeros(count, dtype=bool)
keep[np.unique(labels[(original > 0) & (candidate > 0)])] = True
keep[0] = False
return keep[labels].astype(np.uint8)