github-actions[bot] commited on
Commit
bc8e40d
·
1 Parent(s): bcb16c3

Automated Deploy: 3713a7e9ad89464aae689cf59ee5eaa569edd23e

Browse files
Files changed (3) hide show
  1. app.py +39 -14
  2. floor_direction.py +607 -99
  3. test_floor_geometry.py +145 -9
app.py CHANGED
@@ -2867,7 +2867,21 @@ def build_segmentation_bundle(contents: bytes):
2867
  )
2868
 
2869
  t0 = time.perf_counter()
2870
- floor_direction = analyze_floor_direction_for_surface_mask(img_np, surface_mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2871
  print(
2872
  "[TIMING] Floor direction analysis took "
2873
  f"{time.perf_counter() - t0:.3f} seconds "
@@ -3318,13 +3332,14 @@ def encode_png_data_url(image_bgr: np.ndarray) -> str:
3318
  return f"data:image/png;base64,{payload}"
3319
 
3320
 
3321
- def floor_direction_response(result, segmentation) -> dict:
3322
  overlay_image_base64 = None
3323
  if result.overlay_bgr is not None:
3324
  overlay_image_base64 = encode_png_data_url(result.overlay_bgr)
3325
 
3326
  return {
3327
- "angle_degrees": result.angle_degrees,
 
3328
  "secondary_angle_degrees": result.secondary_angle_degrees,
3329
  "direction_label": result.direction_label,
3330
  "confidence": result.confidence,
@@ -3355,10 +3370,11 @@ def floor_direction_response(result, segmentation) -> dict:
3355
  }
3356
 
3357
 
3358
- def floor_direction_metadata(result, segmentation) -> dict:
3359
  return {
3360
  "source": "backend-floor-direction",
3361
- "angleDegrees": result.angle_degrees,
 
3362
  "secondaryAngleDegrees": result.secondary_angle_degrees,
3363
  "directionLabel": result.direction_label,
3364
  "confidence": result.confidence,
@@ -3376,10 +3392,15 @@ def floor_direction_metadata(result, segmentation) -> dict:
3376
  }
3377
 
3378
 
3379
- def analyze_floor_direction_for_surface_mask(
3380
- img_np: np.ndarray,
3381
- surface_mask: np.ndarray,
3382
- ) -> dict:
 
 
 
 
 
3383
  h, w = img_np.shape[:2]
3384
  polygons = mask_to_polygons(
3385
  surface_mask,
@@ -3393,11 +3414,15 @@ def analyze_floor_direction_for_surface_mask(
3393
  "height": int(h),
3394
  "polygons": polygons,
3395
  })
3396
- result = analyze_floor_direction_from_segmentation(
3397
- cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR),
3398
- floor_segmentation,
3399
- include_overlay=False,
3400
- )
 
 
 
 
3401
  return floor_direction_metadata(result, floor_segmentation)
3402
 
3403
 
 
2867
  )
2868
 
2869
  t0 = time.perf_counter()
2870
+ floor_direction_transform = (
2871
+ plane.get("floorTransform")
2872
+ if plane
2873
+ and plane.get("floorTransform")
2874
+ and float(plane.get("geometryConfidence") or 0.0) >= 0.35
2875
+ else homography
2876
+ )
2877
+ floor_direction = analyze_floor_direction_for_surface_mask(
2878
+ img_np,
2879
+ surface_mask,
2880
+ render_transform=floor_direction_transform,
2881
+ surface_uv=surface_mapping["uv"] if use_surface_uv else None,
2882
+ surface_indices=surface_indices if use_surface_uv else None,
2883
+ surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
2884
+ )
2885
  print(
2886
  "[TIMING] Floor direction analysis took "
2887
  f"{time.perf_counter() - t0:.3f} seconds "
 
3332
  return f"data:image/png;base64,{payload}"
3333
 
3334
 
3335
+ def floor_direction_response(result, segmentation) -> dict:
3336
  overlay_image_base64 = None
3337
  if result.overlay_bgr is not None:
3338
  overlay_image_base64 = encode_png_data_url(result.overlay_bgr)
3339
 
3340
  return {
3341
+ "angle_degrees": result.angle_degrees,
3342
+ "render_angle_degrees": result.render_angle_degrees,
3343
  "secondary_angle_degrees": result.secondary_angle_degrees,
3344
  "direction_label": result.direction_label,
3345
  "confidence": result.confidence,
 
3370
  }
3371
 
3372
 
3373
+ def floor_direction_metadata(result, segmentation) -> dict:
3374
  return {
3375
  "source": "backend-floor-direction",
3376
+ "angleDegrees": result.angle_degrees,
3377
+ "renderAngleDegrees": result.render_angle_degrees,
3378
  "secondaryAngleDegrees": result.secondary_angle_degrees,
3379
  "directionLabel": result.direction_label,
3380
  "confidence": result.confidence,
 
3392
  }
3393
 
3394
 
3395
+ def analyze_floor_direction_for_surface_mask(
3396
+ img_np: np.ndarray,
3397
+ surface_mask: np.ndarray,
3398
+ *,
3399
+ render_transform: list[float] | np.ndarray | None = None,
3400
+ surface_uv: np.ndarray | None = None,
3401
+ surface_indices: np.ndarray | None = None,
3402
+ surface_plane_ids: np.ndarray | None = None,
3403
+ ) -> dict:
3404
  h, w = img_np.shape[:2]
3405
  polygons = mask_to_polygons(
3406
  surface_mask,
 
3414
  "height": int(h),
3415
  "polygons": polygons,
3416
  })
3417
+ result = analyze_floor_direction_from_segmentation(
3418
+ cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR),
3419
+ floor_segmentation,
3420
+ include_overlay=False,
3421
+ render_transform=render_transform,
3422
+ surface_uv=surface_uv,
3423
+ surface_indices=surface_indices,
3424
+ surface_plane_ids=surface_plane_ids,
3425
+ )
3426
  return floor_direction_metadata(result, floor_segmentation)
3427
 
3428
 
floor_direction.py CHANGED
@@ -196,15 +196,25 @@ class DetectedLine:
196
 
197
 
198
  @dataclass(frozen=True)
199
- class TextureOrientation:
200
- angle_degrees: float
201
- confidence: float
202
- support: int
203
- concentration: float
204
-
205
-
206
- @dataclass(frozen=True)
207
- class DirectionResult:
 
 
 
 
 
 
 
 
 
 
208
  angle_degrees: float | None
