k-means clustering原理与举例

图像聚类一般是灰度值的聚类。

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')

 

更多数学原理小文请关注公众号:未名方略

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞行codes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值