OpenCV 图像分割–Kmean聚类

图像分割–Keman聚类

1 Kmean图像分割

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

2 流程

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

3 实现

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


import cv2
import numpy as np
import matplotlib.pyplot as plt

img0 = cv2.imread('bird.png', 1)
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)

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)
res = center_color[label.ravel()]
res = res.reshape([h, w, c])

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)颜色区分低的情况
当颜色区分低时,划分较少的种类,可以达到满意效果。

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('luna.png', 1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, c = img.shape
img0= img.reshape([-1, 3])
img0 = np.float32(img0)

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)
res = center_color[label.ravel()]

res = res.reshape([h, w, c])

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聚类

Original: https://blog.csdn.net/qq_35732321/article/details/123756129
Author: 山居秋暝LS
Title: OpenCV 图像分割–Kmean聚类

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/703981/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球