error in matlab, cellfun, display image

9 visualizaciones (últimos 30 días)
Tomas
Tomas el 26 de Abr. de 2014
Respondida: sanidhyak el 3 de Feb. de 2025 a las 6:33
Hello, i have a problem with cellfun
my code:
Z = cellfun(@(Z) Z', Z,'Un',0);
Z = cellfun(@(Z) cell2mat(Z), Z,'Un',0);
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
figure;
cluster = zeros(size(I));
for ii = 1:length(Z)
cluster(Z{ii}) = ii;
end
imshow(label2rgb(cluster))
title('Vystupny obraz - Metoda KMEANS','FontSize',16,'Color','k');
error:
??? Attempted to access Z(:,2); index out of bounds because size(Z)=[952,1].
Error in ==> KMNSimage>@(Z)sub2ind(size(I),Z(:,1),Z(:,2)) at 503
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
Error in ==> KMNSimage at 503
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
Z is :
Z={1x952 cell} {1x3141 cell} {1x3141 cell} {1x3141 cell}
know someone help ?
Thanks.

Respuestas (1)

sanidhyak
sanidhyak el 3 de Feb. de 2025 a las 6:33
Hi Tomas,
Based on my understanding the issue you are facing is an "index out of bounds" error when attempting to access “Z(:,2)” in the code provided.
I am assuming the following initialization, as it is not explicitly mentioned:
imageHeight = 512;
imageWidth = 512;
I = uint8(rand(imageHeight, imageWidth) * 255);
When running the code provided by you, I too faced a similar error:
Index in position 2 exceeds array bounds.
Error in test1>@(Z)sub2ind(size(I),Z(:,1),Z(:,2)) (line 26)
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This error occurs because some elements of Z are 1xN cell arrays instead of Nx2 matrices, which causes the indexing Z(:,2) to fail. To fix this, please ensure that each element of Z is correctly converted into an Nx2 matrix before calling “sub2ind.
Kindly refer to the following corrected code:
Z = cellfun(@(Z) Z', Z, 'UniformOutput', false); % Transpose each cell element
Z = cellfun(@(Z) cell2mat(Z), Z, 'UniformOutput', false); % Convert to matrix
% Ensure each matrix has two columns before applying sub2ind
Z = cellfun(@(Z) reshape(Z, [], 2), Z, 'UniformOutput', false);
Z = cellfun(@(Z) sub2ind(size(I), Z(:,1), Z(:,2)), Z, 'UniformOutput', false);
% Create output cluster map
cluster = zeros(size(I));
for ii = 1:length(Z)
cluster(Z{ii}) = ii;
end
imshow(label2rgb(cluster));
title('Vystupny obraz - Metoda KMEANS', 'FontSize', 16, 'Color', 'k');
Here, “reshape(Z, [], 2) makes sure that the contents of each cell are formatted into two columns correctly, which helps avoid any indexing problems.
To learn more about this, kindly refer to the following documentations:
Cheers and happy coding :)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by