File size: 1,161 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
"""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