in fvcore/transforms/transform.py [0:0]
def apply_polygons(self, polygons: list) -> list:
"""
Apply crop transform on a list of polygons, each represented by a Nx2 array.
It will crop the polygon with the box, therefore the number of points in the
polygon might change.
Args:
polygon (list[ndarray]): each is a Nx2 floating point array of
(x, y) format in absolute coordinates.
Returns:
ndarray: cropped polygons.
"""
import shapely.geometry as geometry
# Create a window that will be used to crop
crop_box = geometry.box(
self.x0, self.y0, self.x0 + self.w, self.y0 + self.h
).buffer(0.0)
cropped_polygons = []
for polygon in polygons:
polygon = geometry.Polygon(polygon).buffer(0.0)
# polygon must be valid to perform intersection.
if not polygon.is_valid:
continue
cropped = polygon.intersection(crop_box)
if cropped.is_empty:
continue
if not isinstance(cropped, geometry.collection.BaseMultipartGeometry):
cropped = [cropped]
# one polygon may be cropped to multiple ones
for poly in cropped:
# It could produce lower dimensional objects like lines or
# points, which we want to ignore
if not isinstance(poly, geometry.Polygon) or not poly.is_valid:
continue
coords = np.asarray(poly.exterior.coords)
# NOTE This process will produce an extra identical vertex at
# the end. So we remove it. This is tested by
# `tests/test_data_transform.py`
cropped_polygons.append(coords[:-1])
return [self.apply_coords(p) for p in cropped_polygons]