209
  secondary_angle_degrees: float | None
210
  direction_label: str
@@ -213,17 +223,22 @@ class DirectionResult:
213
  line_count: int
214
  dominant_line_count: int
215
  grid_pattern_detected: bool
216
- dominant_lines: list[DetectedLine]
217
- warnings: list[str]
218
- overlay_bgr: np.ndarray | None = None
219
-
220
-
221
- def analyze_floor_direction(
222
- image_bgr: np.ndarray,
223
- segmentation: FloorSegmentation,
224
- *,
225
- include_overlay: bool = False,
226
- ) -> DirectionResult:
 
 
 
 
 
227
  height, width = image_bgr.shape[:2]
228
  warnings: list[str] = list(segmentation.warnings or [])
229
 
@@ -267,7 +282,7 @@ def analyze_floor_direction(
267
  inner_mask = mask
268
 
269
  lines = detect_candidate_lines(image_bgr, inner_mask)
270
- hough_orientation = dominant_orientation(lines)
271
  texture_orientation = estimate_texture_orientation(image_bgr, inner_mask)
272
  selected_orientation = select_orientation(hough_orientation, texture_orientation, warnings)
273
 
@@ -287,7 +302,23 @@ def analyze_floor_direction(
287
  overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None,
288
  )
289
 
290
- angle_degrees, orientation_source = selected_orientation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  dominant_lines: list[DetectedLine] = []
292
  peak_weight_ratio = 0.0
293
  concentration = 0.0
@@ -357,10 +388,11 @@ def analyze_floor_direction(
357
  line_count=len(lines),
358
  dominant_line_count=len(dominant_lines),
359
  grid_pattern_detected=grid_pattern_detected,
360
- dominant_lines=dominant_lines[:30],
361
- warnings=warnings,
362
- overlay_bgr=overlay,
363
- )
 
364
 
365
 
366
  def build_floor_mask(
@@ -441,29 +473,43 @@ def erode_mask(mask: np.ndarray) -> np.ndarray:
441
  return cv2.erode(mask, kernel, iterations=1)
442
 
443
 
444
- def detect_candidate_lines(image_bgr: np.ndarray, mask: np.ndarray) -> list[DetectedLine]:
445
- height, width = image_bgr.shape[:2]
446
- floor_pixels = max(1, int(np.count_nonzero(mask)))
447
- gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
448
 
449
  inside_pixels = gray[mask > 0]
450
  fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray))
451
  prepared = gray.copy()
452
  prepared[mask == 0] = fill_value
453
 
454
- clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
455
- enhanced = clahe.apply(prepared)
456
- blurred = cv2.GaussianBlur(enhanced, (5, 5), 0)
457
-
458
- min_dimension = min(width, height)
459
- min_line_length = max(28, int(min_dimension * 0.055))
460
- max_line_gap = max(8, int(min_dimension * 0.025))
461
- hough_threshold = max(18, int(math.sqrt(floor_pixels) * 0.035))
462
-
463
- attempts = [
464
- (50, 150, hough_threshold, min_line_length),
465
- (30, 100, max(12, int(hough_threshold * 0.75)), max(20, int(min_line_length * 0.8))),
466
- (80, 220, hough_threshold, min_line_length),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  ]
468
 
469
  best_lines: list[DetectedLine] = []
