How to solve error "Index exceeds the number of array elements (12)."?

1 vue (au cours des 30 derniers jours)
Tawsif Mostafiz
Tawsif Mostafiz le 6 Juil 2021
Commenté : Tawsif Mostafiz le 7 Juil 2021
Hi, My code is as follows:
% Specify the folder where the files live.
myFolder = 'location';
filePattern = fullfile(myFolder, '*.bmp');
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
imageArray = imread(fullFileName);
r=1;
a=1;
for q=0.1:0.01:0.5
bw=im2bw(imageArray,q);
%%
% masked image is defined here
%%
blackpix=im2bw(maskedRgbImage,q);
num(r)=sum(blackpix(:) == 0); %calculating black pixels
if(q>0.1)
if (num(r)/num(r-1)>8 &&a==1) %there's always a spike of pixel increase between two certain values.
thresh(k)=q; % When spike occurs, we take the value
a=2; %making sure only the fisrt spike is taken
end
end
r=r+1
end
num=[]; %setting the array as null before entering into q with incremented k.
end
%% Same code again for putting the q from previous segment
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
imageArray = imread(fullFileName);
bw=im2bw(imageArray,thresh(k));
imshow(bw)
end
But when I give a large number of inputs, (more than 12) then it shows the following error:
Index exceeds the number of array elements (12).
Error in Untitled13 (line 117)
bw=im2bw(imageArray,thresh(k));
Can you guys tell me what I am missing here?

Réponse acceptée

Walter Roberson
Walter Roberson le 6 Juil 2021
if(q>0.1)
if (num(r)/num(r-1)>8 &&a==1) %there's always a spike of pixel increase between two certain values.
thresh(k)=q; % When spike occurs, we take the value
a=2; %making sure only the fisrt spike is taken
end
end
You only set thresh(k) in that condition, which means that for some files you might never set it.
for k = 1 : length(theFiles)
No file after the 12 file happened to set the corresponding thresh()
for k = 1 : length(theFiles)
%stuff
bw=im2bw(imageArray,thresh(k));
You are unconditionally using thresh(k) even though you only assign to thresh(k) conditionally.
I suggest you initialize
thresh = nan(1, length(theFiles));
and that will solve the problem of thresh sometimes not being initialized... and will change it into the problem of figuring out what it means to use NaN as the threshold for im2bw()

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by