Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Matrix dimension must agree error in the code,need a solution

1 visualización (últimos 30 días)
Poonam
Poonam el 23 de Sept. de 2013
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
function [clusters, result_image, clusterized_image] = kmeanssegment(im,k)
%histogram calculation
hist_value = zeros(256,1);
img_hist = zeros(1,256); % Reset
tic
[rows, columns] = size(im);
for col = 1 : columns
for row = 1 : rows
img_hist(im(row,col)+1) = img_hist(im(row,col)+1) + 1;
end
end
toc
for i=1:256
hist_value(i)=i-1; %#ok<NASGU>
end
%cluster initialization
cluster=zeros(k,1);
cluster_count = zeros(k,1);
for i=1:k
cluster(i)=uint8(rand*255);
end;
old = zeros(k,1);
while (sum(sum(abs(old-cluster))) >k)
old = cluster;
closest_cluster = zeros(256,1);
min_distance = uint8(zeros(256,1)); %#ok<NASGU>
min_distance = abs(hist_value-cluster(1));
%calculate the minimum distance to a cluster
for i=2:k
min_distance =min(min_distance, abs(hist_value-cluster(i)));
end;
%calculate the closest cluster
for i=1:k
closest_cluster(min_distance==(abs(hist_value-cluster(i)))) = i;
end
%calculate the cluster count
for i=1:k
cluster_count(i) = sum(img_hist.*(closest_cluster==i));
end;
for i=1:k
if (cluster_count(i) == 0)
cluster(i) = uint8(rand*255);
else
cluster(i) = uint8(sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))/cluster_count(i));
end
end
end
imresult=uint8(zeros(size(im)));
for i=1:256
imresult(im==(i-1))=cluster(closest_cluster(i));
end;
clustersresult=uint8(zeros(size(im)));
for i=1:256
clustersresult(im==(i-1))=closest_cluster(i);
end;
clusters = cluster;
result_image = imresult;
clusterized_image = clustersresult;
end
Error Elapsed time is 0.008945 seconds. ??? Error using ==> times Matrix dimensions must agree.
Error in ==> kmeansclustering at 52 cluster(i) = uint8(sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))/cluster_count(i));
Error in ==> kmeansclusteringdemo at 82 k=kmeansclustering(im,5);

Respuestas (1)

Image Analyst
Image Analyst el 23 de Sept. de 2013
Editada: Image Analyst el 23 de Sept. de 2013
Standard debugging technique is to break up the long expressions into smaller parts and look at them, so
sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))
becomes
a=img_hist(closest_cluster==i)
whos a
b = hist_value(closest_cluster==i)
whos b
c = sum(a.*b)
whos c
Give that a try and see what you learn. a and b should be the same size to do the element by element multiplication. But they won't be - that's why you got the error.

La pregunta está cerrada.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by