|
| 1 | +# coding: utf-8 |
| 2 | +import cv2 |
| 3 | +import numpy as np |
| 4 | +import matplotlib.pyplot as plt |
| 5 | + |
| 6 | +#读取原始图像 |
| 7 | +img = cv2.imread('scenery.png') |
| 8 | +print img.shape |
| 9 | + |
| 10 | +#图像二维像素转换为一维 |
| 11 | +data = img.reshape((-1,3)) |
| 12 | +data = np.float32(data) |
| 13 | + |
| 14 | +#定义中心 (type,max_iter,epsilon) |
| 15 | +criteria = (cv2.TERM_CRITERIA_EPS + |
| 16 | + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) |
| 17 | + |
| 18 | +#设置标签 |
| 19 | +flags = cv2.KMEANS_RANDOM_CENTERS |
| 20 | + |
| 21 | +#K-Means聚类 聚集成2类 |
| 22 | +compactness, labels2, centers2 = cv2.kmeans(data, 2, None, criteria, 10, flags) |
| 23 | + |
| 24 | +#K-Means聚类 聚集成4类 |
| 25 | +compactness, labels4, centers4 = cv2.kmeans(data, 4, None, criteria, 10, flags) |
| 26 | + |
| 27 | +#K-Means聚类 聚集成8类 |
| 28 | +compactness, labels8, centers8 = cv2.kmeans(data, 8, None, criteria, 10, flags) |
| 29 | + |
| 30 | +#K-Means聚类 聚集成16类 |
| 31 | +compactness, labels16, centers16 = cv2.kmeans(data, 16, None, criteria, 10, flags) |
| 32 | + |
| 33 | +#K-Means聚类 聚集成64类 |
| 34 | +compactness, labels64, centers64 = cv2.kmeans(data, 64, None, criteria, 10, flags) |
| 35 | + |
| 36 | +#图像转换回uint8二维类型 |
| 37 | +centers2 = np.uint8(centers2) |
| 38 | +res = centers2[labels2.flatten()] |
| 39 | +dst2 = res.reshape((img.shape)) |
| 40 | + |
| 41 | +centers4 = np.uint8(centers4) |
| 42 | +res = centers4[labels4.flatten()] |
| 43 | +dst4 = res.reshape((img.shape)) |
| 44 | + |
| 45 | +centers8 = np.uint8(centers8) |
| 46 | +res = centers8[labels8.flatten()] |
| 47 | +dst8 = res.reshape((img.shape)) |
| 48 | + |
| 49 | +centers16 = np.uint8(centers16) |
| 50 | +res = centers16[labels16.flatten()] |
| 51 | +dst16 = res.reshape((img.shape)) |
| 52 | + |
| 53 | +centers64 = np.uint8(centers64) |
| 54 | +res = centers64[labels64.flatten()] |
| 55 | +dst64 = res.reshape((img.shape)) |
| 56 | + |
| 57 | +#图像转换为RGB显示 |
| 58 | +img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
| 59 | +dst2 = cv2.cvtColor(dst2, cv2.COLOR_BGR2RGB) |
| 60 | +dst4 = cv2.cvtColor(dst4, cv2.COLOR_BGR2RGB) |
| 61 | +dst8 = cv2.cvtColor(dst8, cv2.COLOR_BGR2RGB) |
| 62 | +dst16 = cv2.cvtColor(dst16, cv2.COLOR_BGR2RGB) |
| 63 | +dst64 = cv2.cvtColor(dst64, cv2.COLOR_BGR2RGB) |
| 64 | + |
| 65 | +#用来正常显示中文标签 |
| 66 | +plt.rcParams['font.sans-serif']=['SimHei'] |
| 67 | + |
| 68 | +#显示图像 |
| 69 | +titles = [u'原始图像', u'聚类图像 K=2', u'聚类图像 K=4', |
| 70 | + u'聚类图像 K=8', u'聚类图像 K=16', u'聚类图像 K=64'] |
| 71 | +images = [img, dst2, dst4, dst8, dst16, dst64] |
| 72 | +for i in xrange(6): |
| 73 | + plt.subplot(2,3,i+1), plt.imshow(images[i], 'gray'), |
| 74 | + plt.title(titles[i]) |
| 75 | + plt.xticks([]),plt.yticks([]) |
| 76 | +plt.show() |
0 commit comments