SLIC matlab
时间: 2023-10-31 18:46:13 浏览: 35
SLIC (Simple Linear Iterative Clustering) is an image segmentation algorithm that was first introduced in 2010. It is a popular algorithm due to its simplicity and efficiency. Here is a MATLAB code for SLIC:
% Read the input image
img = imread('input_image.jpg');
% Convert the input image to Lab color space
lab_img = rgb2lab(img);
% Define the number of clusters (k) and the compactness parameter (m)
k = 100;
m = 20;
% Calculate the step size for the grid
step = sqrt(size(img, 1) * size(img, 2) / k);
% Initialize the cluster centers
centers = zeros(k, 3);
for i = 1:k
x = mod(step/2 + (i-1)*step, size(img, 1));
y = mod(step/2 + floor((i-1)*step/size(img, 1))*step, size(img, 2));
centers(i,:) = lab_img(round(x), round(y), :);
end
% Run the SLIC algorithm
max_iter = 10;
for iter = 1:max_iter
% Assign each pixel to the nearest cluster center
dist = pdist2(lab_img, centers);
[min_dist, labels] = min(dist, [], 2);
% Update the cluster centers
for i = 1:k
idx = find(labels == i);
if ~isempty(idx)
center_lab = mean(lab_img(idx, :));
center_xy = mean([mod(idx-1, size(img, 1))+1, floor((idx-1)/size(img, 1))+1]);
D = sqrt(sum((lab_img(idx, :) - repmat(center_lab, size(idx, 1), 1)).^2, 2) + (mod(idx-1, size(img, 1))+1 - center_xy(1)).^2 + (floor((idx-1)/size(img, 1))+1 - center_xy(2)).^2);
mask = D <= m;
centers(i,:) = mean(lab_img(idx(mask), :));
end
end
end
% Display the segmented image
seg_img = reshape(labels, size(img, 1), size(img, 2));
imshow(seg_img, []);
colormap(gca, jet(k));
colorbar;