Download services/image/polygons.py from modventures/room-visualizer-v2: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/image/polygons.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer-v2/services/image/polygons.py
-
curl -L -o polygons.py https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/image/polygons.py
1.16 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 | |