Reputation: 167
I have an numpy array with 0 and 1's. I am trying to convert the 1's into polygons. I have managed to do so using rasterio and shapely as seen in the code below:
im = np.array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
shapes = rasterio.features.shapes(im)
polygons = [shapely.geometry.Polygon(shape[0]["coordinates"][0]) for shape in shapes if shape[1] == 1]
print(polygon[0])
however, each row and column reffers to longitude and latitude coordinates stored in different arrays. for example:
lon = np.array([125. , 125.25, 125.5 , 125.75, 126. ])
lat = np.array([-35. , -35.25, -35.5 , -35.75, -36. ])
Does anyone know how to create the polygons associated with the correct coordinates? I think I have to use the transform parameter of the rasterio.features.shapes function. Yet I haven't been able to figure it out yet.
Upvotes: 1
Views: 1059
Reputation: 167
Found the solution. The transform parameter indeed is needed. This parameter is and affine trasnformation which is defined as:
xres = (max(lon) - min(lon))/len(lon)
yres = (lat[-1] - lat[0])/len(lat)
transform1 = Affine.translation(min(lon) - xres / 2, lat[0] - yres / 2) * Affine.scale(xres, yres)
that can be used to create the polygons with rasterio and shapely
shapes = rasterio.features.shapes(im, transform = transform1)
polygons = [shapely.geometry.Polygon(shape[0]["coordinates"][0]) for shape in shapes if shape[1] == 1]
Upvotes: 1