|
| 1 | +from __future__ import annotations |
1 | 2 | from typing import Optional, Union, Tuple |
2 | 3 |
|
3 | 4 | import cv2 |
4 | 5 | import geojson |
5 | 6 | import numpy as np |
| 7 | +from shapely.geometry import Polygon as SPolygon |
6 | 8 |
|
7 | 9 | from .geometry import Geometry |
8 | 10 | from .point import Point |
@@ -30,6 +32,28 @@ def geometry(self) -> geojson.geometry.Geometry: |
30 | 32 | [self.start.x, self.start.y], |
31 | 33 | ]]) |
32 | 34 |
|
| 35 | + @classmethod |
| 36 | + def from_shapely(cls, shapely_obj: SPolygon) -> Rectangle: |
| 37 | + """Transforms a shapely object. |
| 38 | + |
| 39 | + If the provided shape is a non-rectangular polygon, a rectangle will be |
| 40 | + returned based on the min and max x,y values.""" |
| 41 | + if not isinstance(shapely_obj, SPolygon): |
| 42 | + raise ValueError( |
| 43 | + f"Expected Shapely Polygon. Got {shapely_obj.geom_type}") |
| 44 | + |
| 45 | + #we only consider 0th index because we only allow for filled polygons |
| 46 | + obj_coords = np.array(shapely_obj.__geo_interface__['coordinates'][0]) |
| 47 | + |
| 48 | + min_x, max_x = np.min(obj_coords[:, 0]), np.max(obj_coords[:, 0]) |
| 49 | + min_y, max_y = np.min(obj_coords[:, 1]), np.max(obj_coords[:, 1]) |
| 50 | + |
| 51 | + start = [min_x, min_y] |
| 52 | + end = [max_x, max_y] |
| 53 | + |
| 54 | + return Rectangle(start=Point(x=start[0], y=start[1]), |
| 55 | + end=Point(x=end[0], y=end[1])) |
| 56 | + |
33 | 57 | def draw(self, |
34 | 58 | height: Optional[int] = None, |
35 | 59 | width: Optional[int] = None, |
|
0 commit comments