gpt4 book ai didi

python - 如何使用python opencv中的均值偏移在图像中查找簇?

转载 作者:行者123 更新时间:2023-12-04 09:36:13 26 4
gpt4 key购买 nike

我尝试找到 OpenCV 方法来进行均值偏移,但没有任何结果。我正在寻找一种方法来查找图像中的簇并使用 python OpenCV 用它们的平均值替换它们。任何线索将不胜感激。
例如:
输入:
enter image description here
输出:
enter image description here

最佳答案

这是来自 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()

关于python - 如何使用python opencv中的均值偏移在图像中查找簇?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62575894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com