Vectorize a raster dataset. Args: source (str): The path to the tiff file. output (str): The path to the vector file. simplify_tolerance (float, optional): The maximum allowed geometry displacement. The higher this value, the smaller the number of vertices in
(source, output, simplify_tolerance=None, dst_crs=None, **kwargs)
| 1420 | |
| 1421 | |
| 1422 | def raster_to_vector(source, output, simplify_tolerance=None, dst_crs=None, **kwargs): |
| 1423 | """Vectorize a raster dataset. |
| 1424 | |
| 1425 | Args: |
| 1426 | source (str): The path to the tiff file. |
| 1427 | output (str): The path to the vector file. |
| 1428 | simplify_tolerance (float, optional): The maximum allowed geometry displacement. |
| 1429 | The higher this value, the smaller the number of vertices in the resulting geometry. |
| 1430 | """ |
| 1431 | from rasterio import features |
| 1432 | |
| 1433 | with rasterio.open(source) as src: |
| 1434 | band = src.read() |
| 1435 | |
| 1436 | mask = band != 0 |
| 1437 | shapes = features.shapes(band, mask=mask, transform=src.transform) |
| 1438 | |
| 1439 | fc = [ |
| 1440 | {"geometry": shapely.geometry.shape(shape), "properties": {"value": value}} |
| 1441 | for shape, value in shapes |
| 1442 | ] |
| 1443 | if simplify_tolerance is not None: |
| 1444 | for i in fc: |
| 1445 | i["geometry"] = i["geometry"].simplify(tolerance=simplify_tolerance) |
| 1446 | |
| 1447 | if fc: |
| 1448 | gdf = gpd.GeoDataFrame.from_features(fc) |
| 1449 | else: |
| 1450 | # No foreground pixels in the mask. Build an empty GeoDataFrame that |
| 1451 | # still carries a geometry column so set_crs/to_crs/to_file work and we |
| 1452 | # emit a valid (empty) layer instead of raising "no active geometry |
| 1453 | # column" from geopandas. |
| 1454 | gdf = gpd.GeoDataFrame({"value": []}, geometry=[]) |
| 1455 | if src.crs is not None: |
| 1456 | gdf.set_crs(crs=src.crs, inplace=True) |
| 1457 | |
| 1458 | if dst_crs is not None: |
| 1459 | gdf = gdf.to_crs(dst_crs) |
| 1460 | |
| 1461 | gdf.to_file(output, **kwargs) |
| 1462 | |
| 1463 | |
| 1464 | def raster_to_gpkg(tiff_path, output, simplify_tolerance=None, **kwargs): |
no outgoing calls
no test coverage detected