我正在使用 sklearn 包在 Python 中使用均值偏移算法。我实现的是由均值偏移算法处理的图像。我想要的是:我检测到一定数量的类,它们的颜色存储在cluster_centers
变量中,但我想知道某个类的区域,如果它符合条件,则必须从图像中裁剪该区域。我想我知道如何处理裁剪本身,但我不知道如何执行 ceratin 类的面积计算。也许我应该以某种方式计算这种颜色的像素数,因为我猜这个任务只是关于知道特定颜色覆盖的区域有多大。
以下是我的均值偏移算法代码:
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
import cv2
img = cv2.imread('roundaboutimg67.png')
img = cv2.medianBlur(img, 3)
flat_image = img.reshape((-1,3)) #flattening the imgage so it is no longer 3 dimensional
flat_image = np.float32(flat_image)
bandwidth = estimate_bandwidth(flat_image, quantile=0.06, n_samples=3000)
ms = MeanShift(bandwidth, max_iter=800, bin_seeding=True)
ms.fit(flat_image)
labeled=ms.labels_ #labels each individual class into segements
segments = np.unique(labeled)
cluster_centers = ms.cluster_centers_
cluster_centers = np.uint8(cluster_centers)
print('Number of segments: ', segments.shape[0])
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
cv2.imshow('result',result)
cv2.imwrite("mean_shift_result.png", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
我正在处理的图像示例:[1]:https ://i.stack.imgur.com/GC5pU.png