GitHub Actions commited on
Commit
802aa1a
·
1 Parent(s): 75ac0a9

Deploy from GitHub commit 4f031b93b6f595c3a620a69758aac28b5a09767e

Browse files
Files changed (3) hide show
  1. app.py +148 -2
  2. verify_p1_sim.py +132 -0
  3. verify_rotation.py +138 -0
app.py CHANGED
@@ -373,6 +373,12 @@ def build_shade_map(
373
  except cv2.error:
374
  pass
375
 
 
 
 
 
 
 
376
  sigma = max(8.0, min(h, w) / 28.0)
377
  smooth = cv2.GaussianBlur(filled, (0, 0), sigmaX=sigma, sigmaY=sigma)
378
  relative = smooth / median_lum
@@ -557,6 +563,34 @@ def clean_floor_mask(mask: np.ndarray) -> np.ndarray:
557
  return (labels == largest).astype(np.uint8)
558
 
559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560
  def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> np.ndarray:
561
  reject_raw = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES)).astype(np.uint8)
562
  if dilation > 0:
@@ -800,7 +834,11 @@ def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray):
800
  dst_h = float(np.clip(dst_h, height * 0.8, height * 5.0))
801
 
802
  dst = np.float32([[x1, y2], [x2, y2], [x2, y2 - dst_h], [x1, y2 - dst_h]])
803
- homography = cv2.getPerspectiveTransform(src, dst).flatten().tolist()
 
 
 
 
804
  return homography, {
805
  "x": x1,
806
  "y": y2 - dst_h,
@@ -809,10 +847,101 @@ def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray):
809
  "quad": src.flatten().tolist(),
810
  "hullQuad": hull_quad_list, # B8
811
  "vanishingPoint": vanishing_point, # B6 primary
812
- "vanishingPoint2": vanishing_point2, # B6 secondary
 
813
  }
814
 
815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816
  # ---------------------------------------------------------------------------
817
  # B5 — Complement-Stamp Furniture
818
  # Use a single dilation pass (down from two) and restore the narrow contact
@@ -896,6 +1025,16 @@ def build_floor_surface_mask(
896
  surface = cv2.bitwise_or(surface, restore)
897
  surface[reject_dilated > 0] = 0
898
 
 
 
 
 
 
 
 
 
 
 
899
  return surface
900
 
901
 
@@ -1023,6 +1162,13 @@ def build_segmentation_bundle(contents: bytes):
1023
  floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8)
1024
  floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
1025
  floor_mask = clean_floor_mask(floor_mask)
 
 
 
 
 
 
 
1026
  print(f"[TIMING] Floor masking/cleanup took {time.perf_counter() - t0:.3f} seconds", flush=True)
1027
 
1028
  t0 = time.perf_counter()
 
373
  except cv2.error:
374
  pass
375
 
376
+ # P1-3 — median-filter before the Gaussian: the median removes small-scale
377
+ # floor PATTERN (grout lines, accent tiles, wood figuring) that would
378
+ # otherwise transfer onto the replacement as ghost shading, while the
379
+ # large lighting gradients survive untouched.
380
+ med_k = max(9, int(min(h, w) / 40)) | 1
381
+ filled = cv2.medianBlur(np.clip(filled, 0, 255).astype(np.uint8), med_k).astype(np.float32)
382
  sigma = max(8.0, min(h, w) / 28.0)
383
  smooth = cv2.GaussianBlur(filled, (0, 0), sigmaX=sigma, sigmaY=sigma)
384
  relative = smooth / median_lum
 
563
  return (labels == largest).astype(np.uint8)
564
 
565
 