@@ -482,10 +528,102 @@ def detect_candidate_lines(image_bgr: np.ndarray, mask: np.ndarray) -> list[Dete
482
  lines = normalize_hough_lines(raw_lines, min_length=min_length)
483
  if len(lines) > len(best_lines):
484
  best_lines = lines
485
- if len(best_lines) >= 12:
486
- break
487
-
488
- return deduplicate_lines(best_lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489
 
490
 
491
  def normalize_hough_lines(raw_lines: np.ndarray | None, *, min_length: int) -> list[DetectedLine]:
@@ -532,63 +670,433 @@ def deduplicate_lines(lines: list[DetectedLine]) -> list[DetectedLine]:
532
  return unique[:200]
533
 
534
 
535
- def dominant_orientation(
536
- lines: list[DetectedLine],
537
- ) -> tuple[float, list[DetectedLine], float, float, float] | None:
538
- if not lines:
539
- return None
540
-
541
- angles = np.array([line.angle_degrees for line in lines], dtype=np.float64)
542
- weights = np.array([max(1.0, line.length) for line in lines], dtype=np.float64)
543
- total_weight = float(np.sum(weights))
544
- if total_weight <= 0:
545
- return None
546
-
547
- histogram = np.zeros(180, dtype=np.float64)
548
- for angle, weight in zip(angles, weights, strict=False):
549
- histogram[int(round(angle)) % 180] += weight
550
-
551
- kernel = np.array([1, 2, 3, 4, 3, 2, 1], dtype=np.float64)
552
- padded = np.concatenate([histogram[-3:], histogram, histogram[:3]])
553
- smoothed = np.convolve(padded, kernel / kernel.sum(), mode="valid")
554
- peak_angle = float(int(np.argmax(smoothed)) % 180)
555
-
556
- cluster_indices = [
557
- index
558
- for index, angle in enumerate(angles)
559
- if angular_distance_degrees(float(angle), peak_angle) <= 12.0
560
- ]
561
- if not cluster_indices:
562
- return None
563
-
564
- cluster_weights = weights[cluster_indices]
565
- cluster_angles = angles[cluster_indices]
566
- doubled_angles = np.deg2rad(cluster_angles * 2.0)
567
-
568
- vector_x = float(np.sum(np.cos(doubled_angles) * cluster_weights))
569
- vector_y = float(np.sum(np.sin(doubled_angles) * cluster_weights))
570
- dominant_angle = (math.degrees(math.atan2(vector_y, vector_x)) / 2.0) % 180.0
571
-
572
- cluster_weight = float(np.sum(cluster_weights))
573
- peak_weight_ratio = cluster_weight / total_weight
574
- concentration = math.hypot(vector_x, vector_y) / cluster_weight if cluster_weight else 0.0
575
-
576
- orthogonal_angle = (dominant_angle + 90.0) % 180.0
577
- orthogonal_weight = float(
578
- np.sum(
579
- [
580
  weight
581
  for angle, weight in zip(angles, weights, strict=False)
582
  if angular_distance_degrees(float(angle), orthogonal_angle) <= 12.0
583
  ]
584
  )
585
- )
586
- orthogonal_ratio = orthogonal_weight / cluster_weight if cluster_weight else 0.0
587
-
588
- dominant_lines = [lines[index] for index in cluster_indices]
589
- dominant_lines = sorted(dominant_lines, key=lambda item: item.length, reverse=True)
590
-
591
- return dominant_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
 
593
 
594
  def detect_secondary_grid_angle(
 
196
 
197
 
198
  @dataclass(frozen=True)
199
+ class TextureOrientation:
200
+ angle_degrees: float
201
+ confidence: float
202
+ support: int
203
+ concentration: float
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class LineFamilyCluster:
208
+ line_indices: list[int]
209
+ angle_degrees: float
210
+ weight: float
211
+ concentration: float
212
+ distinct_offset_count: int
213
+ score: float
214
+
215
+
216
+ @dataclass(frozen=True)
217
+ class DirectionResult:
218
  angle_degrees: float | None
219
  secondary_angle_degrees: float | None
220
  direction_label: str
 
223
  line_count: int
224
  dominant_line_count: int
225
  grid_pattern_detected: bool
226
+ dominant_lines: list[DetectedLine]
227
+ warnings: list[str]
228
+ overlay_bgr: np.ndarray | None = None
229
+ render_angle_degrees: float | None = None
230
+
231
+
232
+ def analyze_floor_direction(
233
+ image_bgr: np.ndarray,
234
+ segmentation: FloorSegmentation,
235
+ *,
236
+ include_overlay: bool = False,
237
+ render_transform: list[float] | np.ndarray | None = None,
238
+ surface_uv: np.ndarray | None = None,
239
+ surface_indices: np.ndarray | None = None,
240
+ surface_plane_ids: np.ndarray | None = None,
241
+ ) -> DirectionResult:
242
  height, width = image_bgr.shape[:2]
243
  warnings: list[str] = list(segmentation.warnings or [])
244
 
 
282
  inner_mask = mask
283
 
284
  lines = detect_candidate_lines(image_bgr, inner_mask)
285
+ hough_orientation = dominant_orientation(lines, image_shape=inner_mask.shape[:2])
286
  texture_orientation = estimate_texture_orientation(image_bgr, inner_mask)
287
  selected_orientation = select_orientation(hough_orientation, texture_orientation, warnings)
288
 
 
302
  overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None,
303
  )
304
 
305
+ angle_degrees, orientation_source = selected_orientation
306
+ render_angle_degrees = estimate_surface_uv_grout_rotation(
307
+ lines,
308
+ surface_uv=surface_uv,
309
+ surface_indices=surface_indices,
310
+ surface_plane_ids=surface_plane_ids,
311
+ image_shape=(height, width),
312
+ )
313
+ if render_angle_degrees is not None:
314
+ warnings.append("grout_direction_projected_to_surface_uv")
315
+ else:
316
+ render_angle_degrees = estimate_rectified_grout_rotation(
317
+ lines,
318
+ render_transform=render_transform,
319
+ )
320
+ if render_angle_degrees is not None:
321
+ warnings.append("grout_direction_rectified_for_renderer")
322
  dominant_lines: list[DetectedLine] = []
323
  peak_weight_ratio = 0.0
324
  concentration = 0.0
 
388
  line_count=len(lines),
389
  dominant_line_count=len(dominant_lines),
390
  grid_pattern_detected=grid_pattern_detected,
391
+ dominant_lines=dominant_lines[:30],
392
+ warnings=warnings,
393
+ overlay_bgr=overlay,
394
+ render_angle_degrees=render_angle_degrees,
395
+ )
396
 
397
 
398
  def build_floor_mask(
 
473
  return cv2.erode(mask, kernel, iterations=1)
474
 
475
 
476
+ def detect_candidate_lines(image_bgr: np.ndarray, mask: np.ndarray) -> list[DetectedLine]:
477
+ height, width = image_bgr.shape[:2]
478
+ floor_pixels = max(1, int(np.count_nonzero(mask)))
479
+ gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
480
 
481
  inside_pixels = gray[mask > 0]
482
  fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray))
483
  prepared = gray.copy()
484
  prepared[mask == 0] = fill_value
485
 
486
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
487
+ enhanced = clahe.apply(prepared)
488
+ blurred = cv2.GaussianBlur(enhanced, (5, 5), 0)
489
+
490
+ min_dimension = min(width, height)
491
+ min_line_length = max(28, int(min_dimension * 0.055))
492
+ max_line_gap = max(8, int(min_dimension * 0.025))
493
+ hough_threshold = max(18, int(math.sqrt(floor_pixels) * 0.035))
494
+
495
+ grout_edges = detect_grout_edges(enhanced, mask)
496
+ grout_lines = detect_hough_lines_from_edges(
497
+ grout_edges,
498
+ min_line_length=max(20, int(min_dimension * 0.045)),
499
+ max_line_gap=max(10, int(min_dimension * 0.03)),
500
+ thresholds=[
501
+ max(10, int(math.sqrt(floor_pixels) * 0.02)),
502
+ max(8, int(math.sqrt(floor_pixels) * 0.015)),
503
+ ],
504
+ )
505
+ grout_lines = deduplicate_lines(grout_lines)
506
+ if has_usable_grout_line_support(grout_lines, image_shape=(height, width)):
507
+ return grout_lines
508
+
509
+ attempts = [
510
+ (50, 150, hough_threshold, min_line_length),
511
+ (30, 100, max(12, int(hough_threshold * 0.75)), max(20, int(min_line_length * 0.8))),
512
+ (80, 220, hough_threshold, min_line_length),
513
  ]
514
 
515
  best_lines: list[DetectedLine] = []
 
528
  lines = normalize_hough_lines(raw_lines, min_length=min_length)
529
  if len(lines) > len(best_lines):
530
  best_lines = lines
