Can anyone explain the following code ?

1 Ansicht (letzte 30 Tage)
Touhidul islam
Touhidul islam am 30 Dez. 2017
Beantwortet: Star Strider am 30 Dez. 2017
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
full code is given below:
clc
clear all
close all
%%Load Image
[filename,pathname]=uigetfile({'*.*';'*.bmp';'*.tif';'*.gif';'*.png'},'Pick an Image File');
I= im2double(imread([pathname,filename]));
size(I)
[nrows,ncols,colorchannels]=size(I);
F = reshape(I,nrows*ncols,colorchannels);
size(F)
K = 8; % Cluster Numbers
CENTS = F( ceil(rand(K,1)*size(F,1)) ,:); % Cluster Centers
DAL = zeros(size(F,1),K+2); % Distances and Labels
KMI = 10; % K-means Iteration
for n = 1:KMI
%first step is to find nearby cluster for each pixel
for i = 1:size(F,1)
for j = 1:K
DAL(i,j) = norm(F(i,:) - CENTS(j,:)); %compare the distance between every pixel value with cluster centre.
end
[Distance, CN] = min(DAL(i,1:K)); % 1:K are Distance from Cluster Centers 1:K
DAL(i,K+1) = CN; % K+1 is Cluster Label
DAL(i,K+2) = Distance; % K+2 is Minimum Distance
end
for i = 1:K
A = (DAL(:,K+1) == i); % Cluster K Points
CENTS(i,:) = mean(F(A,:)); % New Cluster Centers
if sum(isnan(CENTS(:))) ~= 0 % If CENTS(i,:) Is Nan Then Replace It With Random Point
NC = find(isnan(CENTS(:,1)) == 1); % Find Nan Centers in first column of cents
for Ind = 1:size(NC,1)
CENTS(NC(Ind),:) = F(randi(size(F,1)),:);
end
end
end
end
X = zeros(size(F));
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
T = reshape(X,nrows,ncols,colorchannels);
%%Show
figure()
subplot(121); imshow(I); title('original')
subplot(122); imshow(T); title('segmented')
disp('number of segments ='); disp(K)

Akzeptierte Antwort

Star Strider
Star Strider am 30 Dez. 2017
With ‘K’ defined as 8, this segment:
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
searches all rows of the ‘K+1’ column of ‘DAL’ for a value that equals the index ‘i’. (The comparison will only match integer values.) It then creates matrix ‘X’ length ‘idx’ rows at a time, using the value ‘idx’ (that is apparently a column vector) returned from the find call to define the rows. It then uses the repmat (essentially ‘replicate matrix’) function to create duplicates of the row vector ‘CENTS(i,:)’ to the row size of the ‘idx’ vector. The 1 as the last argument means that the function creates a vertical (row) replication only, not row-and-column replication.
I added the indentation to make the code easier to read.

Weitere Antworten (0)

Kategorien

Mehr zu Cluster Analysis and Anomaly Detection finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by