Skip to content

Instantly share code, notes, and snippets.

@rocreguant
Created August 7, 2020 15:21
Show Gist options
  • Save rocreguant/4a2e1b762917bd2b80915403f66dcc3a to your computer and use it in GitHub Desktop.
Save rocreguant/4a2e1b762917bd2b80915403f66dcc3a to your computer and use it in GitHub Desktop.
Function to transform cv2 thesholdiag (black and white / binary image) to a group of polygons
import rasterio
from rasterio import features
import shapely
from shapely.geometry import Point, Polygon
def mask_to_polygons_layer(mask):
all_polygons = []
for shape, value in features.shapes(mask.astype(np.int16), mask=(mask >0), transform=rasterio.Affine(1.0, 0, 0, 0, 1.0, 0)):
return shapely.geometry.shape(shape)
all_polygons.append(shapely.geometry.shape(shape))
all_polygons = shapely.geometry.MultiPolygon(all_polygons)
if not all_polygons.is_valid:
all_polygons = all_polygons.buffer(0)
# Sometimes buffer() converts a simple Multipolygon to just a Polygon,
# need to keep it a Multi throughout
if all_polygons.type == 'Polygon':
all_polygons = shapely.geometry.MultiPolygon([all_polygons])
return all_polygons
polygons = mask_to_polygons_layer(threshold)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment