Draw a rectangular bounding box around a person in an image

Aadnan Farooq A picture Aadnan Farooq A · Dec 15, 2014 · Viewed 14.9k times · Source

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:

enter image description here

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);  

Answer

rayryeng picture rayryeng · Dec 15, 2014

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:

  1. 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.
  2. I clear any white pixels that surround the image border
  3. I perform a regionprops call extracting the BoundingBox and Area properties.
  4. I search through all of the areas and find the BoundingBox with the largest Area.
  5. 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:

enter image description here

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!