Reputation: 303
I am trying to draw an outer bounding box, around all smaller bounding boxes that are overlapping. There may be many of these regions within the entire image.
e.g.
So far I have my vector of rectangles called rects.
overlaps = rectint(rects, rects);
Where I check of overlaps with each other, and because it will compare with itself I remove the diagonal as follows:
overlaps(logical(eye(size(overlaps)))) = 0;
Then find the locations of the overlaps
[r,c] = find(overlaps > 0);
However, I am not sure how to deal with this as it is not a simple bi directional mapping in the square matrix returned, as there can be multiple overlaps in the area.
Any suggestions on how I can proceed would be greatly appreciated.
Thanks
Upvotes: 3
Views: 1456
Reputation: 303
function localBoxes = maxBoxVals(finalBoxes)
rects = [];
for es = 1 : length(finalBoxes)
y = finalBoxes(es, 1);
x = finalBoxes(es, 2);
y2 = finalBoxes(es, 3);
x2 = finalBoxes(es, 4);
rects = [rects ; [x, y, y2-y, x2 - x]];
end
overlaps = rectint(rects, rects);
%overlaps(logical(eye(size(overlaps)))) = 0;
[r,c] = find(overlaps > 0);
localBoxes = [];
for i = 1 : length(overlaps)
col = overlaps(:,i);
col2 = find(col > 0);
if(~length(col2) > 0)
continue;
end
localRects = [rects(i,:)];
for j = 1 : length(col2)
localRects = [localRects ; rects(col2(j),:)];
end
if(max(localRects) > 0)
minX = min(localRects(:,1));
minY = min(localRects(:,2));
maxX = max(localRects(:,1))+max(localRects(:,3));
maxY = max(localRects(:,2))+max(localRects(:,4));
localBoxes = [localBoxes ; [minX,minY,abs(maxX - minX), abs(maxY - minY)]];
end
end
localBoxes = unique(localBoxes,'rows')
end
This is what I have come up with to solve. Not vectorised and definitely not optimal, and may be some bugs, but seems to get the job done for what I need, and applies to the whole image.
Upvotes: 0
Reputation: 26069
here's and example with some random rectangles:
% Generate fake data, 3 rects with format [x,y,w,h]:
rects=20+randi(60,3,4);
% plot the rects :
for n=1:size(rects,1)
rectangle('Position',rects(n,:));
end
% get min max
xmin=min(rects(:,1));
ymin=min(rects(:,2));
xmax=max(rects(:,1)+rects(:,3));
ymax=max(rects(:,2)+rects(:,4));
% define outer rect:
outer_rect=[xmin ymin xmax-xmin ymax-ymin];
hold on
rectangle('Position',outer_rect,'EdgeColor','r','LineStyle',':');
Upvotes: 5