How to solve error "Index exceeds the number of array elements (12)."?
1 次查看(过去 30 天)
显示 更早的评论
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?
采纳的回答
Walter Roberson
2021-7-6
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()
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!