566
+ def fill_enclosed_islands(
567
+ mask: np.ndarray, protect: np.ndarray | None, max_area: int
568
+ ) -> np.ndarray:
569
+ """P1-3 — absorb small fully-enclosed non-floor islands back into the floor.
570
+
571
+ Accent tiles, stains, and pattern features the segmenter labels as foreign
572
+ leave holes in the floor mask, and the original floor then ghosts through
573
+ the replacement (e.g. the blue accent tile). Real objects are protected via
574
+ the occluder/reject class masks; anything touching the image border is a
575
+ cut-off region, not an enclosed island, and is left alone.
576
+ """
577
+ h, w = mask.shape[:2]
578
+ inv = (mask == 0).astype(np.uint8)
579
+ count, labels, stats, _ = cv2.connectedComponentsWithStats(inv, connectivity=8)
580
+ out = mask.copy()
581
+ for comp_id in range(1, count):
582
+ x, y, cw, ch, area = stats[comp_id]
583
+ if area > max_area:
584
+ continue
585
+ if x == 0 or y == 0 or x + cw >= w or y + ch >= h:
586
+ continue
587
+ comp = labels == comp_id
588
+ if protect is not None and protect[comp].any():
589
+ continue
590
+ out[comp] = 1
591
+ return out
592
+
593
+
594
  def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> np.ndarray:
595
  reject_raw = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES)).astype(np.uint8)
596
  if dilation > 0:
 
834
  dst_h = float(np.clip(dst_h, height * 0.8, height * 5.0))
835
 
836
  dst = np.float32([[x1, y2], [x2, y2], [x2, y2 - dst_h], [x1, y2 - dst_h]])
837
+ H = cv2.getPerspectiveTransform(src, dst)
838
+ homography = H.flatten().tolist()
839
+
840
+ default_rotation = estimate_default_rotation(mask, H, vanishing_point2)
841
+
842
  return homography, {
843
  "x": x1,
844
  "y": y2 - dst_h,
 
847
  "quad": src.flatten().tolist(),
848
  "hullQuad": hull_quad_list, # B8
849
  "vanishingPoint": vanishing_point, # B6 primary
850
+ "vanishingPoint2": vanishing_point2, # B6 secondary — feeds rotation fallback
851
+ "defaultRotation": default_rotation, # P1-4 — align tile rows with the wall
852
  }
853
 
854
 
855
+ # ---------------------------------------------------------------------------
856
+ # P1-4 — Default Tile Rotation
857
+ # Tiles were laid along the plane's x-axis (= the image bbox axis), which is
858
+ # how the camera was held, not how a person lays tile. Sample the floor's top
859
+ # boundary (the floor↔wall line), map it through the homography into plane
860
+ # space, and fit a line: its angle is the rotation that makes tile rows run
861
+ # parallel to the back wall. When the boundary is too short to fit (heavily
862
+ # occluded back wall), fall back to the secondary vanishing point's direction
863
+ # mapped into plane space (B6's consumer).
864
+ # ---------------------------------------------------------------------------
865
+
866
+ def estimate_default_rotation(
867
+ mask: np.ndarray, H: np.ndarray, vanishing_point2: dict | None
868
+ ) -> float:
869
+ h, w = mask.shape[:2]
870
+
871
+ def _to_plane(img_pts: np.ndarray):
872
+ ones = np.ones((len(img_pts), 1), dtype=np.float64)
873
+ p = np.hstack([img_pts.astype(np.float64), ones]) @ H.T
874
+ zs = p[:, 2]
875
+ valid = np.abs(zs) > 1e-9
876
+ if valid.sum() < 2:
877
+ return None
878
+ return p[valid, 0] / zs[valid], p[valid, 1] / zs[valid]
879
+
880
+ def _plane_angle(img_pts: np.ndarray) -> float | None:
881
+ plane = _to_plane(img_pts)
882
+ if plane is None:
883
+ return None
884
+ px, py = plane
885
+ if px.max() - px.min() < 1e-6:
886
+ return None
887
+ slope = np.polyfit(px, py, 1)[0]
888
+ return float(np.degrees(np.arctan(slope)))
889
+
890
+ # Top boundary of the floor: topmost mask pixel per column, centre 60%.
891
+ pts = []
892
+ for x in range(int(w * 0.2), int(w * 0.8), 4):
893
+ col = np.where(mask[:, x] > 0)[0]
894
+ if len(col) > 10:
895
+ pts.append((float(x), float(col[0])))
896
+
897
+ if len(pts) >= 12:
898
+ plane = _to_plane(np.array(pts))
899
+ if plane is not None:
900
+ px, py = plane
901
+ full_span = px.max() - px.min()
902
+ keep = np.ones(len(px), dtype=bool)
903
+ angle = None
904
+ # Corridors and doorways put depth steps in the boundary that swing
905
+ # a single least-squares fit to a meaningless diagonal. Iteratively
906
+ # trim the worst residuals and only accept once the surviving points
907
+ # are genuinely collinear over a real fraction of the boundary.
908
+ for _ in range(3):
909
+ if keep.sum() < 12:
910
+ break
911
+ sub_x, sub_y = px[keep], py[keep]
912
+ span = sub_x.max() - sub_x.min()
913
+ if span < max(1e-6, full_span * 0.3):
914
+ break
915
+ slope, intercept = np.polyfit(sub_x, sub_y, 1)
916
+ resid = np.abs(py - (slope * px + intercept))
917
+ rms = float(np.sqrt(np.mean(resid[keep] ** 2)))
918
+ # Accept only while most points survive trimming: a clean back
919
+ # wall is one line and keeps nearly all of them, a fragmented
920
+ # boundary (corridor, doorways) needs heavy trimming to look
921
+ # straight and must not be trusted.
922
+ if rms < span * 0.04 and keep.sum() >= len(px) * 0.6:
923
+ angle = float(np.degrees(np.arctan(slope)))
924
+ break
925
+ keep &= resid <= np.percentile(resid[keep], 70)
926
+ # A near-saturated angle means the fit latched onto a side wall or
927
+ # doorway edge, not the back wall — reject rather than clamp.
928
+ if angle is not None and abs(angle) < 25.0:
929
+ return angle
930
+
931
+ # Fallback: direction toward the secondary VP defines the second wall axis.
932
+ if vanishing_point2 is not None:
933
+ cx, cy = w * 0.5, h * 0.75
934
+ toward = np.array([
935
+ [cx, cy],
936
+ [cx + (vanishing_point2["x"] - cx) * 0.25, cy + (vanishing_point2["y"] - cy) * 0.25],
937
+ ])
938
+ angle = _plane_angle(toward)
939
+ if angle is not None:
940
+ return float(np.clip(angle, -30.0, 30.0))
941
+
942
+ return 0.0
943
+
944
+
945
  # ---------------------------------------------------------------------------
