Index exceeds the number of array elements in image processing.

1 view (last 30 days)
The given code below shows an error that index exceeds the number of array elements. And for different video sample it runs for different no. of frames. How to fix this?
% Calculate the diameter.
grayImage = rgb2gray(thisFrame);%to convert image from rgb to gray
Unrecognized function or variable 'thisFrame'.
EdgeFrame = edge(grayImage,"sobel");%to detect edges
Graycrop = imcrop(EdgeFrame,[60 100 150 10]); %To crop the image
t = zeros(2,10);
for i=1:10
r = find(EdgeFrame(:,i));
L = length(r);
t(1,i)=r(1);
t(2,i)=r(L);
end
upper_edge = max(t(1,:));
lower_edge = min(t(2,:));
Diameter(frame) = abs(upper_edge - lower_edge);

Answers (2)

Glenn
Glenn on 24 Jun 2022
To me it seems like the image 'thisFrame', is not always the same size, can that be correct?
It seems like you could either (1) use the cropped version inside your for-loop, or (2) deal with the variable image size in the initiation of your for-loop.
Possible solutions:
(1)
r = find(Graycrop(:,i));
(2)
dimSize = size(EdgeFrame, 2);
Graycrop = imcrop(EdgeFrame,[60 100 150 dimSize]); %To crop the image
t = zeros(2, dimSize);
for i=1:dimSize
r = find(EdgeFrame(:,i));
% moreover, I think you can add some efficiency here:
t(:,i) = r([1, end]);
end

DGM
DGM on 24 Jun 2022
Obviously, not all columns of the edgemap will contain nonzero elements, so r will often be zero-length. Also, Graycrop isn't used for anything, so I don't know if that's intended.
Either way, this isn't exactly an efficient or robust way to find the diameter of an object. Consider the example:
A = imread('acircle.png');
A = rgb2gray(A);
mk = A>128; % binarize
% using regionprops
S = regionprops(mk,'equivdiameter');
d = S.EquivDiameter
d = 190.8529
% this is the simplified version of your method
h = nnz(any(mk,1)) % object height
h = 190
% or likewise
w = nnz(any(mk,2)) % object width
w = 190

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!