I have 3 DEMs that I mask: non-NaN values = True and NaNs = False. I have an algorithm that plots the boundaries of the masks, but the issue is that it also plots the boundaries of the array of the mask (the parts that look like rectangles).. How can I modify my code so it follows strictly boundary of my mask (blue area) ?
Code:
import os
import numpy as np
import geopandas as gpd
import rasterio.features
from shapely.geometry import shape, LineString
from rasterio.enums import Resampling
# Set the directory path containing the georeferenced tifs
list_dems = "/path_to_dems/*"
# Initialize an empty list to hold the polylines
lines = []
# Loop through each tif in the directory
for file in list_dems:
# Open the tif file and read the data
with rasterio.open(os.path.join(directory, file)) as src:
data = src.read(1, masked=True)
transform = src.transform
crs = src.crs
# Generate a binary mask of the valid data pixels
mask = np.ma.masked_invalid(data).mask.astype(int)
# Generate polygon geometries from the valid data mask
shapes = rasterio.features.shapes(mask, transform=transform)
# Convert polygon geometries to LineString geometries
for polygon, value in shapes:
if value == 1:
boundary = shape(polygon).boundary
if isinstance(boundary, LineString):
lines.append(boundary)
# Create a GeoDataFrame from the polylines
df = gpd.GeoDataFrame(geometry=lines, crs=crs)
# Save the GeoDataFrame as a shapefile
df.to_file("output.shp")