946
  # B5 — Complement-Stamp Furniture
947
  # Use a single dilation pass (down from two) and restore the narrow contact
 
1025
  surface = cv2.bitwise_or(surface, restore)
1026
  surface[reject_dilated > 0] = 0
1027
 
1028
+ # P1-6 — the dilated reject band also ate a thin strip of true floor below
1029
+ # the skirting, letting the original floor peek out along the back wall.
1030
+ # Tiling is hard-clamped to floor_mask above, so it can never reach the
1031
+ # wall itself — reclaim the floor pixels the dilation removed (but never
1032
+ # raw reject or occluder pixels).
1033
+ reclaim = cv2.bitwise_and(floor_mask, cv2.bitwise_not(reject_mask))
1034
+ reclaim[occ_dilated > 0] = 0
1035
+ wall_band = cv2.bitwise_and(reclaim, reject_dilated)
1036
+ surface = cv2.bitwise_or(surface, wall_band)
1037
+
1038
  return surface
1039
 
1040
 
 
1162
  floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8)
1163
  floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
1164
  floor_mask = clean_floor_mask(floor_mask)
1165
+ # P1-3 — reclaim small enclosed islands (accent tiles, pattern features)
1166
+ # so the original floor can't ghost through; real objects stay protected.
1167
+ protect = (
1168
+ np.isin(seg_map, class_ids(OCCLUDER_CLASSES))
1169
+ | np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES))
1170
+ ).astype(np.uint8)
1171
+ floor_mask = fill_enclosed_islands(floor_mask, protect, max_area=int(w * h * 0.004))
1172
  print(f"[TIMING] Floor masking/cleanup took {time.perf_counter() - t0:.3f} seconds", flush=True)
1173
 
1174
  t0 = time.perf_counter()