531
+ if len(best_lines) >= 12:
532
+ break
533
+
534
+ return deduplicate_lines(best_lines)
535
+
536
+
537
+ def detect_grout_edges(enhanced_gray: np.ndarray, mask: np.ndarray) -> np.ndarray:
538
+ height, width = enhanced_gray.shape[:2]
539
+ min_dimension = min(width, height)
540
+ if min_dimension <= 0 or int(np.count_nonzero(mask)) < 100:
541
+ return np.zeros_like(enhanced_gray)
542
+
543
+ kernel_size = max(7, int(round(min_dimension * 0.018)))
544
+ if kernel_size % 2 == 0:
545
+ kernel_size += 1
546
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size))
547
+
548
+ dark_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_BLACKHAT, kernel)
549
+ light_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_TOPHAT, kernel)
550
+ response = cv2.max(dark_response, light_response)
551
+ response = cv2.GaussianBlur(response, (3, 3), 0)
552
+ response = cv2.bitwise_and(response, mask)
553
+
554
+ valid_response = response[mask > 0]
555
+ valid_response = valid_response[valid_response > 0]
556
+ if valid_response.size < 80:
557
+ return np.zeros_like(enhanced_gray)
558
+
559
+ percentile_threshold = float(np.percentile(valid_response, 84))
560
+ spread_threshold = float(np.mean(valid_response) + np.std(valid_response) * 0.35)
561
+ threshold = max(5.0, min(percentile_threshold, spread_threshold))
562
+
563
+ binary = np.zeros_like(response)
564
+ binary[response >= threshold] = 255
565
+ cleanup_kernel = np.ones((3, 3), dtype=np.uint8)
566
+ binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, cleanup_kernel)
567
+ binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cleanup_kernel)
568
+
569
+ low_threshold = max(3, int(round(threshold * 0.45)))
570
+ high_threshold = max(low_threshold + 3, int(round(threshold * 1.35)))
571
+ edges = cv2.Canny(response, low_threshold, high_threshold)
572
+ support = cv2.dilate(binary, cleanup_kernel, iterations=1)
573
+ edges = cv2.bitwise_and(edges, support)
574
+ return cv2.bitwise_and(edges, mask)
575
+
576
+
577
+ def detect_hough_lines_from_edges(
578
+ edges: np.ndarray,
579
+ *,
580
+ min_line_length: int,
581
+ max_line_gap: int,
582
+ thresholds: list[int],
583
+ ) -> list[DetectedLine]:
584
+ if int(np.count_nonzero(edges)) < max(24, min_line_length):
585
+ return []
586
+
587
+ best_lines: list[DetectedLine] = []
588
+ for threshold in thresholds:
589
+ raw_lines = cv2.HoughLinesP(
590
+ edges,
591
+ rho=1,
592
+ theta=np.pi / 180,
593
+ threshold=threshold,
594
+ minLineLength=min_line_length,
595
+ maxLineGap=max_line_gap,
596
+ )
597
+ lines = normalize_hough_lines(raw_lines, min_length=min_line_length)
598
+ if len(lines) > len(best_lines):
599
+ best_lines = lines
600
+
601
+ return best_lines
602
+
603
+
604
+ def has_usable_grout_line_support(
605
+ lines: list[DetectedLine],
606
+ *,
607
+ image_shape: tuple[int, int],
608
+ ) -> bool:
609
+ if len(lines) < 3:
610
+ return False
611
+
612
+ clusters = cluster_line_families(lines, image_shape=image_shape)
613
+ if not clusters:
614
+ return False
615
+
616
+ best_cluster = max(clusters, key=lambda cluster: cluster.score)
617
+ if best_cluster.concentration < 0.70:
618
+ return False
619
+
620
+ return (
621
+ len(best_cluster.line_indices) >= 4
622
+ and best_cluster.distinct_offset_count >= 2
623
+ ) or (
624
+ len(best_cluster.line_indices) >= 3
625
+ and best_cluster.distinct_offset_count >= 3
626
+ )
627
 
628
 
629
  def normalize_hough_lines(raw_lines: np.ndarray | None, *, min_length: int) -> list[DetectedLine]:
 
670
  return unique[:200]
671
 
672
 
