Spaces:
Paused
Paused
GitHub Actions commited on
Commit ·
0d1fbc6
1
Parent(s): 79046e7
Deploy from GitHub commit 0b4a46d6249523704b10c03464426d0ab07f81cd
Browse files- app.py +198 -41
- golden_render.py +19 -3
- verify_n1_sim.py +29 -0
- verify_r1_rotation_sim.py +47 -2
- verify_r4_intrinsic_sim.py +45 -2
app.py
CHANGED
|
@@ -539,6 +539,73 @@ def build_shade_map(
|
|
| 539 |
return _encode_shade(relative, lo, hi), (lo, hi)
|
| 540 |
|
| 541 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
def build_intrinsic_shade_map(
|
| 543 |
img_np: np.ndarray, surface_mask: np.ndarray
|
| 544 |
) -> tuple[np.ndarray | None, tuple[float, float]]:
|
|
@@ -580,6 +647,10 @@ def build_intrinsic_shade_map(
|
|
| 580 |
shading = cv2.resize(shading, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 581 |
shading = shading.astype(np.float32)
|
| 582 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
floor_vals = shading[surface_mask > 0]
|
| 584 |
if floor_vals.size == 0:
|
| 585 |
return None, default_range
|
|
@@ -1387,33 +1458,32 @@ def estimate_default_rotation(
|
|
| 1387 |
WALL_CONTACT_CLASSES = {"wall", "door", "window"}
|
| 1388 |
|
| 1389 |
|
| 1390 |
-
def
|
| 1391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1392 |
) -> float | None:
|
| 1393 |
-
"""
|
| 1394 |
-
|
| 1395 |
-
|
| 1396 |
-
|
| 1397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1398 |
"""
|
| 1399 |
-
h, w = wall_mask.shape[:2]
|
| 1400 |
-
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
|
| 1401 |
-
band = cv2.bitwise_and(cv2.dilate(wall_mask, kern), cv2.dilate(floor_mask, kern))
|
| 1402 |
-
if int(band.sum()) < w:
|
| 1403 |
-
return None
|
| 1404 |
-
|
| 1405 |
-
segs = cv2.HoughLinesP(
|
| 1406 |
-
(band * 255).astype(np.uint8),
|
| 1407 |
-
rho=1.0,
|
| 1408 |
-
theta=np.pi / 360.0,
|
| 1409 |
-
threshold=40,
|
| 1410 |
-
minLineLength=max(24, int(min(h, w) * 0.08)),
|
| 1411 |
-
maxLineGap=10,
|
| 1412 |
-
)
|
| 1413 |
-
if segs is None or len(segs) < 5:
|
| 1414 |
-
return None
|
| 1415 |
-
|
| 1416 |
angles, weights = [], []
|
|
|
|
| 1417 |
for x1, y1, x2, y2 in segs[:, 0]:
|
| 1418 |
p = np.array([[x1, y1, 1.0], [x2, y2, 1.0]], dtype=np.float64) @ H.T
|
| 1419 |
if np.any(np.abs(p[:, 2]) < 1e-9):
|
|
@@ -1426,18 +1496,17 @@ def estimate_wall_rotation(
|
|
| 1426 |
continue
|
| 1427 |
angles.append(np.degrees(np.arctan2(dv, du)) % 90.0)
|
| 1428 |
weights.append(length)
|
| 1429 |
-
|
|
|
|
| 1430 |
return None
|
| 1431 |
|
| 1432 |
-
# Deduplicate before voting: a thick contact band yields MANY parallel
|
| 1433 |
-
# Hough segments for ONE wall, which would multiply that wall's weight
|
| 1434 |
-
# and let a long noisy diagonal outvote the true wall instead of
|
| 1435 |
-
# conflicting with it. One direction = one vote: keep the longest
|
| 1436 |
-
# segment per 3-deg direction bin.
|
| 1437 |
bins: dict[int, float] = {}
|
| 1438 |
for ang, wt in zip(angles, weights):
|
| 1439 |
b = int(ang // 3.0)
|
| 1440 |
-
|
|
|
|
|
|
|
|
|
|
| 1441 |
bin_angles = np.array([(b * 3.0 + 1.5) for b in bins])
|
| 1442 |
wts = np.array(list(bins.values()))
|
| 1443 |
|
|
@@ -1449,15 +1518,97 @@ def estimate_wall_rotation(
|
|
| 1449 |
cw = float(np.sum(wts * np.cos(theta)))
|
| 1450 |
sw = float(np.sum(wts * np.sin(theta)))
|
| 1451 |
total = float(np.sum(wts))
|
| 1452 |
-
if total < 1e-9 or np.hypot(cw, sw) / total <
|
| 1453 |
return None
|
| 1454 |
|
| 1455 |
ang = (np.degrees(np.arctan2(sw, cw)) % 360.0) / 360.0 * 90.0
|
| 1456 |
if ang >= 45.0:
|
| 1457 |
ang -= 90.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1458 |
return float(ang)
|
| 1459 |
|
| 1460 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1461 |
# ---------------------------------------------------------------------------
|
| 1462 |
# B5 — Complement-Stamp Furniture
|
| 1463 |
# Use a single dilation pass (down from two) and restore the narrow contact
|
|
@@ -1776,15 +1927,21 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1776 |
# R1-3 — physical plane scale; null on relative depth so the frontend
|
| 1777 |
# falls back to the heuristic repeat.
|
| 1778 |
plane["metersPerUnit"] = estimate_meters_per_unit(depth, floor_mask, homography, w, h)
|
| 1779 |
-
# R1-4 —
|
| 1780 |
-
#
|
| 1781 |
-
|
| 1782 |
-
|
| 1783 |
-
|
| 1784 |
-
)
|
| 1785 |
-
if
|
| 1786 |
-
plane["defaultRotation"] =
|
| 1787 |
-
plane["rotationSource"] = "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1788 |
print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1789 |
|
| 1790 |
t0 = time.perf_counter()
|
|
|
|
| 539 |
return _encode_shade(relative, lo, hi), (lo, hi)
|
| 540 |
|
| 541 |
|
| 542 |
+
def repair_intrinsic_floor_shading(
|
| 543 |
+
shading: np.ndarray, img_np: np.ndarray, surface_mask: np.ndarray
|
| 544 |
+
) -> np.ndarray:
|
| 545 |
+
"""R4-1 v2 — repair the two failure classes of intrinsic decomposition on
|
| 546 |
+
real floors (both confirmed in the 2026-06-12 four-room dataset):
|
| 547 |
+
|
| 548 |
+
(a) Specular glare on a glossy original floor violates the Lambertian
|
| 549 |
+
assumption; the model dumps the highlight into albedo and the
|
| 550 |
+
illumination collapses into a dark blob exactly where the photo is
|
| 551 |
+
brightest (the "black spot on white tiles"). Physically glare means
|
| 552 |
+
MORE light, never less: rebuild shading inside glare zones from the
|
| 553 |
+
surrounding non-glare field, and never darker than the model's value.
|
| 554 |
+
|
| 555 |
+
(b) The original floor's grout grooves are real ambient-occlusion shading,
|
| 556 |
+
but they belong to the OLD floor's geometry — on a new surface they
|
| 557 |
+
re-print as phantom diagonal lines. A median filter (the same trick
|
| 558 |
+
the heuristic path uses, P1-3) removes structures thinner than ~1.5%
|
| 559 |
+
of the image while wide soft shadows (furniture, curtains) survive.
|
| 560 |
+
"""
|
| 561 |
+
h, w = shading.shape[:2]
|
| 562 |
+
floor = surface_mask > 0
|
| 563 |
+
|
| 564 |
+
# (a) glare zones: the brightest floor pixels of the photo.
|
| 565 |
+
lum = (
|
| 566 |
+
img_np[:, :, 0].astype(np.float32) * 0.299
|
| 567 |
+
+ img_np[:, :, 1].astype(np.float32) * 0.587
|
| 568 |
+
+ img_np[:, :, 2].astype(np.float32) * 0.114
|
| 569 |
+
)
|
| 570 |
+
floor_lum = lum[floor]
|
| 571 |
+
if floor_lum.size:
|
| 572 |
+
# Continuous suspicion weight: 0 below the floor's 80th brightness
|
| 573 |
+
# percentile, 1 at the glare threshold. The model's dark basin spans
|
| 574 |
+
# the whole highlight, not just the clipped core, so the correction
|
| 575 |
+
# must be proportional, not a hard mask — and real shadows are dark
|
| 576 |
+
# in the PHOTO too, so they get zero weight by construction.
|
| 577 |
+
p80 = float(np.percentile(floor_lum, 80.0))
|
| 578 |
+
glare_thresh = max(232.0, float(np.percentile(floor_lum, 97.0)))
|
| 579 |
+
suspicion = np.clip((lum - p80) / max(glare_thresh - p80, 1e-3), 0.0, 1.0)
|
| 580 |
+
suspicion[~floor] = 0.0
|
| 581 |
+
if float(suspicion.max()) > 0.5:
|
| 582 |
+
# Ambient field: normalized masked blur over the trusted floor,
|
| 583 |
+
# with a reach far wider than any glare blob.
|
| 584 |
+
keep = (floor & (suspicion < 0.3)).astype(np.float32)
|
| 585 |
+
if keep.any():
|
| 586 |
+
sigma = max(16.0, min(h, w) / 12.0)
|
| 587 |
+
num = cv2.GaussianBlur(shading * keep, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 588 |
+
den = cv2.GaussianBlur(keep, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 589 |
+
fill = num / np.maximum(den, 1e-4)
|
| 590 |
+
# Lift toward ambient where the photo is bright but the model
|
| 591 |
+
# went dark; never darken, never overshoot the ambient field.
|
| 592 |
+
lift = suspicion * np.clip(fill - shading, 0.0, None)
|
| 593 |
+
shading = shading + np.where(floor, lift, 0.0)
|
| 594 |
+
|
| 595 |
+
# (b) thin dark lines (grout ghosts): median over a window wider than a
|
| 596 |
+
# grout line, far smaller than any furniture shadow. Median needs uint8 —
|
| 597 |
+
# normalize around the floor median so the scale is stable.
|
| 598 |
+
floor_vals = shading[floor]
|
| 599 |
+
med = float(np.median(floor_vals)) if floor_vals.size else 1.0
|
| 600 |
+
if med > 1e-4:
|
| 601 |
+
scale = 96.0 / med
|
| 602 |
+
s8 = np.clip(shading * scale, 0, 255).astype(np.uint8)
|
| 603 |
+
med_k = max(9, int(min(h, w) / 60)) | 1
|
| 604 |
+
filtered = cv2.medianBlur(s8, med_k).astype(np.float32) / scale
|
| 605 |
+
shading = np.where(floor, filtered, shading)
|
| 606 |
+
return shading
|
| 607 |
+
|
| 608 |
+
|
| 609 |
def build_intrinsic_shade_map(
|
| 610 |
img_np: np.ndarray, surface_mask: np.ndarray
|
| 611 |
) -> tuple[np.ndarray | None, tuple[float, float]]:
|
|
|
|
| 647 |
shading = cv2.resize(shading, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 648 |
shading = shading.astype(np.float32)
|
| 649 |
|
| 650 |
+
# R4-1 v2 — glare-blob fill + grout-ghost removal BEFORE the blur so
|
| 651 |
+
# the smoothing feathers the repair edges for free.
|
| 652 |
+
shading = repair_intrinsic_floor_shading(shading, img_np, surface_mask)
|
| 653 |
+
|
| 654 |
floor_vals = shading[surface_mask > 0]
|
| 655 |
if floor_vals.size == 0:
|
| 656 |
return None, default_range
|
|
|
|
| 1458 |
WALL_CONTACT_CLASSES = {"wall", "door", "window"}
|
| 1459 |
|
| 1460 |
|
| 1461 |
+
def _fold_segments_to_rotation(
|
| 1462 |
+
segs: np.ndarray,
|
| 1463 |
+
H: np.ndarray,
|
| 1464 |
+
min_angles: int = 5,
|
| 1465 |
+
min_consensus: float = 0.6,
|
| 1466 |
+
bin_agg: str = "max",
|
| 1467 |
+
require_bimodal: bool = False,
|
| 1468 |
) -> float | None:
|
| 1469 |
+
"""Shared voting core of the rotation estimators: project Hough segments
|
| 1470 |
+
into floor-plane space, fold to the tile grid's 90-deg symmetry,
|
| 1471 |
+
aggregate per direction bin, and accept only on strong circular
|
| 1472 |
+
consensus. Returns None unless one direction clearly wins — a wrong
|
| 1473 |
+
rotation lays every tile visibly wrong, so the gates err on abstaining.
|
| 1474 |
+
|
| 1475 |
+
bin_agg: "max" — one direction, one vote (wall path: a thick contact
|
| 1476 |
+
band yields MANY collinear duplicates of ONE wall); "sum" — parallel
|
| 1477 |
+
lines are independent evidence (lattice path: ten grout lines in the
|
| 1478 |
+
same direction really are ten votes).
|
| 1479 |
+
|
| 1480 |
+
require_bimodal: a true lattice shows BOTH perpendicular families (they
|
| 1481 |
+
fold to the same angle); a stray single line family (one carpet seam,
|
| 1482 |
+
plank seams without cross joints) does not constitute a lattice and
|
| 1483 |
+
must abstain so the wall estimate decides instead.
|
| 1484 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1485 |
angles, weights = [], []
|
| 1486 |
+
dirs180 = []
|
| 1487 |
for x1, y1, x2, y2 in segs[:, 0]:
|
| 1488 |
p = np.array([[x1, y1, 1.0], [x2, y2, 1.0]], dtype=np.float64) @ H.T
|
| 1489 |
if np.any(np.abs(p[:, 2]) < 1e-9):
|
|
|
|
| 1496 |
continue
|
| 1497 |
angles.append(np.degrees(np.arctan2(dv, du)) % 90.0)
|
| 1498 |
weights.append(length)
|
| 1499 |
+
dirs180.append(np.degrees(np.arctan2(dv, du)) % 180.0)
|
| 1500 |
+
if len(angles) < min_angles:
|
| 1501 |
return None
|
| 1502 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1503 |
bins: dict[int, float] = {}
|
| 1504 |
for ang, wt in zip(angles, weights):
|
| 1505 |
b = int(ang // 3.0)
|
| 1506 |
+
if bin_agg == "sum":
|
| 1507 |
+
bins[b] = bins.get(b, 0.0) + wt
|
| 1508 |
+
else:
|
| 1509 |
+
bins[b] = max(bins.get(b, 0.0), wt)
|
| 1510 |
bin_angles = np.array([(b * 3.0 + 1.5) for b in bins])
|
| 1511 |
wts = np.array(list(bins.values()))
|
| 1512 |
|
|
|
|
| 1518 |
cw = float(np.sum(wts * np.cos(theta)))
|
| 1519 |
sw = float(np.sum(wts * np.sin(theta)))
|
| 1520 |
total = float(np.sum(wts))
|
| 1521 |
+
if total < 1e-9 or np.hypot(cw, sw) / total < min_consensus:
|
| 1522 |
return None
|
| 1523 |
|
| 1524 |
ang = (np.degrees(np.arctan2(sw, cw)) % 360.0) / 360.0 * 90.0
|
| 1525 |
if ang >= 45.0:
|
| 1526 |
ang -= 90.0
|
| 1527 |
+
|
| 1528 |
+
if require_bimodal:
|
| 1529 |
+
fam_a = fam_b = 0.0
|
| 1530 |
+
for d180, wt in zip(dirs180, weights):
|
| 1531 |
+
off = abs(((d180 - ang) + 90.0) % 180.0 - 90.0)
|
| 1532 |
+
if off <= 20.0:
|
| 1533 |
+
fam_a += wt
|
| 1534 |
+
elif off >= 70.0:
|
| 1535 |
+
fam_b += wt
|
| 1536 |
+
fam_total = fam_a + fam_b
|
| 1537 |
+
if fam_total < 1e-9 or min(fam_a, fam_b) / fam_total < 0.2:
|
| 1538 |
+
return None
|
| 1539 |
+
|
| 1540 |
return float(ang)
|
| 1541 |
|
| 1542 |
|
| 1543 |
+
def estimate_wall_rotation(
|
| 1544 |
+
wall_mask: np.ndarray, floor_mask: np.ndarray, H: np.ndarray
|
| 1545 |
+
) -> float | None:
|
| 1546 |
+
"""Dominant wall direction in floor-plane space (R1-4 v2). Detects line
|
| 1547 |
+
segments on the wall-floor contact band and votes through the shared
|
| 1548 |
+
fold/consensus gates.
|
| 1549 |
+
"""
|
| 1550 |
+
h, w = wall_mask.shape[:2]
|
| 1551 |
+
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
|
| 1552 |
+
band = cv2.bitwise_and(cv2.dilate(wall_mask, kern), cv2.dilate(floor_mask, kern))
|
| 1553 |
+
if int(band.sum()) < w:
|
| 1554 |
+
return None
|
| 1555 |
+
|
| 1556 |
+
segs = cv2.HoughLinesP(
|
| 1557 |
+
(band * 255).astype(np.uint8),
|
| 1558 |
+
rho=1.0,
|
| 1559 |
+
theta=np.pi / 360.0,
|
| 1560 |
+
threshold=40,
|
| 1561 |
+
minLineLength=max(24, int(min(h, w) * 0.08)),
|
| 1562 |
+
maxLineGap=10,
|
| 1563 |
+
)
|
| 1564 |
+
if segs is None or len(segs) < 5:
|
| 1565 |
+
return None
|
| 1566 |
+
return _fold_segments_to_rotation(segs, H)
|
| 1567 |
+
|
| 1568 |
+
|
| 1569 |
+
def estimate_floor_lattice_rotation(
|
| 1570 |
+
img_np: np.ndarray, floor_mask: np.ndarray, H: np.ndarray
|
| 1571 |
+
) -> float | None:
|
| 1572 |
+
"""R1-4 v3 — the direction users actually expect is the EXISTING floor's
|
| 1573 |
+
lattice (grout/plank lines), not the wall direction: an installer lays
|
| 1574 |
+
the new floor the way the old one runs (2026-06-12 dataset — rooms 1/2
|
| 1575 |
+
are laid diagonally, and the wall-aligned 13.5 deg read as wrong). Vote
|
| 1576 |
+
with line segments detected INSIDE the floor region, projected to plane
|
| 1577 |
+
space and folded to the grid's 90-deg symmetry, through the same dedupe
|
| 1578 |
+
and consensus gates as the wall estimator — lineless floors (carpet,
|
| 1579 |
+
plain surfaces) abstain and fall through to the wall-contact estimate.
|
| 1580 |
+
"""
|
| 1581 |
+
h, w = floor_mask.shape[:2]
|
| 1582 |
+
# Erode so mask boundaries and furniture contact edges cannot vote; only
|
| 1583 |
+
# texture interior to the floor counts.
|
| 1584 |
+
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
|
| 1585 |
+
interior = cv2.erode(floor_mask.astype(np.uint8), kern)
|
| 1586 |
+
if int(interior.sum()) < (h * w) // 50:
|
| 1587 |
+
return None
|
| 1588 |
+
|
| 1589 |
+
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
| 1590 |
+
edges = cv2.Canny(gray, 40, 120)
|
| 1591 |
+
edges[interior == 0] = 0
|
| 1592 |
+
|
| 1593 |
+
segs = cv2.HoughLinesP(
|
| 1594 |
+
edges,
|
| 1595 |
+
rho=1.0,
|
| 1596 |
+
theta=np.pi / 360.0,
|
| 1597 |
+
threshold=40,
|
| 1598 |
+
minLineLength=max(24, int(min(h, w) * 0.06)),
|
| 1599 |
+
maxLineGap=6,
|
| 1600 |
+
)
|
| 1601 |
+
if segs is None or len(segs) < 6:
|
| 1602 |
+
return None
|
| 1603 |
+
# A lattice yields many segments in two perpendicular families that fold
|
| 1604 |
+
# together: parallel grout lines are independent evidence, so bins SUM
|
| 1605 |
+
# (unlike the wall path, where parallel segments duplicate one wall) —
|
| 1606 |
+
# and BOTH families must be present, or it's a stray seam, not a lattice.
|
| 1607 |
+
return _fold_segments_to_rotation(
|
| 1608 |
+
segs, H, min_angles=6, bin_agg="sum", require_bimodal=True
|
| 1609 |
+
)
|
| 1610 |
+
|
| 1611 |
+
|
| 1612 |
# ---------------------------------------------------------------------------
|
| 1613 |
# B5 — Complement-Stamp Furniture
|
| 1614 |
# Use a single dilation pass (down from two) and restore the narrow contact
|
|
|
|
| 1927 |
# R1-3 — physical plane scale; null on relative depth so the frontend
|
| 1928 |
# falls back to the heuristic repeat.
|
| 1929 |
plane["metersPerUnit"] = estimate_meters_per_unit(depth, floor_mask, homography, w, h)
|
| 1930 |
+
# R1-4 v3 — rotation cue priority: the ORIGINAL floor's own lattice
|
| 1931 |
+
# outranks the wall direction (an installer matches the existing
|
| 1932 |
+
# floor), walls remain the fallback for lineless floors (carpet),
|
| 1933 |
+
# and the silhouette v1 estimate is the final fallback.
|
| 1934 |
+
H_plane = np.asarray(homography, np.float64).reshape(3, 3)
|
| 1935 |
+
lattice_rot = estimate_floor_lattice_rotation(img_np, floor_mask, H_plane)
|
| 1936 |
+
if lattice_rot is not None:
|
| 1937 |
+
plane["defaultRotation"] = lattice_rot
|
| 1938 |
+
plane["rotationSource"] = "floor-lattice"
|
| 1939 |
+
else:
|
| 1940 |
+
wall_mask = np.isin(seg_map, class_ids(WALL_CONTACT_CLASSES)).astype(np.uint8)
|
| 1941 |
+
wall_rot = estimate_wall_rotation(wall_mask, floor_mask, H_plane)
|
| 1942 |
+
if wall_rot is not None:
|
| 1943 |
+
plane["defaultRotation"] = wall_rot
|
| 1944 |
+
plane["rotationSource"] = "wall-contact"
|
| 1945 |
print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1946 |
|
| 1947 |
t0 = time.perf_counter()
|
golden_render.py
CHANGED
|
@@ -24,6 +24,7 @@ from PIL import Image
|
|
| 24 |
from verify_n1_sim import (
|
| 25 |
build_mips,
|
| 26 |
detect_wrap_mode,
|
|
|
|
| 27 |
make_seamless,
|
| 28 |
period_snap,
|
| 29 |
sample_bilinear_wrap,
|
|
@@ -88,6 +89,10 @@ def prepare_texture(tile_path):
|
|
| 88 |
# R2-3 v1 — truly organic materials (healed, not periodic) lay as
|
| 89 |
# procedural cells; periodic/authored tiles keep the plain repeat.
|
| 90 |
lay_mode = "cells"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return tex, repeat_scale, lay_mode
|
| 92 |
|
| 93 |
|
|
@@ -120,8 +125,15 @@ def procedural_cells(rx, ry, repeat_w, repeat_h, grout_frac, tw, th, footprint,
|
|
| 120 |
col = np.floor(sx / repeat_w).astype(np.int64)
|
| 121 |
lu = sx / repeat_w - col
|
| 122 |
lv = ry / repeat_h - row
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
tone = 0.94 + 0.12 * hash01(col - 0x13, row + 0x77)
|
| 126 |
half_u = grout_frac * 0.5
|
| 127 |
half_v = half_u * (repeat_w / repeat_h)
|
|
@@ -197,7 +209,11 @@ def render(bundle_path, tile_path, finish="matte"):
|
|
| 197 |
lv = seg.get("lightVector")
|
| 198 |
|
| 199 |
tex, repeat_scale, lay_mode = prepare_texture(tile_path)
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
# R2-3 v1 — derived seam tone + width; mirrors canvas-engine.ts (same
|
| 202 |
# every-16th-pixel mean, same no-physical-metadata fraction).
|
| 203 |
grout_col = tex.reshape(-1, 3)[::16].astype(np.float64).mean(axis=0) * 0.45
|
|
|
|
| 24 |
from verify_n1_sim import (
|
| 25 |
build_mips,
|
| 26 |
detect_wrap_mode,
|
| 27 |
+
flatten_luminance,
|
| 28 |
make_seamless,
|
| 29 |
period_snap,
|
| 30 |
sample_bilinear_wrap,
|
|
|
|
| 89 |
# R2-3 v1 — truly organic materials (healed, not periodic) lay as
|
| 90 |
# procedural cells; periodic/authored tiles keep the plain repeat.
|
| 91 |
lay_mode = "cells"
|
| 92 |
+
# R2-3b — strip the photo's baked lighting (mirrors canvas-engine.ts):
|
| 93 |
+
# snapped patterns stop showing tonal seams at every repeat; healed
|
| 94 |
+
# organic textures stop reading as patchwork across cells.
|
| 95 |
+
tex = flatten_luminance(tex)
|
| 96 |
return tex, repeat_scale, lay_mode
|
| 97 |
|
| 98 |
|
|
|
|
| 125 |
col = np.floor(sx / repeat_w).astype(np.int64)
|
| 126 |
lu = sx / repeat_w - col
|
| 127 |
lv = ry / repeat_h - row
|
| 128 |
+
# R2-3b — grid/diamond tiles are factory prints (real tiles repeat their
|
| 129 |
+
# print): content stays aligned per cell; organic grain keeps the
|
| 130 |
+
# per-cell toroidal window. Mirrors canvas-engine.ts.
|
| 131 |
+
if pattern in ("grid", "diamond"):
|
| 132 |
+
u = np.mod(lu, 1.0)
|
| 133 |
+
v = np.mod(lv, 1.0)
|
| 134 |
+
else:
|
| 135 |
+
u = np.mod(lu + hash01(col, row), 1.0)
|
| 136 |
+
v = np.mod(lv + hash01(col + 0x55, row - 0x21), 1.0)
|
| 137 |
tone = 0.94 + 0.12 * hash01(col - 0x13, row + 0x77)
|
| 138 |
half_u = grout_frac * 0.5
|
| 139 |
half_v = half_u * (repeat_w / repeat_h)
|
|
|
|
| 209 |
lv = seg.get("lightVector")
|
| 210 |
|
| 211 |
tex, repeat_scale, lay_mode = prepare_texture(tile_path)
|
| 212 |
+
# R4-2b — catalog finish overrides the texture-smoothness estimate (T9):
|
| 213 |
+
# matte gets no sheen however smooth the print; gloss keeps a baseline.
|
| 214 |
+
# Mirrors canvas-engine.ts.
|
| 215 |
+
gloss_est = estimate_gloss(np.asarray(Image.open(tile_path).convert("RGB")).astype(np.float64))
|
| 216 |
+
gloss = 0.0 if finish == "matte" else max(0.5, gloss_est) if finish == "gloss" else gloss_est
|
| 217 |
# R2-3 v1 — derived seam tone + width; mirrors canvas-engine.ts (same
|
| 218 |
# every-16th-pixel mean, same no-physical-metadata fraction).
|
| 219 |
grout_col = tex.reshape(-1, 3)[::16].astype(np.float64).mean(axis=0) * 0.45
|
verify_n1_sim.py
CHANGED
|
@@ -211,6 +211,35 @@ def period_snap(img):
|
|
| 211 |
return make_seamless(img), ("fallback", px, py, None, None)
|
| 212 |
|
| 213 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
def build_mips(img):
|
| 215 |
mips = [img.astype(np.float64)]
|
| 216 |
cur = img.astype(np.float64)
|
|
|
|
| 211 |
return make_seamless(img), ("fallback", px, py, None, None)
|
| 212 |
|
| 213 |
|
| 214 |
+
def flatten_luminance(img):
|
| 215 |
+
"""R2-3b — remove the source photo's baked lighting so the texture behaves
|
| 216 |
+
like albedo: divide by a heavily-blurred (toroidal) luminance field
|
| 217 |
+
normalized to the texture mean. The blur wraps, so the correction is
|
| 218 |
+
itself seamless; only the lighting gradient is equalized, grain/veining
|
| 219 |
+
survives. Mirror of flattenLuminance (canvas-engine.ts) — keep in
|
| 220 |
+
lockstep."""
|
| 221 |
+
h, w, _ = img.shape
|
| 222 |
+
lum = (
|
| 223 |
+
img[..., 0] * 0.299 + img[..., 1] * 0.587 + img[..., 2] * 0.114
|
| 224 |
+
).astype(np.float64)
|
| 225 |
+
|
| 226 |
+
def box_wrap(a, r, axis):
|
| 227 |
+
win = 2 * r + 1
|
| 228 |
+
out = np.zeros_like(a)
|
| 229 |
+
for d in range(-r, r + 1):
|
| 230 |
+
out += np.roll(a, -d, axis=axis)
|
| 231 |
+
return out / win
|
| 232 |
+
|
| 233 |
+
rx = max(2, w // 4)
|
| 234 |
+
ry = max(2, h // 4)
|
| 235 |
+
for _ in range(2):
|
| 236 |
+
lum = box_wrap(lum, rx, axis=1)
|
| 237 |
+
lum = box_wrap(lum, ry, axis=0)
|
| 238 |
+
gain = np.clip(lum.mean() / np.maximum(lum, 1.0), 0.6, 1.6)
|
| 239 |
+
out = np.clip(np.round(img.astype(np.float64) * gain[..., None]), 0, 255)
|
| 240 |
+
return out.astype(np.uint8)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
def build_mips(img):
|
| 244 |
mips = [img.astype(np.float64)]
|
| 245 |
cur = img.astype(np.float64)
|
verify_r1_rotation_sim.py
CHANGED
|
@@ -20,12 +20,15 @@ import numpy as np
|
|
| 20 |
from verify_r1_scale_sim import CAM_H, F, H as IMG_H, PITCH, W as IMG_W
|
| 21 |
|
| 22 |
# --- real implementation from app.py ------------------------------------------
|
|
|
|
|
|
|
| 23 |
src = open("app.py").read()
|
| 24 |
ns = {"np": np, "cv2": cv2}
|
| 25 |
-
start = src.index("def
|
| 26 |
-
end = src.index("\
|
| 27 |
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 28 |
estimate_wall_rotation = ns["estimate_wall_rotation"]
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def plane_homography():
|
|
@@ -71,6 +74,26 @@ def rotated_room(phi_deg, Hp, walls=("back", "right")):
|
|
| 71 |
return wall.astype(np.uint8), floor.astype(np.uint8)
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def fold(a):
|
| 75 |
a = a % 90.0
|
| 76 |
return a - 90.0 if a >= 45.0 else a
|
|
@@ -122,6 +145,28 @@ def main():
|
|
| 122 |
print(f" [{'PASS' if got is None else 'FAIL'}] conflicting 0/45 walls -> {got}")
|
| 123 |
ok &= got is None
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
print("\n" + ("ALL R1-4 SIM CHECKS PASSED" if ok else "R1-4 SIM CHECKS FAILED"))
|
| 126 |
return 0 if ok else 1
|
| 127 |
|
|
|
|
| 20 |
from verify_r1_scale_sim import CAM_H, F, H as IMG_H, PITCH, W as IMG_W
|
| 21 |
|
| 22 |
# --- real implementation from app.py ------------------------------------------
|
| 23 |
+
# R1-4 v3: the span covers the shared voting helper plus both estimators
|
| 24 |
+
# (wall-contact and floor-lattice), ending at the next section banner.
|
| 25 |
src = open("app.py").read()
|
| 26 |
ns = {"np": np, "cv2": cv2}
|
| 27 |
+
start = src.index("def _fold_segments_to_rotation")
|
| 28 |
+
end = src.index("\n# ---", start)
|
| 29 |
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 30 |
estimate_wall_rotation = ns["estimate_wall_rotation"]
|
| 31 |
+
estimate_floor_lattice_rotation = ns["estimate_floor_lattice_rotation"]
|
| 32 |
|
| 33 |
|
| 34 |
def plane_homography():
|
|
|
|
| 74 |
return wall.astype(np.uint8), floor.astype(np.uint8)
|
| 75 |
|
| 76 |
|
| 77 |
+
def lattice_room(phi_deg, Hp, tile=0.5):
|
| 78 |
+
"""R1-4 v3 — synthetic photo of an EXISTING tiled floor: dark grout lines
|
| 79 |
+
every `tile` metres in a world frame rotated by phi (perspective-correct
|
| 80 |
+
through the scene camera), on a light tile field."""
|
| 81 |
+
x_w, fwd, ok = world_grid(Hp)
|
| 82 |
+
phi = np.radians(phi_deg)
|
| 83 |
+
f_c = CAM_H / np.tan(PITCH) * 0.9 + 2.0
|
| 84 |
+
fx = fwd - f_c
|
| 85 |
+
xr = np.cos(phi) * x_w + np.sin(phi) * fx
|
| 86 |
+
fr = -np.sin(phi) * x_w + np.cos(phi) * fx
|
| 87 |
+
HX, HF = 4.0, 2.0
|
| 88 |
+
floor = ok & (np.abs(xr) <= HX) & (np.abs(fr) <= HF)
|
| 89 |
+
img = np.full((IMG_H, IMG_W, 3), 200, np.uint8)
|
| 90 |
+
gx = np.abs(xr / tile - np.round(xr / tile)) * tile < 0.015
|
| 91 |
+
gf = np.abs(fr / tile - np.round(fr / tile)) * tile < 0.015
|
| 92 |
+
img[floor & (gx | gf)] = 90
|
| 93 |
+
img[~floor] = 230
|
| 94 |
+
return img, floor.astype(np.uint8)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
def fold(a):
|
| 98 |
a = a % 90.0
|
| 99 |
return a - 90.0 if a >= 45.0 else a
|
|
|
|
| 145 |
print(f" [{'PASS' if got is None else 'FAIL'}] conflicting 0/45 walls -> {got}")
|
| 146 |
ok &= got is None
|
| 147 |
|
| 148 |
+
# 7-8 — R1-4 v3: the floor-lattice estimator recovers the EXISTING
|
| 149 |
+
# floor's grout direction from the photo (the cue that outranks walls)
|
| 150 |
+
for phi in (18.0, -30.0):
|
| 151 |
+
img, floor = lattice_room(phi, Hp)
|
| 152 |
+
got = estimate_floor_lattice_rotation(img, floor, Hp)
|
| 153 |
+
want = fold(phi)
|
| 154 |
+
good = got is not None and abs(fold(got - want)) <= 2.0
|
| 155 |
+
print(f" [{'PASS' if good else 'FAIL'}] lattice phi={phi:+.0f} deg -> "
|
| 156 |
+
f"{'None' if got is None else f'{got:+.2f}'} (want {want:+.1f})")
|
| 157 |
+
ok &= good
|
| 158 |
+
|
| 159 |
+
# 9 — carpet / lineless floor: speckle texture, no lattice — must abstain
|
| 160 |
+
# so the pipeline falls through to the wall-contact estimate
|
| 161 |
+
rng = np.random.default_rng(11)
|
| 162 |
+
_, floor = rotated_room(0.0, Hp)
|
| 163 |
+
carpet = np.clip(
|
| 164 |
+
180 + rng.normal(0, 6, (IMG_H, IMG_W, 3)), 0, 255
|
| 165 |
+
).astype(np.uint8)
|
| 166 |
+
got = estimate_floor_lattice_rotation(carpet, floor, Hp)
|
| 167 |
+
print(f" [{'PASS' if got is None else 'FAIL'}] carpet (speckle) -> {got}")
|
| 168 |
+
ok &= got is None
|
| 169 |
+
|
| 170 |
print("\n" + ("ALL R1-4 SIM CHECKS PASSED" if ok else "R1-4 SIM CHECKS FAILED"))
|
| 171 |
return 0 if ok else 1
|
| 172 |
|
verify_r4_intrinsic_sim.py
CHANGED
|
@@ -51,7 +51,7 @@ sys.modules["intrinsic.pipeline"] = _mod
|
|
| 51 |
# --- real implementations from app.py ----------------------------------------
|
| 52 |
src = open("app.py").read()
|
| 53 |
ns = {"np": np, "cv2": cv2, "intrinsic_models": object(), "device": "cpu"}
|
| 54 |
-
for fn in ["_adaptive_shade_range", "_encode_shade", "build_intrinsic_shade_map"]:
|
| 55 |
start = src.index(f"def {fn}")
|
| 56 |
end = src.index("\ndef ", start + 10)
|
| 57 |
exec(compile(src[start:end], "app.py", "exec"), ns)
|
|
@@ -150,7 +150,50 @@ def main():
|
|
| 150 |
print(" [FAIL] inv_shd: did not engage")
|
| 151 |
ok &= good
|
| 152 |
|
| 153 |
-
# 5 —
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
cases = []
|
| 155 |
_fake_results.clear()
|
| 156 |
_fake_results["albedo_only"] = shading.astype(np.float32)
|
|
|
|
| 51 |
# --- real implementations from app.py ----------------------------------------
|
| 52 |
src = open("app.py").read()
|
| 53 |
ns = {"np": np, "cv2": cv2, "intrinsic_models": object(), "device": "cpu"}
|
| 54 |
+
for fn in ["_adaptive_shade_range", "_encode_shade", "repair_intrinsic_floor_shading", "build_intrinsic_shade_map"]:
|
| 55 |
start = src.index(f"def {fn}")
|
| 56 |
end = src.index("\ndef ", start + 10)
|
| 57 |
exec(compile(src[start:end], "app.py", "exec"), ns)
|
|
|
|
| 150 |
print(" [FAIL] inv_shd: did not engage")
|
| 151 |
ok &= good
|
| 152 |
|
| 153 |
+
# 5 — R4-1 v2 glare repair: the model inverts specular glare into a dark
|
| 154 |
+
# blob (2026-06-12 dataset, room 2). Photo: bright glare patch on the
|
| 155 |
+
# floor; model: shading collapses there. The repaired output must sit at
|
| 156 |
+
# the ambient level, not the dip — while the REAL shadow (photo-dark,
|
| 157 |
+
# check 1) keeps transferring.
|
| 158 |
+
yy, xx = np.indices((H, W)).astype(np.float64)
|
| 159 |
+
glare_zone = ((xx - W * 0.3) ** 2 + ((yy - H * 0.75) * 1.4) ** 2) < 45.0 ** 2
|
| 160 |
+
img_g = img.copy()
|
| 161 |
+
img_g[glare_zone & (mask > 0)] = 250
|
| 162 |
+
inverted = shading.copy()
|
| 163 |
+
inverted[glare_zone & (mask > 0)] = 0.12
|
| 164 |
+
_fake_results.clear()
|
| 165 |
+
_fake_results["gry_shd"] = inverted.astype(np.float32)
|
| 166 |
+
enc_g, rng_g = build_intrinsic_shade_map(img_g, mask)
|
| 167 |
+
rel_g = decode(enc_g.reshape(H, W), rng_g)
|
| 168 |
+
core = glare_zone & interior
|
| 169 |
+
ring = (~glare_zone) & interior & (
|
| 170 |
+
((xx - W * 0.3) ** 2 + ((yy - H * 0.75) * 1.4) ** 2) < 90.0 ** 2
|
| 171 |
+
)
|
| 172 |
+
dip = float(rel_g[ring].mean()) - float(rel_g[core].mean())
|
| 173 |
+
good = dip < 0.06
|
| 174 |
+
print(f" [{'PASS' if good else 'FAIL'}] glare repair: blob dip {dip:.3f} "
|
| 175 |
+
f"below ambient (<0.06; was an inverted dark blob)")
|
| 176 |
+
ok &= good
|
| 177 |
+
|
| 178 |
+
# 6 — R4-1 v2 grout-ghost removal: thin dark lines in the model's
|
| 179 |
+
# shading (the OLD floor's grout grooves) must not reach the output;
|
| 180 |
+
# the wide soft shadow survives via check 1.
|
| 181 |
+
ghost = shading.copy()
|
| 182 |
+
line_mask = (mask > 0) & (((xx + 2 * yy) % 60) < 3)
|
| 183 |
+
ghost[line_mask] *= 0.72
|
| 184 |
+
_fake_results.clear()
|
| 185 |
+
_fake_results["gry_shd"] = ghost.astype(np.float32)
|
| 186 |
+
enc_l, rng_l = build_intrinsic_shade_map(img, mask)
|
| 187 |
+
rel_l = decode(enc_l.reshape(H, W), rng_l)
|
| 188 |
+
on_line = line_mask & sel
|
| 189 |
+
off_line = (~line_mask) & sel
|
| 190 |
+
leak = abs(float(rel_l[on_line].mean()) - float(rel_l[off_line].mean()))
|
| 191 |
+
good = leak < 0.02
|
| 192 |
+
print(f" [{'PASS' if good else 'FAIL'}] grout-ghost removal: line leakage "
|
| 193 |
+
f"{leak:.4f} (<0.02; lines were 28% deep)")
|
| 194 |
+
ok &= good
|
| 195 |
+
|
| 196 |
+
# 7 — fallback paths all return None (caller then uses the heuristic)
|
| 197 |
cases = []
|
| 198 |
_fake_results.clear()
|
| 199 |
_fake_results["albedo_only"] = shading.astype(np.float32)
|