Meanshift 算法是一種基于密度的聚類方法,可以用于圖像分割
import numpy as np
import cv2
from sklearn.cluster import MeanShift
image = cv2.imread('input_image.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_reshaped = image.reshape((-1, 3))
bandwidth = 50 # 調整這個值以改變聚類的精度
meanshift = MeanShift(bandwidth=bandwidth, bin_seeding=True)
meanshift.fit(image_reshaped)
labels = meanshift.labels_
cluster_centers = meanshift.cluster_centers_
segmented_image = cluster_centers[labels].reshape(image.shape)
segmented_image = cv2.cvtColor(segmented_image.astype(np.uint8), cv2.COLOR_RGB2BGR)
cv2.imshow('Segmented Image', segmented_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
這就是如何使用 Meanshift 算法進行圖像分割。請注意,這個方法可能不適用于所有類型的圖像,你可能需要根據實際情況調整參數。