# Count the polygons of the raster given by the kmeans algorithm

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.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

# try to compute polygons based on the classification
m=m.astype(np.float32)
mypoly = []

for vec in rasterio.features.shapes(m):
mypoly.append(shape(vec[0]))

``````

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?

• Why not use rasterio directly to load the image ? – gene May 7 at 7:38
• @gene thanks for your comment! Is it then possible to use the kmeans algorithm like this if the image is directly loaded via rasterio?? – Gatsen May 7 at 8:55
• I found many examples when I search rasterio+kmeans pn google – gene May 7 at 9:23
• Thanks a lot for this little hint! Now, I am able to get the right Polygons. Thanks @gene – Gatsen May 7 at 10:53