【问题标题】:How to find clusters in image using mean shift in python opencv?如何使用 python opencv 中的均值偏移查找图像中的簇?
【发布时间】:2020-10-15 22:37:47
【问题描述】:
我尝试找到用于均值偏移的 OpenCV 方法,但没有任何结果。我正在寻找一种方法来查找图像中的簇并使用 python OpenCV 将它们替换为它们的平均值。任何线索将不胜感激。
例如:
输入:
输出:
【问题讨论】:
标签:
python
opencv
image-segmentation
mean-shift
【解决方案1】:
这是来自sklearn的结果:
请注意,首先对图像进行平滑处理以减少噪点。另外,这不是图像分割论文中的算法,因为图像和内核被展平了。
代码如下:
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()
【解决方案2】:
对于那些认为在 cv2 中找到均值偏移很简单的人,我有一些信息要与您分享。
@fmw42 给出的meanShift() 函数不是你想要的。我相信很多人(包括我)已经用谷歌搜索并找到了它。 OpenCV的meanShift()函数用于对象跟踪。
我们想要的可能是另一个名为 pyrMeanShiftFiltering() 的函数。
我没试过。仅供参考。