网络编程
位置:首页>> 网络编程>> 网络编程>> OpenCV 图像分割实现Kmean聚类的示例代码

OpenCV 图像分割实现Kmean聚类的示例代码

作者:山居秋暝LS  发布时间:2023-08-10 18:59:41 

标签:OpenCV,Kmean,聚类

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

OpenCV 图像分割实现Kmean聚类的示例代码

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

OpenCV 图像分割实现Kmean聚类的示例代码

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

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

res = center_color[label.ravel()]

OpenCV 图像分割实现Kmean聚类的示例代码

来源:https://blog.csdn.net/qq_35732321/article/details/123756129

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com