673
+ def dominant_orientation(
674
+ lines: list[DetectedLine],
675
+ image_shape: tuple[int, int] | None = None,
676
+ ) -> tuple[float, list[DetectedLine], float, float, float] | None:
677
+ if not lines:
678
+ return None
679
+
680
+ angles = np.array([line.angle_degrees for line in lines], dtype=np.float64)
681
+ weights = np.array([max(1.0, line.length) for line in lines], dtype=np.float64)
682
+ total_weight = float(np.sum(weights))
683
+ if total_weight <= 0:
684
+ return None
685
+
686
+ clusters = cluster_line_families(lines, image_shape=image_shape)
687
+ if not clusters:
688
+ return None
689
+
690
+ dominant_cluster = max(clusters, key=lambda cluster: cluster.score)
691
+ dominant_angle = dominant_cluster.angle_degrees
692
+ peak_weight_ratio = dominant_cluster.weight / total_weight
693
+ concentration = dominant_cluster.concentration
694
+
695
+ orthogonal_angle = (dominant_angle + 90.0) % 180.0
696
+ orthogonal_weight = float(
697
+ np.sum(
698
+ [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699
  weight
700
  for angle, weight in zip(angles, weights, strict=False)
701
  if angular_distance_degrees(float(angle), orthogonal_angle) <= 12.0
702
  ]
703
  )
704
+ )
705
+ orthogonal_ratio = orthogonal_weight / dominant_cluster.weight if dominant_cluster.weight else 0.0
706
+
707
+ dominant_lines = [lines[index] for index in dominant_cluster.line_indices]
708
+ dominant_lines = sorted(dominant_lines, key=lambda item: item.length, reverse=True)
709
+
710
+ return dominant_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio
711
+
712
+
713
+ def estimate_rectified_grout_rotation(
714
+ lines: list[DetectedLine],
715
+ *,
716
+ render_transform: list[float] | np.ndarray | None,
717
+ ) -> float | None:
718
+ """Return a cardinal tile rotation in the renderer's floor-plane coordinates."""
719
+ transform = normalize_render_transform(render_transform)
720
+ if transform is None or len(lines) < 4:
721
+ return None
722
+
723
+ rectified_lines = transform_detected_lines(lines, transform)
724
+ orientation = dominant_orientation(rectified_lines)
725
+ if orientation is None:
726
+ return None
727
+
728
+ angle_degrees, dominant_lines, _peak_weight_ratio, concentration, _orthogonal_ratio = orientation
729
+ if len(dominant_lines) < 4 or concentration < 0.76:
730
+ return None
731
+
732
+ return snap_to_tile_axis(angle_degrees)
733
+
734
+
735
+ def estimate_surface_uv_grout_rotation(
736
+ lines: list[DetectedLine],
737
+ *,
738
+ surface_uv: np.ndarray | None,
739
+ surface_indices: np.ndarray | None,
740
+ surface_plane_ids: np.ndarray | None,
741
+ image_shape: tuple[int, int],
742
+ ) -> float | None:
743
+ """Measure original-image grout directly in the UV space used by the renderer."""
744
+ uv_grid, plane_grid = build_surface_uv_grids(
745
+ surface_uv=surface_uv,
746
+ surface_indices=surface_indices,
747
+ surface_plane_ids=surface_plane_ids,
748
+ image_shape=image_shape,
749
+ )
750
+ if uv_grid is None or len(lines) < 4:
751
+ return None
752
+
753
+ uv_lines = project_lines_to_surface_uv(lines, uv_grid, plane_grid)
754
+ orientation = dominant_orientation(uv_lines)
755
+ if orientation is None:
756
+ return None
757
+
758
+ angle_degrees, dominant_lines, _peak_weight_ratio, concentration, _orthogonal_ratio = orientation
759
+ if len(dominant_lines) < 4 or concentration < 0.76:
760
+ return None
761
+ return angle_degrees
762
+
763
+
764
+ def build_surface_uv_grids(
765
+ *,
766
+ surface_uv: np.ndarray | None,
767
+ surface_indices: np.ndarray | None,
768
+ surface_plane_ids: np.ndarray | None,
769
+ image_shape: tuple[int, int],
770
+ ) -> tuple[np.ndarray | None, np.ndarray | None]:
771
+ if surface_uv is None or surface_indices is None:
772
+ return None, None
773
+
774
+ height, width = image_shape
775
+ uv_values = np.asarray(surface_uv, dtype=np.float32)
776
+ indices = np.asarray(surface_indices, dtype=np.int64).reshape(-1)
777
+ if uv_values.ndim != 2 or uv_values.shape[1] != 2 or len(uv_values) != len(indices):
778
+ return None, None
779
+ if not len(indices) or np.any(indices < 0) or np.any(indices >= height * width):
780
+ return None, None
781
+
782
+ uv_grid = np.full((height * width, 2), np.nan, dtype=np.float32)
783
+ uv_grid[indices] = uv_values
784
+ uv_grid = uv_grid.reshape(height, width, 2)
785
+
786
+ plane_grid = None
787
+ if surface_plane_ids is not None:
788
+ plane_ids = np.asarray(surface_plane_ids, dtype=np.uint8).reshape(-1)
789
+ if len(plane_ids) == len(indices):
790
+ plane_grid = np.full(height * width, 255, dtype=np.uint8)
791
+ plane_grid[indices] = plane_ids
792
+ plane_grid = plane_grid.reshape(height, width)
793
+
794
+ return uv_grid, plane_grid
795
+
796
+
797
+ def project_lines_to_surface_uv(
798
+ lines: list[DetectedLine],
799
+ uv_grid: np.ndarray,
800
+ plane_grid: np.ndarray | None,
801
+ ) -> list[DetectedLine]:
802
+ height, width = uv_grid.shape[:2]
803
+ projected_lines: list[DetectedLine] = []
804
+
805
+ for line in lines:
806
+ sample_count = int(np.clip(round(line.length / 8.0) + 1, 9, 64))
807
+ fractions = np.linspace(0.0, 1.0, sample_count, dtype=np.float32)
808
+ xs = np.clip(
809
+ np.rint(line.x1 + (line.x2 - line.x1) * fractions).astype(np.int32),
810
+ 0,
811
+ width - 1,
812
+ )
813
+ ys = np.clip(
814
+ np.rint(line.y1 + (line.y2 - line.y1) * fractions).astype(np.int32),
815
+ 0,
816
+ height - 1,
817
+ )
818
+ points = uv_grid[ys, xs]
819
+ valid = np.isfinite(points).all(axis=1)
820
+
821
+ if plane_grid is not None:
822
+ sampled_planes = plane_grid[ys, xs]
823
+ valid_planes = sampled_planes[valid & (sampled_planes != 255)]
824
+ if valid_planes.size:
825
+ dominant_plane = int(np.bincount(valid_planes).argmax())
826
+ valid &= sampled_planes == dominant_plane
827
+
828
+ if int(valid.sum()) < max(6, int(math.ceil(sample_count * 0.55))):
829
+ continue
830
+
831
+ sampled_points = points[valid].astype(np.float64)
832
+ center = np.mean(sampled_points, axis=0)
833
+ _unused, _singular_values, basis = np.linalg.svd(sampled_points - center, full_matrices=False)
834
+ direction = basis[0]
835
+ distances = (sampled_points - center) @ direction
836
+ start = center + direction * float(np.min(distances))
837
+ end = center + direction * float(np.max(distances))
838
+ dx = float(end[0] - start[0])
839
+ dy = float(end[1] - start[1])
840
+ length = math.hypot(dx, dy)
841
+ if length <= 1e-5:
842
+ continue
843
+
844
+ projected_lines.append(
845
+ DetectedLine(
846
+ x1=float(start[0]),
847
+ y1=float(start[1]),
848
+ x2=float(end[0]),
849
+ y2=float(end[1]),
850
+ angle_degrees=normalized_line_angle(dx, dy),
851
+ length=length,
852
+ )
853
+ )
854
+
855
+ return projected_lines
856
+
857
+
858
+ def normalize_render_transform(
859
+ value: list[float] | np.ndarray | None,
860
+ ) -> np.ndarray | None:
861
+ if value is None:
862
+ return None
863
+
864
+ transform = np.asarray(value, dtype=np.float64)
865
+ if transform.size != 9:
866
+ return None
867
+ transform = transform.reshape(3, 3)
868
+ if not np.isfinite(transform).all() or abs(float(np.linalg.det(transform))) < 1e-10:
869
+ return None
870
+ return transform.astype(np.float32)
871
+
872
+
873
+ def transform_detected_lines(
874
+ lines: list[DetectedLine],
875
+ transform: np.ndarray,
876
+ ) -> list[DetectedLine]:
877
+ rectified_lines: list[DetectedLine] = []
878
+ for line in lines:
879
+ source_points = np.array([[[line.x1, line.y1], [line.x2, line.y2]]], dtype=np.float32)
880
+ mapped_points = cv2.perspectiveTransform(source_points, transform)[0]
881
+ if not np.isfinite(mapped_points).all():
882
+ continue
883
+
884
+ start, end = mapped_points
885
+ dx = float(end[0] - start[0])
886
+ dy = float(end[1] - start[1])
887
+ length = math.hypot(dx, dy)
888
+ if length <= 1e-5:
889
+ continue
890
+
891
+ rectified_lines.append(
892
+ DetectedLine(
893
+ x1=float(start[0]),
894
+ y1=float(start[1]),
895
+ x2=float(end[0]),
896
+ y2=float(end[1]),
897
+ angle_degrees=normalized_line_angle(dx, dy),
898
+ length=length,
899
+ )
900
+ )
901
+
902
+ return rectified_lines
903
+
904
+
905
+ def snap_to_tile_axis(angle_degrees: float) -> float | None:
906
+ normalized_angle = angle_degrees % 180.0
907
+ nearest_axis = 0.0 if angular_distance_degrees(normalized_angle, 0.0) <= 45.0 else 90.0
908
+ if angular_distance_degrees(normalized_angle, nearest_axis) > 28.0:
909
+ return None
910
+ return nearest_axis
911
+
912
+
913
+ def cluster_line_families(
914
+ lines: list[DetectedLine],
915
+ *,
916
+ image_shape: tuple[int, int] | None = None,
917
+ ) -> list[LineFamilyCluster]:
918
+ raw_clusters: list[list[int]] = []
919
+
920
+ for line_index in sorted(range(len(lines)), key=lambda index: lines[index].length, reverse=True):
921
+ line_angle = lines[line_index].angle_degrees
922
+ best_cluster_index = None
923
+ best_distance = float("inf")
924
+
925
+ for cluster_index, cluster_indices in enumerate(raw_clusters):
926
+ cluster_angle, _concentration, _weight = line_family_stats(lines, cluster_indices)
927
+ distance = angular_distance_degrees(line_angle, cluster_angle)
928
+ if distance <= 10.0 and distance < best_distance:
929
+ best_cluster_index = cluster_index
930
+ best_distance = distance
931
+
932
+ if best_cluster_index is None:
933
+ raw_clusters.append([line_index])
934
+ else:
935
+ raw_clusters[best_cluster_index].append(line_index)
936
+
937
+ raw_clusters = merge_nearby_line_family_clusters(lines, raw_clusters)
938
+ return [
939
+ build_line_family_cluster(lines, cluster_indices, image_shape=image_shape)
940
+ for cluster_indices in raw_clusters
941
+ if cluster_indices
942
+ ]
943
+
944
+
945
+ def merge_nearby_line_family_clusters(
946
+ lines: list[DetectedLine],
947
+ raw_clusters: list[list[int]],
948
+ ) -> list[list[int]]:
949
+ merged_clusters = [list(cluster) for cluster in raw_clusters]
950
+ changed = True
951
+
952
+ while changed and len(merged_clusters) > 1:
953
+ changed = False
954
+ for first_index in range(len(merged_clusters)):
955
+ first_angle, _first_concentration, _first_weight = line_family_stats(
956
+ lines,
957
+ merged_clusters[first_index],
958
+ )
959
+ for second_index in range(first_index + 1, len(merged_clusters)):
960
+ second_angle, _second_concentration, _second_weight = line_family_stats(
961
+ lines,
962
+ merged_clusters[second_index],
963
+ )
964
+ if angular_distance_degrees(first_angle, second_angle) > 8.0:
965
+ continue
966
+
967
+ merged_clusters[first_index].extend(merged_clusters[second_index])
968
+ del merged_clusters[second_index]
969
+ changed = True
970
+ break
971
+ if changed:
972
+ break
973
+
974
+ return merged_clusters
975
+
976
+
977
+ def build_line_family_cluster(
978
+ lines: list[DetectedLine],
979
+ line_indices: list[int],
980
+ *,
981
+ image_shape: tuple[int, int] | None = None,
982
+ ) -> LineFamilyCluster:
983
+ angle, concentration, weight = line_family_stats(lines, line_indices)
984
+ distinct_offset_count = count_distinct_line_offsets(
985
+ lines,
986
+ line_indices,
987
+ angle_degrees=angle,
988
+ image_shape=image_shape,
989
+ )
990
+ score = line_family_selection_score(
991
+ weight=weight,
992
+ concentration=concentration,
993
+ line_count=len(line_indices),
994
+ distinct_offset_count=distinct_offset_count,
995
+ )
996
+ return LineFamilyCluster(
997
+ line_indices=list(line_indices),
998
+ angle_degrees=angle,
999
+ weight=weight,
1000
+ concentration=concentration,
1001
+ distinct_offset_count=distinct_offset_count,
1002
+ score=score,
1003
+ )
1004
+
1005
+
1006
+ def line_family_stats(
1007
+ lines: list[DetectedLine],
1008
+ line_indices: list[int],
1009
+ ) -> tuple[float, float, float]:
1010
+ angles = np.array([lines[index].angle_degrees for index in line_indices], dtype=np.float64)
1011
+ weights = np.array([max(1.0, lines[index].length) for index in line_indices], dtype=np.float64)
1012
+ total_weight = float(np.sum(weights))
1013
+ if total_weight <= 0.0:
1014
+ return 0.0, 0.0, 0.0
1015
+
1016
+ angle, concentration = circular_mean_with_concentration(angles, weights)
1017
+ return angle, concentration, total_weight
1018
+
1019
+
1020
+ def count_distinct_line_offsets(
1021
+ lines: list[DetectedLine],
1022
+ line_indices: list[int],
1023
+ *,
1024
+ angle_degrees: float,
1025
+ image_shape: tuple[int, int] | None = None,
1026
+ ) -> int:
1027
+ if not line_indices:
1028
+ return 0
1029
+
1030
+ center_x, center_y, min_dimension = hough_offset_reference_frame(
1031
+ lines,
1032
+ line_indices,
1033
+ image_shape=image_shape,
1034
+ )
1035
+ tolerance = max(6.0, min_dimension * 0.018)
1036
+ radians = math.radians(angle_degrees)
1037
+ normal_x = -math.sin(radians)
1038
+ normal_y = math.cos(radians)
1039
+
1040
+ offsets = []
1041
+ for index in line_indices:
1042
+ line = lines[index]
1043
+ midpoint_x = (line.x1 + line.x2) * 0.5
1044
+ midpoint_y = (line.y1 + line.y2) * 0.5
1045
+ rho = (midpoint_x - center_x) * normal_x + (midpoint_y - center_y) * normal_y
1046
+ offsets.append((rho, max(1.0, line.length)))
1047
+
1048
+ offset_groups: list[list[float]] = []
1049
+ for rho, weight in sorted(offsets, key=lambda item: item[0]):
1050
+ if not offset_groups or abs(rho - offset_groups[-1][0]) > tolerance:
1051
+ offset_groups.append([rho, weight])
1052
+ continue
1053
+
1054
+ previous_rho, previous_weight = offset_groups[-1]
1055
+ combined_weight = previous_weight + weight
1056
+ offset_groups[-1][0] = (previous_rho * previous_weight + rho * weight) / combined_weight
1057
+ offset_groups[-1][1] = combined_weight
1058
+
1059
+ return len(offset_groups)
1060
+
1061
+
1062
+ def hough_offset_reference_frame(
1063
+ lines: list[DetectedLine],
1064
+ line_indices: list[int],
1065
+ *,
1066
+ image_shape: tuple[int, int] | None = None,
1067
+ ) -> tuple[float, float, float]:
1068
+ if image_shape is not None:
1069
+ height, width = image_shape
1070
+ min_dimension = max(1.0, float(min(width, height)))
1071
+ return (width - 1) * 0.5, (height - 1) * 0.5, min_dimension
1072
+
1073
+ xs: list[float] = []
1074
+ ys: list[float] = []
1075
+ for index in line_indices:
1076
+ line = lines[index]
1077
+ xs.extend([float(line.x1), float(line.x2)])
1078
+ ys.extend([float(line.y1), float(line.y2)])
1079
+
1080
+ min_x = min(xs) if xs else 0.0
1081
+ max_x = max(xs) if xs else 1.0
1082
+ min_y = min(ys) if ys else 0.0
1083
+ max_y = max(ys) if ys else 1.0
1084
+ width = max(1.0, max_x - min_x)
1085
+ height = max(1.0, max_y - min_y)
1086
+ return min_x + width * 0.5, min_y + height * 0.5, min(width, height)
1087
+
1088
+
1089
+ def line_family_selection_score(
1090
+ *,
1091
+ weight: float,
1092
+ concentration: float,
1093
+ line_count: int,
1094
+ distinct_offset_count: int,
1095
+ ) -> float:
1096
+ distinct_bonus = min(6, max(0, distinct_offset_count - 1))
1097
+ line_bonus = min(8, max(0, line_count - 1))
1098
+ repeated_line_multiplier = 1.0 + 0.18 * distinct_bonus + 0.05 * line_bonus
1099
+ return weight * max(0.35, concentration) * repeated_line_multiplier
1100
 
