How can I fix 'index ecxeeds matrix dimension' in face detection?

1 view (last 30 days)
hello, I've been working out with this coding which is if face have been detected, the ultrasonic can be sensed. Supposedly when the face not detected, the ultrasonic cannot be sensed.
%Create a detector object
faceDetector = vision.CascadeObjectDetector;
%Read input image from webcam
obj = imaq.VideoDevice('winvideo',1,'YUY2_160x120');
set(obj,'ReturnedColorSpace','rgb');
a = arduino('COM9', 'Uno', 'Libraries', {'JRodrigoTech/HCSR04', 'Servo'});
sensor = addon(a, 'JRodrigoTech/HCSR04','D12','D13');
servo_motor = servo(a,'D7');
%preview(obj)
axes(handles.axes1)
while(true)
frame=step(obj);
%Detect faces
bboxes =step(faceDetector,frame);
if bboxes (true)
%Annotate detected faces
IFaces = insertObjectAnnotation(frame,'rectangle', bboxes, 'HumanFace');
imshow(IFaces)
for i=1:inf
dist1=readDistance(sensor);
if(dist1<0.1500)
writePosition(servo_motor, 0.4);
cp = readPosition(servo_motor);
cp = cp*180;
fprintf('LID OPEN\n');
pause(5)
break
else
fprintf('LID CLOSE\n');
break
end
writePosition(servo_motor, 0);
cp = readPosition(servo_motor);
cp = cp*180
fprintf('LID CLOSE\n');
end
else(isempty(bboxes))
fprintf('LID CLOSE\n');
end
end
%closepreview(obj)
release(obj)
The ultrasonic sensor and servo motor is working well. But when I try to not show my face, the coding will show 'index exceeds matrix dimension' and error at 'if bboxes(true)'. Can someone tell me where the wrong part in my coding?

Accepted Answer

Walter Roberson
Walter Roberson on 21 Mar 2018
You have
bboxes =step(faceDetector,frame);
if bboxes (true)
When bboxes is not empty, then the equivalent code is:
temp = false(size(bboxes));
temp(1) = true;
if bboxes(temp) ~= 0
which uses logical indexing to select the first element of bboxes and then test whether it is zero or not. This works out to be the same as
if bboxes(1) ~= 0
Now consider the case where bboxes is empty because nothing was detected. Then bboxes(true) tries to select the first element of bboxes, same as bboxes(1), and that is a problem because bboxes is empty.
If what you want to check is whether any bounding boxes were detected, then your check should be
if ~isempty(bboxes)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!