prevision / apps /renderer /services /image /polygons.py
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
6.69 kB
"""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]))
lines.append(_fit_line(run))
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 straighten_polyline(points: np.ndarray, tolerance: float) -> np.ndarray:
"""Open-path version of `_straight_polygon`: the run's best-fit lines.
The path is split where it really changes direction (Douglas-Peucker,
`tolerance` px), each piece becomes its least-squares line, inner corners go
where neighbouring lines meet and the two ends are projected onto their line.
"""
points = np.asarray(points, dtype=np.float32).reshape(-1, 2)
if len(points) < 3 or tolerance <= 0:
return points.copy()
approx = cv2.approxPolyDP(points.reshape(-1, 1, 2), tolerance, False).reshape(-1, 2)
anchors = sorted({0, len(points) - 1} | {
int(np.flatnonzero((points == vertex).all(axis=1))[0]) for vertex in approx
})
lines = [_fit_line(points[start:end + 1]) for start, end in zip(anchors, anchors[1:])]
vertices = [_project_onto_line(points[0], lines[0])]
for k in range(1, len(lines)):
corner = _line_intersection(lines[k - 1], lines[k])
original = points[anchors[k]].astype(np.float64)
if corner is None or np.linalg.norm(corner - original) > 2.0 * tolerance:
corner = original
vertices.append(corner)
vertices.append(_project_onto_line(points[-1], lines[-1]))
return np.asarray(vertices, dtype=np.float32)
def _fit_line(run: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
vx, vy, x0, y0 = cv2.fitLine(run.astype(np.float32), cv2.DIST_L2, 0, 0.01, 0.01).ravel()
return np.array([x0, y0], np.float64), np.array([vx, vy], np.float64)
def _project_onto_line(point: np.ndarray, line) -> np.ndarray:
origin, direction = line
offset = np.asarray(point, np.float64) - origin
return origin + float(offset @ direction) * direction
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