I am struggling with a Python problem. My plan is to compute the clustering of the kmeans algorithm for an image and to create polygons from this classification. My goal is to get the total number of Polygons and the area they are capturing.
The computation of the kmeans classification is working without any problem, but I have problems to create Polygons for a selected cluster. My code looks like this:
###import the necessary libraries import cv2 from sklearn.cluster import KMeans import numpy as np from rasterio import features from shapely.geometry import shape ###import the image, you can test it with any image img = cv2.imread("Test.jpeg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ###image preperation x, y, z = img.shape im = img.reshape(x*y, z) im = np.float32(im) #final cluster computation kmeans = KMeans(n_clusters=10, n_init=2) kmeans = kmeans.fit(im) means = np.float64(kmeans.labels_) #select one cluster masked_data = np.ma.masked_where(means != 0, means) # try to compute polygons based on the classification m=masked_data.data.reshape((x,y,1)) m=m.astype(np.float32) mypoly =  for vec in rasterio.features.shapes(m): mypoly.append(shape(vec))
When I export the
mypoly array, I get a strange looking polygon. I exported it like this:
import geopandas as gpd my_gdf = gpd.GeoDataFrame( geometry=mypoly) my_gdf.to_file("Example.shp", driver='ESRI Shapefile')
Any idea how to fix this?