如何使用PythonOpenCV中的meanshift在图像中查找集群?

2024-03-28 12:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着找到均值漂移的OpenCV方法,但什么也没找到。我正在寻找一种在图像中查找集群的方法,并使用python OpenCV将它们替换为它们的平均值。任何线索将不胜感激

例如:

输入:

enter image description here

输出:

enter image description here


Tags: 方法图像集群opencv均值平均值线索
1条回答
网友
1楼 · 发布于 2024-03-28 12:31:56

下面是来自sklearn的一个结果:

enter image description here

请注意,首先平滑图像以减少噪波。此外,这与图像分割论文中的算法不完全相同,因为图像和核是平坦的

代码如下:

import numpy as np
import cv2 as cv
from sklearn.cluster import MeanShift, estimate_bandwidth


img = cv.imread(your_image)

# filter to reduce noise
img = cv.medianBlur(img, 3)

# flatten the image
flat_image = img.reshape((-1,3))
flat_image = np.float32(flat_image)

# meanshift
bandwidth = estimate_bandwidth(flat_image, quantile=.06, n_samples=3000)
ms = MeanShift(bandwidth, max_iter=800, bin_seeding=True)
ms.fit(flat_image)
labeled=ms.labels_


# get number of segments
segments = np.unique(labeled)
print('Number of segments: ', segments.shape[0])

# get the average color of each segment
total = np.zeros((segments.shape[0], 3), dtype=float)
count = np.zeros(total.shape, dtype=float)
for i, label in enumerate(labeled):
    total[label] = total[label] + flat_image[i]
    count[label] += 1
avg = total/count
avg = np.uint8(avg)

# cast the labeled image into the corresponding average color
res = avg[labeled]
result = res.reshape((img.shape))

# show the result
cv.imshow('result',result)
cv.waitKey(0)
cv.destroyAllWindows()

相关问题 更多 >