在 mean_shift 算法中没有产生正确的输出并且对图像进行分割

问题描述 投票:0回答:0

我有一个问题,比如我必须实施移位算法并对图像执行分割。这是蔬菜图片 我必须使用合适的带宽,使蔬菜看起来尽可能分离。我手动使用 sklearn estimate_bandwidth 来计算带宽并且我进行了硬编码。我不允许使用 sklearn,我只能使用 numpy、PIL 或 matplotlib 来实现它。 这是我试过的

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = np.array(Image.open("peppers.jpg"))

# Convert the image to grayscale
gray_img = np.mean(img, axis=2)

# Flatten the image to a 2D array of pixel values
flat_img = gray_img.reshape((-1, 1))

# Define the distance metric
def euclidean_distance(x1, x2):
    return np.sqrt(np.sum((x1 - x2) ** 2))

# Estimate the bandwidth parameter using the median of the pairwise distances
bandwidth = 0.24570638879032147

# Perform Mean Shift clustering
centroids = []
for i, point in enumerate(flat_img):
    centroid = point
    converged = False
    while not converged:
        points_within_bandwidth = flat_img[euclidean_distance(flat_img, centroid) < bandwidth]
        new_centroid = np.mean(points_within_bandwidth, axis=0)
        if euclidean_distance(new_centroid, centroid) < 1e-5:
            converged = True
        centroid = new_centroid
    centroids.append(centroid)

# Assign each data point to a cluster based on its converged mean
labels = np.zeros_like(flat_img)
for i, centroid in enumerate(centroids):
    labels[euclidean_distance(flat_img, centroid) < bandwidth] = i

# Reshape the labels to the shape of the original image
segmented_img = labels.reshape(gray_img.shape)

# Display the segmented image
plt.imshow(segmented_img)
plt.show()

首先花了很长时间,没有显示正确的输出。

python numpy machine-learning image-segmentation mean-shift
© www.soinside.com 2019 - 2024. All rights reserved.