1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import numpy as np import cv2 from PIL import Image from PIL import ImageEnhance from PIL import ImageFilter
from sklearn.cluster import KMeans from scipy.spatial.distance import cdist import matplotlib.pyplot as plt from sklearn import metrics
plt.rcParams['font.sans-serif']= ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
def func(): plt.figure(figsize=(8, 10)) plt.subplot(3, 2, 1) x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9]) x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3]) X = np.array(list(zip(x1, x2))).reshape(len(x1), 2) plt.xlim([0, 10]) plt.ylim([0, 10]) plt.title('Sample') plt.scatter(x1, x2) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b'] markers = ['o', 's', 'D', 'v', '^', 'p', '*', '+'] tests = [2, 3, 4, 5, 8] subplot_counter = 1 for t in tests: subplot_counter += 1 plt.subplot(3, 2, subplot_counter) kmeans_model = KMeans(n_clusters=t).fit(X) for i, l in enumerate(kmeans_model.labels_): plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l],ls='None') plt.xlim([0, 10]) plt.ylim([0, 10]) plt.title('K = %s, SCoefficient = %.03f' % (t, metrics.silhouette_score (X, kmeans_model.labels_,metric='euclidean'))) plt.show()
if __name__ == '__main__': data = cv2.imread(r'src/python-opencv/a.jpg') func()
|