K-Means Clustering in OpenCVhtml
cv2.kmeans(data, K, bestLabels, criteria, attempts, flags[, centers]) -> retval, bestLabels, centers
算法
(type,max_iter,epsilon)
type又有兩種選擇:數組
centers:這是一組聚類中心app
假設只有一個特徵的數據,即一維的,咱們能夠採用咱們的T恤問題,只使用人的高度來決定T恤的大小。
所以,咱們首先建立數據並在Matplotlib中繪製它dom
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我的的高度,第二列對應於它們的權重。 第一行包含兩個元素,其中第一行是第一人的高度,第二行是他的重量。 相似地,剩餘的行對應於其餘人的高度和重量。 ui
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均值聚類進行顏色量化。spa
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()