原始slic算法的matlab代码
时间: 2023-05-20 21:03:28 浏览: 72
以下是原始slic算法的matlab代码:
function [L, num] = slic(I, K, m)
% I: input image
% K: number of superpixels
% m: compactness parameter
% L: superpixel label matrix
% num: number of superpixels
[h, w, ~] = size(I);
S = round(sqrt(h*w/K)); % average size of superpixel
dx = [1, 0, -1, 0];
dy = [0, 1, 0, -1];
% initialize
L = zeros(h, w);
num = 0;
center = zeros(K, 2);
for i = 1:S:h
for j = 1:S:w
num = num + 1;
center(num, :) = [i+round(S/2), j+round(S/2)];
end
end
% iterate
for iter = 1:10
for k = 1:K
x = center(k, 1);
y = center(k, 2);
for i = max(1, x-S):min(h, x+S)
for j = max(1, y-S):min(w, y+S)
d = sqrt((i-x)^2 + (j-y)^2);
dc = sqrt(sum((I(i,j,:)-I(x,y,:)).^2));
D = sqrt(d^2 + (m*dc/S)^2);
if D < L(i,j) || L(i,j) == 0
L(i,j) = D;
end
end
end
end
% update center
for k = 1:K
x = center(k, 1);
y = center(k, 2);
minD = Inf;
for i = max(1, x-S):min(h, x+S)
for j = max(1, y-S):min(w, y+S)
if L(i,j) < minD
minD = L(i,j);
center(k, :) = [i, j];
end
end
end
end
end
% assign label
for i = 1:h
for j = 1:w
minD = Inf;
for k = 1:K
d = sqrt((i-center(k,1))^2 + (j-center(k,2))^2);
if d < minD
minD = d;
L(i,j) = k;
end
end
end
end
end
阅读全文