This works only for images with very high contrast. So the code is limited to the contrast. Anyway to enhance contrast without introducing noise in an image?
function D = boundingbox(file,level)
image=imread(file);
figure
BW=im2bw(image,level);
%BW = ~BW;
imshow(BW)
BBs = [];
measurements = regionprops(BW, 'BoundingBox', 'Area');
for k = 1 : length(measurements)
thisBB = measurements(k).BoundingBox;
%rectangle('Position', [thisBB(1),thisBB(2),thisBB(3),thisBB(4)],...
%'EdgeColor','r','LineWidth',2 )
BBs = [BBs;thisBB];
end
areas=cat(1,measurements.Area);
[sortedAreas, sortingIndexes] = sort(areas, 'descend');
fusionindex = sortingIndexes(2);
rectangle('Position', [BBs(fusionindex,1),BBs(fusionindex,2),BBs(fusionindex,3),BBs(fusionindex,4)],...
'EdgeColor','r','LineWidth',2 )
D = BBs(fusionindex,3);
end