Kmeans 图像分割 by python
来源:互联网 发布:淘宝店铺监控插件 编辑:程序博客网 时间:2024/05/17 12:55
依然是神奇的numpy boardcast!!!
于是代码只有28行!!!
>
输入:k,data[n];
(1) 选择 k 个初始中心点,例如 c[0] = data[0], ……,c[k-1]=data[k-1];
(2) 对于 data[0],……,data[n],分别与 c[0],……,c[k-1]比较,假设 c[i]差值最少,就标记为 i;
(3) 对于所有标记为 i 点,重新计算 c[i]={所有标记为 i 的 data[i]z 之和}/标记为 i 的个数;
(4) 重复(2)(3),直至所有 c[j]值的变化小于给定阈值。
from scipy.misc import imread,imshow,imsaveimport numpy as npfrom functools import partialdef kmeans(img,K,epsilon): img = img.astype(np.float64) randpos = partial(np.random.randint,0,min(img.shape[0],img.shape[1])) cx,cy = [randpos(K) for i in range(2)] center = img[cx,cy] img = img.reshape(1, img.shape[0], img.shape[1], -1) center = center.reshape(K, 1, 1, 3) # ite = 0 diff = np.inf pre_center = np.sum(center) while(diff>epsilon): dis = (img - center) ** 2 pos_label = np.sum(dis, axis=3).argmin(axis=0) for i in range(K): center[i] = np.mean(img[0,pos_label == i],axis=0) diff = np.abs(np.sum(center)-pre_center) pre_center = np.sum(center) # ite+=1 # print(ite,diff) for i in range(K): img[0,pos_label == i] = center[i] return np.squeeze(img).astype(np.float16)if __name__ == '__main__': img = np.floor(imread("/home/ryan/Desktop/cat.jpg")) img = kmeans(img,5,0.05) imshow(img)
0 0
- Kmeans 图像分割 by python
- kmeans算法分割图像
- Python小白进阶4:基于Kmeans的图像分割
- OPENCV之Kmeans图像分割
- Kmeans++及字典学习和图像分割
- Kmeans聚类及图像分割
- OpenCV学习 kmeans实现图像分割
- java代码 kmeans算法实现 图像分割
- 机器学习之Kmeans图像分割
- kmeans对图像和数据进行分割
- python-opencv3 kmeans图像分类
- python-opencv3 kmeans图像分类
- python 图像分割
- 图像分割kmeans算法利用hill-clambing确定k
- 基于kmeans聚类算法的图像分割
- Python Kmeans
- python-kmeans
- python libsvm 图像分割 字符识别
- 排序:入门及桶排序
- TCP-IP详解之TCP的超时与重传4
- [leetcode: Python]278.First Bad Version
- URLError处理异常
- 条款17以独立语句将new置入智能指针
- Kmeans 图像分割 by python
- java static 函数 变量 代码块
- exec函数族小结
- 静态方法注入bean
- thinkpad 自己安装Windows 10系统
- 算法导论 练习题 13.3-6
- Ubuntu显示/boot空间不足
- 进程间通信--管道通信
- Spring mvc mybatis 中Date类型 在返回给前端时需要格式化的实现方式