File size: 7,706 Bytes
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""Floor plane detection via edge fitting, vanishing point estimation, and homography.

Functions
---------
fit_floor_edges         - fit linear left/right floor boundary edges
detect_vanishing_point  - estimate a perspective vanishing point from floor edges
estimate_floor_plane    - compute a full floor plane (homography + optional metric geometry)
"""

import cv2
import numpy as np

from enums import GeometryProvider
from config.runtime import ENABLE_PLANE_FIT
from services.geometry.plane_fitting import (
    estimate_metric_floor_transform,
    fit_metric_floor_transform,
)


def fit_floor_edges(mask: np.ndarray):
    h, w = mask.shape[:2]
    row_ys, lefts, rights = [], [], []
    step = max(1, h // 260)
    for y in range(0, h, step):
        row_xs = np.where(mask[y] > 0)[0]
        if len(row_xs) < max(8, w * 0.01):
            continue
        row_ys.append(float(y))
        lefts.append(float(np.percentile(row_xs, 3)))
        rights.append(float(np.percentile(row_xs, 97)))
    if len(row_ys) < 8:
        return None
    row_ys_np = np.asarray(row_ys, dtype=np.float32)
    return np.polyfit(row_ys_np, np.asarray(lefts, dtype=np.float32), 1), np.polyfit(
        row_ys_np,
        np.asarray(rights, dtype=np.float32),
        1,
    )


def detect_vanishing_point(img_np: np.ndarray, floor_mask: np.ndarray):
    gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(gray, 60, 160)
    edges[floor_mask == 0] = 0
    lines = cv2.HoughLinesP(
        edges,
        rho=1,
        theta=np.pi / 180,
        threshold=60,
        minLineLength=max(40, min(img_np.shape[:2]) // 16),
        maxLineGap=24,
    )
    if lines is None:
        return None

    h, w = img_np.shape[:2]
    candidates = []
    for line in lines.reshape(-1, 4):
        x1, y1, x2, y2 = [float(v) for v in line]
        dx, dy = x2 - x1, y2 - y1
        length = float(np.hypot(dx, dy))
        if length < 40 or abs(dx) < 1:
            continue
        slope = dy / dx
        if abs(slope) >= 0.18:
            candidates.append((x1, y1, x2, y2, slope, length))

    intersections = []
    for i, (x1, y1, _, _, s1, l1) in enumerate(candidates):
        a1 = y1 - s1 * x1
        for x3, y3, _, _, s2, l2 in candidates[i + 1:]:
            if s1 * s2 > 0 or abs(s1 - s2) < 0.12:
                continue
            a2 = y3 - s2 * x3
            x = (a2 - a1) / (s1 - s2)
            y = s1 * x + a1
            if -w * 0.5 <= x <= w * 1.5 and -h <= y <= h * 0.95:
                intersections.append((x, y, min(l1, l2)))
    if not intersections:
        return None

    pts = np.asarray([[p[0], p[1]] for p in intersections], dtype=np.float32)
    weights = np.asarray([p[2] for p in intersections], dtype=np.float32)
    center = np.average(pts, axis=0, weights=weights)
    dist = np.linalg.norm(pts - center, axis=1)
    keep = dist <= np.percentile(dist, 70)
    if keep.sum() >= 3:
        center = np.average(pts[keep], axis=0, weights=weights[keep])
    return {"x": float(center[0]), "y": float(center[1])}


def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict | None = None):
    ys, xs = np.where(mask > 0)
    if len(xs) < 1000:
        return None, None

    xs_f, ys_f = xs.astype(np.float32), ys.astype(np.float32)
    x1, x2 = float(np.percentile(xs_f, 1)), float(np.percentile(xs_f, 99))
    y1, y2 = float(np.percentile(ys_f, 1)), float(np.percentile(ys_f, 99))
    width, height = x2 - x1, y2 - y1
    if width < 20 or height < 20:
        return None, None

    top_y = float(np.percentile(ys_f, 8))
    bottom_y = float(np.percentile(ys_f, 97))
    edge_fits = fit_floor_edges(mask)
    if edge_fits is None:
        return None, None
    left_fit, right_fit = edge_fits

    top_left = float(np.polyval(left_fit, top_y))
    top_right = float(np.polyval(right_fit, top_y))
    bottom_left = float(np.polyval(left_fit, bottom_y))
    bottom_right = float(np.polyval(right_fit, bottom_y))
    lower_xs = xs_f[ys_f >= np.percentile(ys_f, 80)]
    bottom_left = min(bottom_left, float(np.percentile(lower_xs, 4)))
    bottom_right = max(bottom_right, float(np.percentile(lower_xs, 96)))

    min_top_width = max(24.0, width * 0.18)
    top_center = (top_left + top_right) * 0.5
    if top_right - top_left < min_top_width:
        top_left = top_center - min_top_width * 0.5
        top_right = top_center + min_top_width * 0.5

    min_bottom_width = max(min_top_width * 1.25, width * 0.45)
    bottom_center = (bottom_left + bottom_right) * 0.5
    if bottom_right - bottom_left < min_bottom_width:
        bottom_left = bottom_center - min_bottom_width * 0.5
        bottom_right = bottom_center + min_bottom_width * 0.5

    h, w = mask.shape[:2]
    src = np.float32([
        [np.clip(bottom_left, 0, w - 1), np.clip(bottom_y, 0, h - 1)],
        [np.clip(bottom_right, 0, w - 1), np.clip(bottom_y, 0, h - 1)],
        [np.clip(top_right, 0, w - 1), np.clip(top_y, 0, h - 1)],
        [np.clip(top_left, 0, w - 1), np.clip(top_y, 0, h - 1)],
    ])

    vanishing_point = detect_vanishing_point(img_np, mask)
    if vanishing_point is not None and vanishing_point["y"] < bottom_y:
        vp_x = float(np.clip(vanishing_point["x"], -w * 0.25, w * 1.25))
        top_width = max(src[2][0] - src[3][0], width * 0.16)
        horizon_gap = max(bottom_y - top_y, 1.0)
        convergence = np.clip((top_y - vanishing_point["y"]) / horizon_gap, 0.12, 0.75)
        top_center = top_center * (1 - convergence * 0.35) + vp_x * (convergence * 0.35)
        src[3][0] = np.clip(top_center - top_width * 0.5, 0, w - 1)
        src[2][0] = np.clip(top_center + top_width * 0.5, 0, w - 1)

    if cv2.contourArea(src) < 100:
        return None, None
    dst = np.float32([[x1, y2], [x2, y2], [x2, y1], [x1, y1]])
    homography = cv2.getPerspectiveTransform(src, dst).flatten().tolist()
    metric_geometry = None
    if ENABLE_PLANE_FIT and geometry and geometry.get("points") is not None:
        metric_geometry = fit_metric_floor_transform(
            mask,
            geometry["points"],
            geometry.get("validMask"),
            geometry.get("normals"),
            geometry.get("intrinsics"),
            geometry.get("provider", GeometryProvider.MOGE_2),
        )
    if ENABLE_PLANE_FIT and metric_geometry is None and geometry:
        depth_provider = geometry.get("provider", GeometryProvider.DEPTH_ANYTHING)
        if depth_provider == GeometryProvider.MOGE_2:
            depth_provider = "moge-2-depth"
        metric_geometry = estimate_metric_floor_transform(
            mask,
            geometry.get("depth"),
            depth_provider,
            geometry.get("intrinsics"),
        )
    plane = {
        "x": x1,
        "y": y1,
        "width": width,
        "height": height,
        "quad": src.flatten().tolist(),
        "vanishingPoint": vanishing_point,
    }
    if metric_geometry:
        plane.update(metric_geometry)
        plane["camera"]["horizonY"] = (
            float(vanishing_point["y"]) if vanishing_point is not None else top_y
        )
    else:
        plane.update({
            "floorTransform": None,
            "metersPerUnit": None,
            "geometryConfidence": 0.25 if vanishing_point is not None else 0.1,
            "geometryProvider": GeometryProvider.HOMOGRAPHY,
            "cameraIntrinsics": None,
            "camera": {
                "focalLength": float(max(h, w) * 0.95),
                "horizonY": float(vanishing_point["y"]) if vanishing_point is not None else top_y,
                "confidence": 0.25 if vanishing_point is not None else 0.1,
            },
        })
    return homography, plane