verify_p1_sim.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ verify_p1_sim.py — scratch harness for P1-1 (fold-breaking) and P1-2
3
+ (highlight soft-clip). Renders a bundle with:
4
+ left = current production: mirror-repeat + hard clamp
5
+ right = P1: makeSeamless 4-tap blend + per-cell random flips + soft clip
6
+
7
+ Usage:
8
+ python verify_p1_sim.py /tmp/hf_new_bundle.json <tile> <out_prefix>
9
+ """
10
+
11
+ import base64
12
+ import io
13
+ import json
14
+ import sys
15
+
16
+ import numpy as np
17
+ from PIL import Image
18
+
19
+
20
+ def positive_modulo(v, d):
21
+ return ((v % d) + d) % d
22
+
23
+
24
+ def mirror_repeat(v):
25
+ f = positive_modulo(v, 2.0)
26
+ return np.where(f <= 1.0, f, 2.0 - f)
27
+
28
+
29
+ def make_seamless(tex):
30
+ h, w, _ = tex.shape
31
+ half_w, half_h = w // 2, h // 2
32
+
33
+ def win(n):
34
+ t = 1 - np.abs(2 * np.arange(n) / (n - 1) - 1)
35
+ return t * t * (3 - 2 * t)
36
+
37
+ wx = win(w)[None, :, None]
38
+ wy = win(h)[:, None, None]
39
+ t0 = tex.astype(np.float32)
40
+ t1 = np.roll(t0, -half_w, axis=1)
41
+ t2 = np.roll(t0, -half_h, axis=0)
42
+ t3 = np.roll(t1, -half_h, axis=0)
43
+ out = t0 * (wx * wy) + t1 * ((1 - wx) * wy) + t2 * (wx * (1 - wy)) + t3 * ((1 - wx) * (1 - wy))
44
+ return np.clip(out, 0, 255).astype(np.uint8)
45
+
46
+
47
+ def soft_clip(v, knee=220.0):
48
+ rng = 255.0 - knee
49
+ t = np.maximum(v - knee, 0.0)
50
+ return np.where(v <= knee, v, knee + t * rng / (t + rng))
51
+
52
+
53
+ def sample_bilinear(tex, x, y, wrap=True):
54
+ h, w, _ = tex.shape
55
+ x0 = np.clip(np.floor(x).astype(int), 0, w - 1)
56
+ y0 = np.clip(np.floor(y).astype(int), 0, h - 1)
57
+ if wrap:
58
+ x1, y1 = (x0 + 1) % w, (y0 + 1) % h
59
+ else:
60
+ x1, y1 = np.minimum(x0 + 1, w - 1), np.minimum(y0 + 1, h - 1)
61
+ fx = (x - np.floor(x))[:, None]
62
+ fy = (y - np.floor(y))[:, None]
63
+ t = tex.astype(np.float32)
64
+ return (t[y0, x0] * (1 - fx) * (1 - fy) + t[y0, x1] * fx * (1 - fy)
65
+ + t[y1, x0] * (1 - fx) * fy + t[y1, x1] * fx * fy)
66
+
67
+
68
+ def render(bundle, tex_raw, mode):
69
+ """mode 'mirror' = current prod; 'p1' = seamless + flips + softclip"""
70
+ w, h = bundle["width"], bundle["height"]
71
+ img = np.array(Image.open(io.BytesIO(base64.b64decode(bundle["pixels"]))).convert("RGB"))
72
+ seg = bundle["segments"][0]
73
+ idx = np.frombuffer(base64.b64decode(seg["mask"]), dtype=np.uint32)
74
+ H = np.array(seg["homography"], dtype=np.float64).reshape(3, 3)
75
+ p = seg["plane"]
76
+
77
+ tex = make_seamless(tex_raw) if mode == "p1" else tex_raw
78
+ texH, texW = tex.shape[:2]
79
+
80
+ ys, xs = idx // w, idx % w
81
+ pw = p["width"]
82
+ cx, cy = p["x"] + pw / 2, p["y"] + p["height"] / 2
83
+ repeat_w = max(32.0, pw * 0.18)
84
+ repeat_h = repeat_w * (texH / texW)
85
+
86
+ pts = np.column_stack([xs, ys, np.ones(len(xs))]) @ H.T
87
+ fx = pts[:, 0] / pts[:, 2]
88
+ fy = pts[:, 1] / pts[:, 2]
89
+ cu = (fx - cx) / repeat_w
90
+ cv = (fy - cy) / repeat_h
91
+
92
+ if mode == "mirror":
93
+ u = mirror_repeat(cu)
94
+ v = mirror_repeat(cv)
95
+ sample = sample_bilinear(tex, u * texW, v * texH, wrap=False)
96
+ else:
97
+ ci = np.floor(cu).astype(np.int64)
98
+ cj = np.floor(cv).astype(np.int64)
99
+ hsh = ((ci * 73856093) ^ (cj * 19349663)).astype(np.uint32)
100
+ u = cu - ci
101
+ v = cv - cj
102
+ u = np.where(hsh & 1, 1 - u, u)
103
+ v = np.where(hsh & 2, 1 - v, v)
104
+ sample = sample_bilinear(tex, u * texW, v * texH, wrap=True)
105
+
106
+ sr = seg.get("shadeRange") or [0.55, 1.35]
107
+ sm = np.frombuffer(base64.b64decode(seg["shadeMap"]), dtype=np.uint8)
108
+ shade = sr[0] + (sm[idx].astype(np.float32) / 255.0) * (sr[1] - sr[0])
109
+
110
+ lit = sample * shade[:, None]
111
+ lit = soft_clip(lit) if mode == "p1" else np.clip(lit, 0, 255)
112
+
113
+ out = img.copy()
114
+ out[ys, xs] = np.clip(lit, 0, 255).astype(np.uint8)
115
+ return out
116
+
117
+
118
+ def main():
119
+ bundle_path, tile_path, prefix = sys.argv[1], sys.argv[2], sys.argv[3]
120
+ with open(bundle_path) as f:
121
+ bundle = json.load(f)
122
+ tex = np.array(Image.open(tile_path).convert("RGB"))
123
+ print(f"tile: {tile_path} {tex.shape}")
124
+
125
+ a = render(bundle, tex, "mirror")
126
+ b = render(bundle, tex, "p1")
127
+ Image.fromarray(np.hstack([a, b])).save(f"verify_out/{prefix}_p1_compare.png")
128
+ print(f"saved verify_out/{prefix}_p1_compare.png (left=mirror/prod, right=P1)")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
verify_rotation.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ verify_rotation.py — scratch check for P1-4 default tile rotation.
3
+
4
+ Computes the wall-aligned rotation from a bundle (same algorithm as
5
+ estimate_default_rotation in app.py), then renders a brick grid with
6
+ rotation 0 (left) vs the computed rotation (right) using the exact frontend
7
+ rotation math, to confirm the sign and magnitude visually.
8
+
9
+ Usage:
10
+ python verify_rotation.py /tmp/hf_new_bundle.json
11
+ """
12
+
13
+ import base64
14
+ import io
15
+ import json
16
+ import sys
17
+
18
+ import numpy as np
19
+ from PIL import Image
20
+
21
+
22
+ def estimate_default_rotation(mask, H, vp2=None):
23
+ h, w = mask.shape[:2]
24
+
25
+ def _to_plane(img_pts):
26
+ ones = np.ones((len(img_pts), 1), dtype=np.float64)
27
+ p = np.hstack([img_pts.astype(np.float64), ones]) @ H.T
28
+ zs = p[:, 2]
29
+ valid = np.abs(zs) > 1e-9
30
+ if valid.sum() < 2:
31
+ return None
32
+ return p[valid, 0] / zs[valid], p[valid, 1] / zs[valid]
33
+
34
+ pts = []
35
+ for x in range(int(w * 0.2), int(w * 0.8), 4):
36
+ col = np.where(mask[:, x] > 0)[0]
37
+ if len(col) > 10:
38
+ pts.append((float(x), float(col[0])))
39
+
40
+ if len(pts) >= 12:
41
+ plane = _to_plane(np.array(pts))
42
+ if plane is not None:
43
+ px, py = plane
44
+ full_span = px.max() - px.min()
45
+ keep = np.ones(len(px), dtype=bool)
46
+ angle = None
47
+ for i in range(3):
48
+ if keep.sum() < 12:
49
+ break
50
+ sub_x, sub_y = px[keep], py[keep]
51
+ span = sub_x.max() - sub_x.min()
52
+ if span < max(1e-6, full_span * 0.3):
53
+ break
54
+ slope, intercept = np.polyfit(sub_x, sub_y, 1)
55
+ resid = np.abs(py - (slope * px + intercept))
56
+ rms = float(np.sqrt(np.mean(resid[keep] ** 2)))
57
+ print(f" pass {i}: n={keep.sum()} span={span:.0f} rms={rms:.1f} "
58
+ f"({rms / span:.3f} of span) angle={np.degrees(np.arctan(slope)):.1f}")
59
+ if rms < span * 0.04 and keep.sum() >= len(px) * 0.6:
60
+ angle = float(np.degrees(np.arctan(slope)))
61
+ break
62
+ keep &= resid <= np.percentile(resid[keep], 70)
63
+ if angle is not None and abs(angle) < 25.0:
64
+ return angle
65
+ return 0.0
66
+
67
+
68
+ def decode_pixels(bundle):
69
+ w, h = bundle["width"], bundle["height"]
70
+ raw = base64.b64decode(bundle["pixels"])
71
+ if len(raw) == w * h * 4:
72
+ return np.frombuffer(raw, np.uint8).reshape(h, w, 4)[:, :, :3].copy()
73
+ return np.array(Image.open(io.BytesIO(raw)).convert("RGB"))
74
+
75
+
76
+ def render(bundle, rotation_deg):
77
+ w, h = bundle["width"], bundle["height"]
78
+ img = decode_pixels(bundle)
79
+ seg = bundle["segments"][0]
80
+ idx = np.frombuffer(base64.b64decode(seg["mask"]), dtype=np.uint32)
81
+ H = np.array(seg["homography"], dtype=np.float64).reshape(3, 3)
82
+ p = seg["plane"]
83
+
84
+ ys, xs = idx // w, idx % w
85
+ pw, ph = p["width"], p["height"]
86
+ cx, cy = p["x"] + pw / 2, p["y"] + ph / 2
87
+ repeat = max(32.0, pw * 0.18)
88
+
89
+ pts = np.column_stack([xs, ys, np.ones(len(xs))]) @ H.T
90
+ fx = pts[:, 0] / pts[:, 2]
91
+ fy = pts[:, 1] / pts[:, 2]
92
+
93
+ # frontend rotation math: rad = rot*pi/180; cos(-rad), sin(-rad)
94
+ rad = rotation_deg * np.pi / 180.0
95
+ c, s = np.cos(-rad), np.sin(-rad)
96
+ dx, dy = fx - cx, fy - cy
97
+ rx = dx * c - dy * s
98
+ ry = dx * s + dy * c
99
+
100
+ u = rx / repeat
101
+ v = ry / repeat
102
+ row = np.floor(v).astype(int)
103
+ uu = u + (row % 2) * 0.5
104
+ cell = ((np.floor(uu).astype(int) + row) % 2).astype(bool)
105
+ fu, fv = uu - np.floor(uu), v - np.floor(v)
106
+ grout = (fu < 0.06) | (fv < 0.06)
107
+
108
+ color = np.where(cell[:, None], [184, 115, 51], [222, 184, 135]).astype(np.uint8)
109
+ color[grout] = (60, 60, 60)
110
+ out = img.copy()
111
+ out[ys, xs] = (0.75 * color + 0.25 * out[ys, xs]).astype(np.uint8)
112
+ return out
113
+
114
+
115
+ def main():
116
+ bundle_path = sys.argv[1]
117
+ with open(bundle_path) as f:
118
+ bundle = json.load(f)
119
+
120
+ w, h = bundle["width"], bundle["height"]
121
+ seg = bundle["segments"][0]
122
+ idx = np.frombuffer(base64.b64decode(seg["mask"]), dtype=np.uint32)
123
+ mask = np.zeros(h * w, np.uint8)
124
+ mask[idx] = 1
125
+ mask = mask.reshape(h, w)
126
+ H = np.array(seg["homography"], dtype=np.float64).reshape(3, 3)
127
+
128
+ rot = estimate_default_rotation(mask, H)
129
+ print(f"defaultRotation = {rot:.2f} deg")
130
+
131
+ a = render(bundle, 0.0)
132
+ b = render(bundle, rot)
133
+ Image.fromarray(np.hstack([a, b])).save("verify_out/rotation_compare.png")
134
+ print("saved verify_out/rotation_compare.png (left=rotation 0, right=defaultRotation)")
135
+
136
+
137
+ if __name__ == "__main__":
138
+ main()