TP-modelisation-images/super_pixel.asv

125 lines
2.9 KiB
Plaintext
Raw Normal View History

2022-03-22 07:13:49 +00:00
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 = +inf;
index_germe = 0;
for germe = germes'
index_germe = index_germe + 1;
% 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], 2);
% 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], 2);
% 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
for index_germe = 1:length(germes)
truc = germe_per_pixel == index_germe;
truc_rgb = reshape(img(repmat(truc,[1 1 3])), [], 3);
mean(truc_rgb);
mx = 0;
my = 0;
end
scatter(germes(:, 2), germes(:, 1), 'b.');
end
end