1101
 
1102
  def detect_secondary_grid_angle(
test_floor_geometry.py CHANGED
@@ -1,13 +1,15 @@
1
  import unittest
2
  import io
3
- import tempfile
4
- from pathlib import Path
5
-
6
- import numpy as np
7
- from PIL import Image
8
- from fastapi.testclient import TestClient
9
-
10
- import app
 
 
11
 
12
 
13
  class MetricFloorGeometryTests(unittest.TestCase):
@@ -550,6 +552,135 @@ class MetricFloorGeometryTests(unittest.TestCase):
550
  self.assertGreater(payload["line_count"], 0)
551
  self.assertTrue(payload["overlay_image_base64"].startswith("data:image/png;base64,"))
552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  def test_floor_direction_parser_does_not_use_non_floor_segment(self):
554
  payload = {
555
  "width": 120,
@@ -581,10 +712,15 @@ class MetricFloorGeometryTests(unittest.TestCase):
581
  image[y:y + 2, 20:width - 20] = 70
582
  surface_mask = np.ones((height, width), dtype=np.uint8)
583
 
584
- metadata = app.analyze_floor_direction_for_surface_mask(image, surface_mask)
 
 
 
 
585
 
586
  self.assertEqual(metadata["source"], "backend-floor-direction")
587
  self.assertIsNotNone(metadata["angleDegrees"])
 
588
  self.assertEqual(metadata["directionLabel"], "left_to_right")
589
  self.assertGreater(metadata["lineCount"], 0)
590
  self.assertEqual(metadata["segmentation"]["label"], "floor")
 
1
  import unittest
2
  import io
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from PIL import Image
9
+ from fastapi.testclient import TestClient
10
+
11
+ import app
12
+ import floor_direction
13
 
14
 
15
  class MetricFloorGeometryTests(unittest.TestCase):
 
552
  self.assertGreater(payload["line_count"], 0)
553
  self.assertTrue(payload["overlay_image_base64"].startswith("data:image/png;base64,"))
554
 
555
+ def test_floor_direction_prefers_repeated_grout_family_over_single_long_line(self):
556
+ lines = [
557
+ floor_direction.DetectedLine(30, 80, 110, 80, 0.0, 80.0),
558
+ floor_direction.DetectedLine(30, 140, 110, 140, 0.0, 80.0),
559
+ floor_direction.DetectedLine(30, 200, 110, 200, 0.0, 80.0),
560
+ floor_direction.DetectedLine(30, 260, 110, 260, 0.0, 80.0),
561
+ floor_direction.DetectedLine(310, 20, 310, 380, 90.0, 360.0),
562
+ ]
563
+
564
+ orientation = floor_direction.dominant_orientation(lines, image_shape=(420, 360))
565
+
566
+ self.assertIsNotNone(orientation)
567
+ angle_degrees, dominant_lines, _peak_weight_ratio, _concentration, orthogonal_ratio = orientation
568
+ self.assertLess(floor_direction.angular_distance_degrees(angle_degrees, 0.0), 1.0)
569
+ self.assertEqual(len(dominant_lines), 4)
570
+ self.assertGreater(orthogonal_ratio, 1.0)
571
+
572
+ def test_floor_direction_uses_original_image_grout_lines(self):
573
+ height, width = 220, 300
574
+ image_bgr = np.full((height, width, 3), 190, dtype=np.uint8)
575
+ grout_angle = 12.0
576
+ slope = np.tan(np.deg2rad(grout_angle))
577
+
578
+ for y in range(34, height - 32, 34):
579
+ start = (20, y)
580
+ end = (width - 24, int(round(y + (width - 44) * slope)))
581
+ cv2.line(image_bgr, start, end, (58, 58, 58), 2, cv2.LINE_AA)
582
+
583
+ cv2.line(image_bgr, (252, 18), (252, height - 18), (42, 42, 42), 5, cv2.LINE_AA)
584
+
585
+ segmentation = floor_direction.FloorSegmentation(
586
+ label="floor",
587
+ confidence=1.0,
588
+ polygons=[
589
+ floor_direction.FloorPolygon(
590
+ points=[(0, 0), (width - 1, 0), (width - 1, height - 1), (0, height - 1)]
591
+ )
592
+ ],
593
+ source_width=width,
594
+ source_height=height,
595
+ )
596
+
597
+ result = floor_direction.analyze_floor_direction(image_bgr, segmentation)
598
+
599
+ self.assertIsNotNone(result.angle_degrees)
600
+ self.assertLess(
601
+ floor_direction.angular_distance_degrees(result.angle_degrees or 0.0, grout_angle),
602
+ 5.0,
603
+ )
604
+ self.assertGreaterEqual(result.dominant_line_count, 4)
605
+
606
+ def test_rectified_grout_rotation_snaps_to_the_tile_axes(self):
607
+ lines = [
608
+ floor_direction.DetectedLine(20, 30, 180, 30, 0.0, 160.0),
609
+ floor_direction.DetectedLine(20, 70, 180, 70, 0.0, 160.0),
610
+ floor_direction.DetectedLine(20, 110, 180, 110, 0.0, 160.0),
611
+ floor_direction.DetectedLine(20, 150, 180, 150, 0.0, 160.0),
612
+ ]
613
+ rotation_degrees = 14.0
614
+ radians = np.deg2rad(rotation_degrees)
615
+ render_transform = [
616
+ np.cos(radians), -np.sin(radians), 0.0,
617
+ np.sin(radians), np.cos(radians), 0.0,
618
+ 0.0, 0.0, 1.0,
619
+ ]
620
+
621
+ render_rotation = floor_direction.estimate_rectified_grout_rotation(
622
+ lines,
623
+ render_transform=render_transform,
624
+ )
625
+
626
+ self.assertEqual(render_rotation, 0.0)
627
+
628
+ def test_surface_uv_grout_rotation_uses_renderer_coordinates(self):
629
+ height, width = 180, 240
630
+ lines = [
631
+ floor_direction.DetectedLine(20, 30, 220, 30, 0.0, 200.0),
632
+ floor_direction.DetectedLine(20, 65, 220, 65, 0.0, 200.0),
633
+ floor_direction.DetectedLine(20, 100, 220, 100, 0.0, 200.0),
634
+ floor_direction.DetectedLine(20, 135, 220, 135, 0.0, 200.0),
635
+ ]
636
+ yy, xx = np.mgrid[0:height, 0:width]
637
+ angle_radians = np.deg2rad(23.0)
638
+ surface_uv = np.column_stack((
639
+ xx.ravel() * np.cos(angle_radians) - yy.ravel() * np.sin(angle_radians),
640
+ xx.ravel() * np.sin(angle_radians) + yy.ravel() * np.cos(angle_radians),
641
+ )).astype(np.float32)
642
+ surface_indices = np.arange(height * width, dtype=np.uint32)
643
+ surface_plane_ids = np.zeros(height * width, dtype=np.uint8)
644
+
645
+ render_rotation = floor_direction.estimate_surface_uv_grout_rotation(
646
+ lines,
647
+ surface_uv=surface_uv,
648
+ surface_indices=surface_indices,
649
+ surface_plane_ids=surface_plane_ids,
650
+ image_shape=(height, width),
651
+ )
652
+
653
+ self.assertIsNotNone(render_rotation)
654
+ self.assertLess(floor_direction.angular_distance_degrees(render_rotation or 0.0, 23.0), 1.0)
655
+
656
+ def test_floor_direction_metadata_prefers_surface_uv_rotation(self):
657
+ height, width = 180, 240
658
+ image = np.full((height, width, 3), 225, dtype=np.uint8)
659
+ for y in range(30, height - 20, 30):
660
+ image[y:y + 2, 20:width - 20] = 65
661
+ yy, xx = np.mgrid[0:height, 0:width]
662
+ angle_radians = np.deg2rad(23.0)
663
+ surface_uv = np.column_stack((
664
+ xx.ravel() * np.cos(angle_radians) - yy.ravel() * np.sin(angle_radians),
665
+ xx.ravel() * np.sin(angle_radians) + yy.ravel() * np.cos(angle_radians),
666
+ )).astype(np.float32)
667
+ surface_indices = np.arange(height * width, dtype=np.uint32)
668
+ surface_plane_ids = np.zeros(height * width, dtype=np.uint8)
669
+
670
+ metadata = app.analyze_floor_direction_for_surface_mask(
671
+ image,
672
+ np.ones((height, width), dtype=np.uint8),
673
+ surface_uv=surface_uv,
674
+ surface_indices=surface_indices,
675
+ surface_plane_ids=surface_plane_ids,
676
+ )
677
+
678
+ self.assertLess(
679
+ floor_direction.angular_distance_degrees(metadata["renderAngleDegrees"] or 0.0, 23.0),
680
+ 1.0,
681
+ )
682
+ self.assertIn("grout_direction_projected_to_surface_uv", metadata["warnings"])
683
+
684
  def test_floor_direction_parser_does_not_use_non_floor_segment(self):
685
  payload = {
686
  "width": 120,
 
712
  image[y:y + 2, 20:width - 20] = 70
713
  surface_mask = np.ones((height, width), dtype=np.uint8)
714
 
715
+ metadata = app.analyze_floor_direction_for_surface_mask(
716
+ image,
717
+ surface_mask,
718
+ render_transform=[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
719
+ )
720
 
721
  self.assertEqual(metadata["source"], "backend-floor-direction")
722
  self.assertIsNotNone(metadata["angleDegrees"])
723
+ self.assertEqual(metadata["renderAngleDegrees"], 0.0)
724
  self.assertEqual(metadata["directionLabel"], "left_to_right")
725
  self.assertGreater(metadata["lineCount"], 0)
726
  self.assertEqual(metadata["segmentation"]["label"], "floor")