i need a rough k means code anyone help me plzz ...the following code has some errors.

1 次查看(过去 30 天)
function [rkm] = Km(I,K,wlower,threshold)
I = imread('1.jpg');
I = im2double(I); % Load Image
F = reshape(I,size(I,1)*size(I,2),3);
wupper=1-wlower;
K = 8;
F_ORG=F;
N=fix(size(F,1)/k);
for i=1:k
lowap(:,:,i) = F( ceil(rand(N,1)*size(F,1)) ,:);
F(ismember(F,lowap(:,:,i),'rows'),:)=[]
end
lowap(:,:,i)=(lowap(:,:,i);F);
for i=1:k
upap(:,:,i)=lowap(:,:,i);
end
DAL = zeros(size(F_ORG,1),K+2); % Distances and Labels
KMI = 10; % K-means Iteration
for n = 1:KMI
for i = 1:size(F,1)
upap(:,:,i)(ismember(upap(:,:,i),lowap(:,:,i),'rows'),:)=[];
if (~isempty(lowap(:,:,i)))&& (isempty(upap(:,:,i)))
cents(k,size(F,1))=sum(lowapp(:,:,i),1)/size(lowap(:,:,i));
elseif (isempty(lowap(:,:,i))) && (~isempty(upap(:,:,i)))
cents(k,size(F,1)=sum(upap(:,:,i)/size(upap(:,:,i);
else
cents(k,size(F,1)=wlower*(sum(lowap(:,:,i))/size(lowap(:,:i)))+wupper*(sum(upap(:,:,i))/size(upap(:,:,i)));
for j = 1:K
DAL(i,j) = norm(F(i,:) - cents(j,:));
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
for a=1:k
for b=1:k
if DAL(:,a)/DAL(:,b)<=threshold
end
X = zeros(size(F_ORG));
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
rkm = reshape(X,size(I,1),size(I,2),3);
end
  4 个评论
Jan
Jan 2019-2-20
Does this mean, that you have posted a completely flawed code? Why?
What's wrong with using one of the many published codes for a valid KNN-search? Take a look in the FileExchange.

请先登录,再进行评论。

回答(2 个)

John D'Errico
John D'Errico 2019-2-20
编辑:John D'Errico 2019-2-20
Easy, peasy. It is right here:
Writing your own code to do what others have done far better than you know how to do is a bad idea. And it costs what? Compared to the amount of your own time you have already wasted should say something. Is your own time worth nothing at all?
Or do a search for kmeans on the file exchange. I'd bet you will find at least one code. You would be better off getting the stats TB.

Image Analyst
Image Analyst 2019-2-20
Not sure what this confusing, uncommented code does. But if you want an example of how kmeans can do a segmentation of intensity in images, see the attached.
That said, I think that in most cases, kmeans is a lousy way to segment images, as you'll probably find out, so don't come back and say "Hey kmeans did a lousy job segmenting my images."
By the way, no sense in passing in the badly-named I when I is just overwritten by calling imread() in the function.

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by