import numpy as np
import cv2
img = cv2.imread('differential geometry.jpeg')
img2 = img.reshape((-1,3))
# convert to np.float32
img2 = np.float32(img2)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret,label,center=cv2.kmeans(img2,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('img',img)
cv2.imshow('res2',res2)
K=3
ret,label,center=cv2.kmeans(img2,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('res3',res2)
K=4
ret,label,center=cv2.kmeans(img2,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('res4',res2)
搬运原理
import pylab
import scipy.cluster.vq as vq
class1 = 1.5 * pylab.randn(100, 2)
class2 = pylab.randn(100, 2) + pylab.array([5, 5])
features = pylab.vstack((class1, class2))
centroids, variance = vq.kmeans(features, 2)
code, distance = vq.vq(features, centroids)
pylab.figure()
ndx = pylab.where(code == 0)[0]
pylab.plot(features[ndx, 0], features[ndx, 1], '*')
ndx = pylab.where(code == 1)[0]
pylab.plot(features[ndx, 0], features[ndx, 1], 'r.')
pylab.plot(centroids[:, 0], centroids[:, 1], 'go')
更多数学原理小文请关注公众号:未名方略