zhongranxu 2019-06-28
cv2.kmeans(data, K, bestLabels, criteria, attempts, flags[, centers]) -> retval, bestLabels, centers
(type,max_iter,epsilon)
type又有两种选择:
centers:这是一组聚类中心
假设只有一个特征的数据,即一维的,我们可以采用我们的T恤问题,只使用人的高度来决定T恤的大小。
因此,我们首先创建数据并在Matplotlib中绘制它
import numpy as np import cv2 import matplotlib.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()
现在我们应用KMeans功能。我们的标准是,每当运行10次迭代算法或达到epsilon = 1.0的精度时,停止算法并返回答案.
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 ) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) # Set flags (Just to avoid line break in the code) flags = cv2.KMEANS_RANDOM_CENTERS # Apply KMeans compactness,labels,centers = cv2.kmeans(z,2,None,criteria,10,flags) A = z[labels==0] B = z[labels==1] # Now plot 'A' in red, 'B' in blue, 'centers' in yellow 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()
我们设置大小为50x2的测试数据,其高度和权重为50人。 第一列对应于所有50个人的高度,第二列对应于它们的权重。 第一行包含两个元素,其中第一行是第一人的高度,第二行是他的重量。 类似地,剩余的行对应于其他人的高度和重量。
import numpy as np import cv2 import matplotlib.pyplot as plt X = np.random.randint(25,50,(25,2)) Y = np.random.randint(60,85,(25,2)) Z = np.vstack((X,Y)) # convert to np.float32 Z = np.float32(Z) # define criteria and apply 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) # Now separate the data, Note the flatten() A = Z[label.ravel()==0] B = Z[label.ravel()==1] # Plot the data plt.scatter(A[:,0],A[:,1]) 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()
颜色量化是减少图像中颜色数量的过程,这样做的一个原因是减少内存,某些设备可能具有限制,使得它只能产生有限数量的颜色,在那些情况下,也执行颜色量化,这里我们使用k均值聚类进行颜色量化。
import numpy as np import cv2 import matplotlib.pyplot as plt img = cv2.imread('img.jpg') Z = img.reshape((-1,3)) # convert to np.float32 Z = np.float32(Z) # define criteria, number of clusters(K) and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 8 ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) cv2.imshow('res2',res2) cv2.waitKey(0) cv2.destroyAllWindows()