|
| 1 | +import numpy as np |
| 2 | +from rasterio import features |
| 3 | + |
| 4 | +from nucleus import Point, PolygonPrediction |
| 5 | + |
| 6 | +try: |
| 7 | + from shapely import geometry |
| 8 | +except ModuleNotFoundError: |
| 9 | + from nucleus.shapely_not_installed import ( # pylint: disable=ungrouped-imports |
| 10 | + ShapelyNotInstalled, |
| 11 | + ) |
| 12 | + |
| 13 | + geometry = ShapelyNotInstalled |
| 14 | + |
| 15 | + |
| 16 | +def instance_mask_to_polys(instance_mask: np.ndarray, background_code=None): |
| 17 | + mask_values = [] |
| 18 | + all_polygons = [] |
| 19 | + not_background_mask = ( |
| 20 | + (instance_mask != background_code) if background_code else None |
| 21 | + ) |
| 22 | + for shape, value in features.shapes( |
| 23 | + instance_mask.astype(np.int16), |
| 24 | + mask=not_background_mask, |
| 25 | + ): |
| 26 | + poly = geometry.shape(shape) |
| 27 | + all_polygons.append(poly) |
| 28 | + mask_values.append(int(value)) |
| 29 | + |
| 30 | + return mask_values, all_polygons |
| 31 | + |
| 32 | + |
| 33 | +def transform_poly_codes_to_poly_preds( |
| 34 | + dataset_item_id: str, pred_value, pred_polys, code_to_label |
| 35 | +): |
| 36 | + polygon_predictions = [] |
| 37 | + for code, poly in zip(pred_value, pred_polys): |
| 38 | + if poly.type != "Polygon": |
| 39 | + continue |
| 40 | + label = code_to_label[code] |
| 41 | + x_stack, y_stack = poly.exterior.coords.xy |
| 42 | + pred = PolygonPrediction( |
| 43 | + label, |
| 44 | + vertices=[Point(x, y) for x, y in zip(x_stack, y_stack)], |
| 45 | + reference_id=dataset_item_id, |
| 46 | + ) |
| 47 | + polygon_predictions.append(pred) |
| 48 | + return polygon_predictions |
0 commit comments