Draw a rectangular bounding box around a person in an image
Solution 1
Your problem actually isn't drawing the bounding box - it's locating the person inside the image, which you haven't quite done properly. If you don't do this correctly, then you won't be able place the correct bounding box around the person. This is what I have done to locate the person in the image, then drawing a bounding box around this person. This is assuming that your image is stored in im
:
- Notice that the intensity distribution of the person is darker than most of the scene. As such, I'm going to threshold the image by choosing any pixels less than intensity 65 to be white while the other pixels black.
- I clear any white pixels that surround the image border
- I perform a
regionprops
call extracting theBoundingBox
andArea
properties. - I search through all of the areas and find the
BoundingBox
with the largestArea
. - I use this
BoundingBox
and draw it on our image.
Therefore:
%// Step #1
im_thresh = im < 65;
%// Step #2
im_thresh2 = imclearborder(im_thresh);
%// Step #3
rp = regionprops(im_thresh2, 'BoundingBox', 'Area');
%// Step #4
area = [rp.Area].';
[~,ind] = max(area);
bb = rp(ind).BoundingBox;
%// Step #5
imshow(im);
rectangle('Position', bb, 'EdgeColor', 'red');
This is what we get:
Bear in mind that this isn't perfect. You may have to play around with the threshold to get a more accurate bounding box, but this should be enough for you to start with.
Good luck!
Solution 2
You can also use vision.PeopleDetector
in the Computer Vision System Toolbox:
im = imread('bnJzI.png');
detector = vision.PeopleDetector('ClassificationModel', 'UprightPeople_96x48', 'ClassificationThreshold', 2.5);
bbox = step(detector, im);
im2 = insertObjectAnnotation(im, 'rectangle', bbox, 'person');
imshow(im2);
Aadnan Farooq A
Updated on June 05, 2022Comments
-
Aadnan Farooq A almost 2 years
I want to make a bounding box around a person in an image. I tried different methods but I couldn't get the solution that I want.
Here's the image I am using:
Here's the code I have written so far:
bw = im2bw(test, graythresh(test)); bw2 = imfill(bw,'holes'); imshow(bw2); figure; L = bwlabel(bw2); imshow(label2rgb(L, @jet, [.7 .7 .7])) figure; imshow(I1); R = regionprops(L, 'BoundingBox'); rectangle('Position', R(1).BoundingBox);