# 单特征数据的聚类
import numpy as np
import cv2
from matplotlib import pyplot as plt
x = np.random.randint(25,100,25)
y = np.random.randint(175,255,25)
z = np.hstack((x,y))
z = z.reshape((50,1))
z = np.float32(z)
plt.hist(z,256,[0,256]),plt.show()
# 定义终止条件 = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# 设置标志
flags = cv2.KMEANS_RANDOM_CENTERS
# 应用 KMeans
compactness, labels, centers = cv2.kmeans(z, 2, None, criteria, 10, flags)
A = z[labels == 0]
B = z[labels == 1]
# 红色 A,蓝色 B, 黄色中心
plt.hist(A, 256, [0, 256], color='r')
plt.hist(B, 256, [0, 256], color='b')
plt.hist(centers, 32, [0, 256], color='y')
plt.show()
# 多特征数据的聚类
import numpy as np
import cv2
from matplotlib import pyplot as plt
Data1 = np.random.randint(25, 50, (25, 2))
Data2 = np.random.randint(60, 85, (25, 2))
Z = np.vstack((Data1, Data2))
Z = np.float32(Z)
# 定义终止条件和应用KMeans
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret, label, center = cv2.kmeans(
Z, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
A = Z[label.ravel() == 0]
B = Z[label.ravel() == 1]
# Plot the data
plt.scatter(A[:, 0], A[:, 1], c='b')
plt.scatter(B[:, 0], B[:, 1], c='r')
plt.scatter(center[:, 0], center[:, 1], s=80, c='y', marker='s')
plt.xlabel('Height'), plt.ylabel('Weight')
plt.show()
# 颜色量化
import numpy as np
import cv2
img = cv2.imread('assets/home.jpg')
# 拉成3维的特征,数量一共有图像尺寸的面积大小
Z = img.reshape((-1, 3))
Z = np.float32(Z)
# 定义终止条件和应用 KMeans
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 32
ret, label, center = cv2.kmeans(
Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
#
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
cv2.imshow('res2', res2)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv.kmeans( data, K, bestLabels, criteria, attempts, flags[, centers] ) -> retval, bestLabels, centers
查找聚类中心,并围绕聚类分组输入样本。
函数kmeans实现了一个k-means算法,该算法查找cluster_count聚类的中心,并围绕聚类对输入样本进行分组。作为输出, b e s t L a b e l s i bestLabels_i bestLabelsi包含存储在样本矩阵第 i i i行中的样本的基于0的聚类索引。
- data: 用于聚类的数据,可以是N维的浮点,类型可以是 CV_32F, CV_32FC2, CV_32FC3, 或者 std::vectorcv::Point2f points(sampleCount);
- K: 需要聚类的数目
- bestLabels: 存储聚类分类后的每个样本的标签
- criteria: 终止条件
- attempts: 标志,以指定使用不同初始标签执行算法的次数。算法返回产生最佳紧凑性的标签
- flags: 见 cv::KmeansFlags
- centers: 聚类中心的输出矩阵,每个聚类中心有一行。