Spaces:
Paused
Paused
File size: 6,955 Bytes
1fe7075 | 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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """Wall edges around objects in front of it: wallpaper up to their real outline.
Segmentation marks a bouquet, a lamp or a vase as one coarse blob (and often
with the wrong class: a dried bouquet came back as "bulletin board"), so the
wall mask stopped at a blocky outline and the old wall showed around and
between the stems. Next to each wall, a pixel that lies on the wall's own
plane (by depth) is bare wall; there each pixel is keyed against the bare
wall's colour (filled in from the wall around it), so what still looks like
that wall gets the wallpaper with soft coverage, and every stem, leaf and
object keeps its photographed pixels. Solid things in front of the wall (a
vase, a chair) are off the plane and are never touched.
Functions
---------
matte_wall_decor - the wall mask grown into decor, and its per-pixel coverage
"""
from __future__ import annotations
import cv2
import numpy as np
from state import class_ids
from utils import seg_class_mask
# Never keyed: the wall's architectural neighbours.
ARCHITECTURE_CLASSES = {"floor", "ceiling", "door", "window", "column", "stairs", "windowpane", "rug", "curtain"}
# How far from the wall pixels may be keyed (fraction of the short side).
DECOR_REACH_RATIO = 0.08
# On the wall's plane: within this distance of it (metres, or this share of the depth if larger).
PLANE_TOLERANCE_M = 0.04
PLANE_TOLERANCE_RATIO = 0.015
# Plane distances are computed on every n-th pixel and interpolated.
PLANE_STRIDE = 2
# Bare-wall colour estimate resolution (long side, px).
BACKGROUND_SIDE = 640
BACKGROUND_SIGMA_RATIO = 0.012 # of the long side
# A pixel is decor, not wall, from these differences to the bare wall (OpenCV Lab units):
# colour (a dried flower, a leaf) or brightness well beyond the wall's own shading.
CHROMA_FROM, CHROMA_TO = 6.0, 14.0
LIGHTNESS_FROM, LIGHTNESS_TO = 24.0, 40.0
# Pixels the wall covers less than this stay out of the mask.
MIN_COVERAGE = 0.1
# Matches the browser's own edge feather (edge-weight.ts EDGE_FEATHER_PX), which no longer
# applies once a wall ships its own coverage.
EDGE_FEATHER_PX = 2.0
def _feather(mask: np.ndarray) -> np.ndarray:
"""0..1: the browser's edge feather (distance to the nearest outside pixel / 2); the photo border is no edge."""
padded = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_REPLICATE)
distance = cv2.distanceTransform(padded, cv2.DIST_L2, 5)[1:-1, 1:-1]
return np.minimum(distance / EDGE_FEATHER_PX, 1.0).astype(np.float32)
def _bare_wall(img_np: np.ndarray, wall: np.ndarray) -> np.ndarray:
"""The photo's wall colour everywhere near the wall, spread from the wall's own pixels (Lab, float).
A masked (normalised) Gaussian blur: each pixel gets the average colour of the
wall around it, so the wall's own shading carries over. A wider pass covers
pixels farther from the wall than the narrow one reaches.
"""
height, width = wall.shape
scale = BACKGROUND_SIDE / max(height, width)
size = (max(8, round(width * scale)), max(8, round(height * scale)))
small = cv2.cvtColor(cv2.resize(img_np, size, interpolation=cv2.INTER_AREA), cv2.COLOR_RGB2LAB).astype(np.float32)
known = cv2.erode(cv2.resize(wall, size, interpolation=cv2.INTER_NEAREST), np.ones((3, 3), np.uint8)).astype(np.float32)
result = np.zeros_like(small)
weight_done = np.zeros(known.shape, np.float32)
for sigma in (BACKGROUND_SIGMA_RATIO * max(size), 4 * BACKGROUND_SIGMA_RATIO * max(size)):
weight = cv2.GaussianBlur(known, (0, 0), sigma)
colour = cv2.GaussianBlur(small * known[..., None], (0, 0), sigma) / np.maximum(weight, 1e-6)[..., None]
take = (weight_done < 0.05) & (weight >= 0.05)
result[take] = colour[take]
weight_done = np.maximum(weight_done, np.where(take, weight, 0))
return cv2.resize(result, (width, height), interpolation=cv2.INTER_LINEAR)
def _on_plane(points: np.ndarray, origin: np.ndarray, normal: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
"""0..1 per pixel: how surely its 3D point lies on the wall's plane (full resolution, smooth)."""
sampled = points[::PLANE_STRIDE, ::PLANE_STRIDE].astype(np.float32)
distance = np.abs((sampled - origin.astype(np.float32)) @ normal.astype(np.float32))
tolerance = np.maximum(PLANE_TOLERANCE_M, PLANE_TOLERANCE_RATIO * np.abs(sampled[..., 2]))
closeness = ((distance <= tolerance) & np.isfinite(distance)).astype(np.float32)
closeness = cv2.resize(closeness, (shape[1], shape[0]), interpolation=cv2.INTER_LINEAR)
# Only anti-aliased (no wider ramp): glass a few centimetres off the wall must stay glass.
return cv2.GaussianBlur(closeness, (0, 0), 0.75)
def matte_wall_decor(
img_np: np.ndarray,
seg_map: np.ndarray,
wall: np.ndarray,
points: np.ndarray | None,
plane,
) -> tuple[np.ndarray, np.ndarray | None]:
"""(mask, alpha): the wall grown up to the real outline of objects in front of it, and uint8
coverage per pixel. alpha is None when nothing changes (no depth, no plane, nothing to key)."""
wall = (wall > 0).astype(np.uint8)
if points is None or plane is None or not wall.any() or points.shape[:2] != wall.shape:
return wall, None
short_side = min(wall.shape)
from_wall = cv2.distanceTransform(1 - wall, cv2.DIST_L2, 3)
architecture = seg_class_mask(seg_map, class_ids(ARCHITECTURE_CLASSES)) > 0
near = (from_wall > 0) & (from_wall <= DECOR_REACH_RATIO * short_side) & ~architecture
if not near.any():
return wall, None
on_plane = _on_plane(points, plane.origin, plane.normal, wall.shape)
keyed = near & (on_plane > 0.5)
if not keyed.any():
return wall, None
bare = _bare_wall(img_np, wall) # already Lab
photo = cv2.cvtColor(img_np, cv2.COLOR_RGB2LAB).astype(np.float32)
chroma = np.hypot(photo[..., 1] - bare[..., 1], photo[..., 2] - bare[..., 2])
lightness = np.abs(photo[..., 0] - bare[..., 0])
is_object = np.maximum(
np.clip((chroma - CHROMA_FROM) / (CHROMA_TO - CHROMA_FROM), 0.0, 1.0),
np.clip((lightness - LIGHTNESS_FROM) / (LIGHTNESS_TO - LIGHTNESS_FROM), 0.0, 1.0),
)
is_object = cv2.GaussianBlur(is_object, (0, 0), 0.7) # anti-aliased stem edges
keyed_coverage = (1.0 - is_object) * np.clip(2.0 * on_plane - 1.0, 0.0, 1.0)
grown = keyed & (keyed_coverage >= MIN_COVERAGE)
# Only what joins the wall: a patch of wall colour on the far side of a chair is not this wall.
count, labels = cv2.connectedComponents((wall | grown).astype(np.uint8), connectivity=8)
joined = np.isin(labels, np.unique(labels[wall > 0]))
mask = (wall > 0) | (grown & joined)
if int(mask.sum()) == int(wall.sum()):
return wall, None
coverage = np.where(grown & joined, keyed_coverage, _feather(mask.astype(np.uint8)))
coverage[~mask] = 0.0
alpha = np.clip(np.rint(coverage * 255.0), 0, 255).astype(np.uint8)
return mask.astype(np.uint8), alpha
|