# Avoiding identifying objects within previously identified objects in MATLAB

Apologies if the question title is confusing.

I've got some code below in MATLAB, which identifies squares/rectangles in an image.

img = imread('image.jpg');
imgbw = im2bw(image);
filter = bwareafilt(imagebw, [800 10000]);
fill = imfill(imgbw,'holes');
area = bwareaopen(fill,15);
final = bwlabel(area);
dets = regionprops(final,'boundingbox');
figure(1), imagesc(I1); hold on;
for count = 1 : numel(dets)
gg = dets(count).BoundingBox;
rectangle('position',gg,'edgecolor','r','linewidth',2);
end


I keep getting results where I am identifying squares, within another square I have already identified. i.e.:

What I wanted, was to identify the yellow as one square/rectangle, and leave it at that. But as you can see, I've identified my rectangle/square, but also identified squares in the middle. Does anyone know how I can get ignore shapes, that are also inside previously identified squares?

• once you get a meaningful shape, say the outer one(yellow), you capture those pixel boundaries and dont go into those boundaries. Hope this hint helps!! Jan 18 '15 at 10:59

There are two alternatives to this.

1. Adjust your opening parameter so that you end up with a fully connected shape. Say, instead of 15 you can use 25.

2. You can find the areas of all intersecting polygons using e.g. this. If the area of an intersection is higher than a given threshold, discard the polygon.

After finding overlapping polygons, you could consider averaging the hypothesis so that you end up with a more correct shape pose.