How can I alterate a mask for Kmeans segmentation

조회 수: 1 (최근 30일)
Andreea Stancu
Andreea Stancu 2019년 6월 16일
댓글: Andreea Stancu 2019년 6월 16일
Dear all,
For K-means segmentation I used this code:
K = 4; % cluster number
men = menu('Choose the region of analysis','ALL image','Bounding box');
%%
[fname path]=uigetfile('*.*','Enter and Image');
fname=strcat(path, fname);
im=imread(fname);
figure, imshow(im)
%% ROI
if men==1
rect=[1,1,size(im,2)-1,size(im,1)-1];
elseif men==2
figure(),imshow(im)
rect = ceil(getrect());
close
end
% Mask
M = false(size(im(:,:,1)));
M(rect(2):rect(2)+rect(4),...
rect(1):rect(1)+rect(3)) = true;
%% function
[L,C_RGB] = kmeansfcn(im,K,M);
hold on;
figure('Position',[168,182,1625,744])
subplot(2,1,1),imshow(im)
title('Imagine originala')
% legend
leg = {}; hold on
for i=1:K
Col = (C_RGB(i,:)./255);
leg(i,:)={['Cluster ',num2str(i)]};
plot(1,1,'LineWidth',12,'Color',Col)
end
legend(leg,'FontSize',12);hold off
L=L(1:4:end, 1:4:end,:); % subsampling-iau din 4 in 4 pixeli=> micsorez aria de 4 ori
subplot(2,1,2),imshow(L,[])
title('Segmentare pe clustere')
with this function:
function [L,C_RGB] = kmeansfcn(img,K, mask)
if length(size(img))==3
X = [reshape(img(:,:,1),[],1),...
reshape(img(:,:,2),[],1),...
reshape(img(:,:,3),[],1)];
else
X = reshape(img(:,:,1),[],1);
end
mask = reshape(mask,[],1);
X2 = X(mask,:);
[Clust,C] = kmeans(double(X2),K,'Replicates',6);
C_RGB = round(C);
idx =uint8(mask);
idx2 = find(idx);
for i=1:length(idx2)
idx(idx2(i)) = Clust(i);
end
L= reshape(idx,size(img,1),size(img,2));
The code works just fine on sole images, but now I want to run it on an image database and I don't need anymore the whole ROI and the menu thing BUT I don't know how change the mask in the main code.
M = false(size(im(:,:,1)));
M(rect(2):rect(2)+rect(4),...
rect(1):rect(1)+rect(3)) = true;
I understand that this is related to the first part where I draw a rectangle over the region of interest but I can't see how to eliminate that first part without affecting the rest of my code.
Thanks in advance!!
LATER EDIT: I wish to use the full image option for all images, not the bounding box one.
  댓글 수: 2
Rik
Rik 2019년 6월 16일
Do you want to use the full image for all images, or the bounding box?
Andreea Stancu
Andreea Stancu 2019년 6월 16일
Full image for all of the images

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2019년 6월 16일
M = true(size(im,1), size(im,2));

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by