131 lines
3.2 KiB
Matlab
131 lines
3.2 KiB
Matlab
function germes = super_pixel(img, K, m, n, q_max)
|
|
img = im2double(img);
|
|
% img = img(1:10, 1:10, :);
|
|
|
|
width = size(img, 1);
|
|
height = size(img, 2);
|
|
N = width * height;
|
|
|
|
S = sqrt(N / K);
|
|
X = S / 2:S:width;
|
|
Y = S / 2:S:height;
|
|
germes = zeros(length(X) * length(Y), 5);
|
|
c = 1;
|
|
|
|
for x = X
|
|
|
|
for y = Y
|
|
germes(c, :) = [x y 0 0 0];
|
|
c = c + 1;
|
|
end
|
|
|
|
end
|
|
|
|
scatter(germes(:, 2), germes(:, 1), 'g.');
|
|
|
|
c = 1;
|
|
|
|
for germe = germes'
|
|
|
|
x = germe(1);
|
|
y = germe(2);
|
|
|
|
xmin = floor(max(x - n, 1));
|
|
interval_x = xmin:min(x + n, width);
|
|
|
|
ymin = floor(max(y - n, 1));
|
|
interval_y = ymin:min(y + n, height);
|
|
|
|
Gmag = imgradient(img(interval_x, interval_y));
|
|
[~, ind_min] = min(Gmag(:));
|
|
[nr, nc] = ind2sub(size(Gmag), ind_min);
|
|
|
|
x = xmin + nr - 1;
|
|
y = ymin + nc - 1;
|
|
|
|
germes(c, :) = [x y img(x, y, 1) img(x, y, 2) img(x, y, 3)];
|
|
|
|
c = c + 1;
|
|
end
|
|
|
|
scatter(germes(:, 2), germes(:, 1), 'r.');
|
|
|
|
germe_per_pixel = zeros(width, height);
|
|
|
|
for q = 1:q_max
|
|
|
|
for x = 1:width
|
|
|
|
for y = 1:height
|
|
|
|
% initialisation des minimums
|
|
min_Ds = 1e5;
|
|
|
|
for index_germe = 1:length(germes)
|
|
germe = germes(index_germe,:);
|
|
|
|
% on récupère les coordonnées du germe
|
|
xg = germe(1);
|
|
yg = germe(2);
|
|
|
|
% on calcule la distance spatiale entre le germe et le pixel
|
|
Dxy = norm([x - xg y - yg]);
|
|
|
|
% si le germe est trop loin on skip
|
|
if Dxy > S
|
|
continue;
|
|
end
|
|
|
|
% on récupère les couleurs du germe
|
|
rg = germe(3);
|
|
gg = germe(4);
|
|
bg = germe(5);
|
|
|
|
% on récupère les couleurs du pixel
|
|
r = img(x, y, 1);
|
|
g = img(x, y, 2);
|
|
b = img(x, y, 3);
|
|
|
|
% on calcule la distance chromatique entre le germe et le pixel
|
|
Dlab = norm([r - rg g - gg b - bg]);
|
|
|
|
% on calcule Ds
|
|
Ds = Dlab + m / S * Dxy;
|
|
|
|
% Si Ds est meilleur on le prend
|
|
if Ds < min_Ds
|
|
germe_per_pixel(x, y) = index_germe;
|
|
min_Ds = Ds;
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
image(germe_per_pixel);
|
|
colormap lines;
|
|
|
|
for index_germe = 1:length(germes)
|
|
truc = germe_per_pixel == index_germe;
|
|
truc_rgb = reshape(img(repmat(truc,[1 1 3])), [], 3);
|
|
m_rgb = mean(truc_rgb);
|
|
mx = 0;
|
|
my = 0;
|
|
for i = find(truc == 1)'
|
|
[x, y] = ind2sub(size(img), i);
|
|
mx = mx + x;
|
|
my = my + y;
|
|
end
|
|
mx = mx / sum(truc, 'all');
|
|
my = my / sum(truc, 'all');
|
|
germes(index_germe,:) = [mx my m_rgb];
|
|
end
|
|
|
|
scatter(germes(:, 2), germes(:, 1), 'b.');
|
|
|
|
end
|
|
|
|
end
|