栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

从图像分割的角度叙述Kmeans的模型与算法_opencv数字识别图像分割?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从图像分割的角度叙述Kmeans的模型与算法_opencv数字识别图像分割?

图像分割--Keman聚类

1 Kmean图像分割2 流程3 实现

1 Kmean图像分割

按照Kmean原理,对图像像素进行聚类。
优点:此方法原理简单,效果显著。
缺点:实践发现对于前景和背景颜色相近或者颜色区分度差的图像效果不显著。
本文对图像进行滤波,主要是为了消除树枝颜色的影响(滤波为非Keman图像分割的必要操作)。

2 流程

(1)读入图片,把图片转化为二维。
(2)根据Kmean算法对图像分割,返回类别标签和各类别中心点。
(3)根据类别标签复制各类别中心点得到结果,在对结果调整到原有尺度。

3 实现

(1)图像分割前添加滤波,消除噪声

## 1 图像分割--Keman聚类
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 1 读入图片
img0 = cv2.imread('bird.png', 1)  # (548,727,3)
img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)
img_ = cv2.GaussianBlur(img0, (13, 13), 10, 10)
h, w, c = img_.shape
img_blur = img_.reshape([-1, 3])
img_blur = np.float32(img_blur)

# 2 分类
criteria = (
cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
num_clusters = 2
_, label, center_color = cv2.kmeans(img_blur, num_clusters,
                                    None, criteria,
                                    num_clusters,
                                    cv2.KMEANS_RANDOM_CENTERS)
center_color = np.uint8(
    center_color)  # img_blur[398396,3],label[398396,1],center[2,3]
res = center_color[label.ravel()]  # [398396,3]
res = res.reshape([h, w, c])  # res[668044,3]--> [548,727,3]

# 3 显示
plt.subplot(131)
plt.title('origin')
plt.imshow(img0)
plt.subplot(132)
plt.title('img_blur')
plt.imshow(img_)
plt.subplot(133)
plt.title('result')
plt.imshow(res)

plt.show()


(2)颜色区分低的情况
当颜色区分低时,划分较少的种类,可以达到满意效果。

## 1 图像分割--Keman聚类
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 1 读入图片
img = cv2.imread('luna.png', 1)  # (548,727,3)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, c = img.shape
img0= img.reshape([-1, 3])
img0 = np.float32(img0)

# 3 分类
criteria = (
cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
num_clusters = 2
_, label, center_color = cv2.kmeans(img0, num_clusters,
                                    None, criteria,
                                    num_clusters,
                                    cv2.KMEANS_RANDOM_CENTERS)
center_color = np.uint8(
    center_color)  # img_blur[398396,3],label[398396,1],center[2,3]
res = center_color[label.ravel()]  # [398396,3]

res = res.reshape([h, w, c])  # res[668044,3]--> [548,727,3]

plt.subplot(121)
plt.title('origin')
plt.imshow(img)
plt.subplot(122)
plt.title('result')
plt.imshow(res)

plt.show()


注: 可以改变中心点的数值,调整分割后图像的颜色。

center_color = np.uint8(
    center_color)  
## 调整显示颜色
center_color[0]=[0,0,255]
center_color[1]=[255,0,0]

res = center_color[label.ravel()] 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782970.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号