TestClust.py 900 bytes
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 14:03:17 2019

@author: thomas.drevet
"""

import numpy as np
import imageio
from skimage import color
import matplotlib.pyplot as plt
import cv2

img = imageio.imread("C:\\Users\\thomas.drevet\\Documents\\Seafile\\DéFI\\Images_Orthorectifiées\\OrthoImage1_0865.png")

imgRS = img.reshape(-1, 3)

# convert to np.float32
imgRS = np.float32(imgRS)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 0.2)
K = 5
ret,label,center=cv2.kmeans(imgRS,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image
center = np.uint8(center)
ImageOutRS = center[label.flatten()]
ImageOut = ImageOutRS.reshape((img.shape))

plt.figure(2)
plt.imshow(ImageOut, cmap = 'gray')
plt.title("K-Cluster, K = 5")

imageio.imsave("Kmean.png", ImageOut)