File size: 5,081 Bytes
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18196ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Mask-to-polygon conversion utilities."""

import cv2
import numpy as np


def contour_to_polygon(contour: np.ndarray, simplify_epsilon: float) -> np.ndarray:
    if simplify_epsilon > 0:
        contour = cv2.approxPolyDP(contour, simplify_epsilon, True)
    return contour.reshape(-1, 2)


def mask_to_polygons(
    mask: np.ndarray,
    min_area: float,
    simplify_epsilon: float,
) -> list[dict]:
    mask_u8 = (mask > 0).astype(np.uint8)
    contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    polygons = []
    for contour in contours:
        area = float(cv2.contourArea(contour))
        if area < min_area:
            continue

        polygon = contour_to_polygon(contour, simplify_epsilon)
        if len(polygon) < 3:
            continue

        x, y, width, height = cv2.boundingRect(polygon.astype(np.int32).reshape(-1, 1, 2))
        polygons.append({
            "points": [[int(px), int(py)] for px, py in polygon],
            "area": area,
            "bbox": [int(x), int(y), int(width), int(height)],
        })

    polygons.sort(key=lambda item: item["area"], reverse=True)
    return polygons


# Sub-pixel precision used when filling straightened polygons (cv2 `shift` bits).
_FILL_SHIFT = 4


def straighten_mask_edges(mask: np.ndarray, tolerance: float, min_area: float = 0.0) -> np.ndarray:
    """Redraw a binary mask so its boundaries are straight lines.

    Each boundary (outer edges and holes such as door or window cut-outs) is
    split where it really changes direction (Douglas-Peucker, `tolerance` px),
    every run is replaced by its least-squares line, and corners are placed
    where neighbouring lines meet. Pixel-level zig-zag within `tolerance`
    therefore becomes one straight edge through the middle of the wobble.
    Boundaries enclosing less than `min_area` px are dropped (specks vanish,
    pinholes are filled).
    """
    mask_u8 = (mask > 0).astype(np.uint8)
    if tolerance <= 0 or not mask_u8.any():
        return mask_u8
    contours, hierarchy = cv2.findContours(mask_u8, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    if hierarchy is None:
        return mask_u8

    depths = _contour_depths(hierarchy[0][:, 3])
    scale = float(1 << _FILL_SHIFT)
    out = np.zeros_like(mask_u8)
    for index in np.argsort(depths, kind="stable"):
        contour = contours[index]
        if abs(cv2.contourArea(contour)) < min_area:
            continue
        polygon = np.round(_straight_polygon(contour.reshape(-1, 2), tolerance) * scale).astype(np.int32)
        if len(polygon) < 3:
            continue
        if depths[index] % 2 == 0:
            cv2.fillPoly(out, [polygon], 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
        else:
            # A hole's contour runs through the mask pixels bordering it, so
            # redraw that edge line after clearing to keep the mask flush with it.
            cv2.fillPoly(out, [polygon], 0, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
            cv2.polylines(out, [polygon], True, 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
    return out


def _contour_depths(parents: np.ndarray) -> np.ndarray:
    """Nesting depth of each contour from cv2 RETR_TREE parent indices (0 = outer)."""
    depths = np.zeros(len(parents), dtype=np.int32)
    for index in range(len(parents)):
        parent = parents[index]
        while parent >= 0:
            depths[index] += 1
            parent = parents[parent]
    return depths


def _straight_polygon(points: np.ndarray, tolerance: float) -> np.ndarray:
    """Polygon whose edges are the best-fit lines of the contour's straight runs."""
    approx = cv2.approxPolyDP(points.reshape(-1, 1, 2), tolerance, True).reshape(-1, 2)
    if len(approx) < 3:
        return approx.astype(np.float32)

    position = {(int(x), int(y)): i for i, (x, y) in enumerate(points)}
    anchors = sorted(position[(int(x), int(y))] for x, y in approx)
    count = len(points)
    lines = []
    for k, start in enumerate(anchors):
        end = anchors[(k + 1) % len(anchors)]
        run = points[start:end + 1] if end > start else np.concatenate((points[start:], points[:end + 1]))
        vx, vy, x0, y0 = cv2.fitLine(run.astype(np.float32), cv2.DIST_L2, 0, 0.01, 0.01).ravel()
        lines.append((np.array([x0, y0], np.float64), np.array([vx, vy], np.float64)))

    vertices = []
    for k, anchor in enumerate(anchors):
        corner = _line_intersection(lines[k - 1], lines[k])
        original = points[anchor % count].astype(np.float64)
        # Near-parallel neighbours or a far-away intersection: keep the traced corner.
        if corner is None or np.linalg.norm(corner - original) > 2.0 * tolerance:
            corner = original
        vertices.append(corner)
    return np.asarray(vertices, dtype=np.float32)


def _line_intersection(first, second) -> np.ndarray | None:
    (p1, d1), (p2, d2) = first, second
    denom = d1[0] * d2[1] - d1[1] * d2[0]
    if abs(denom) < 1e-3:
        return None
    t = ((p2[0] - p1[0]) * d2[1] - (p2[1] - p1[1]) * d2[0]) / denom
    return p1 + t * d1