MATLAB: How to find the nearest object to a reference point in binary image

find the nearest object in binary imageImage Acquisition ToolboxImage Processing Toolbox

Dear all,
I have a binary image that contains two objects(Object_A, Object_B) very close to each other as shown below. I want to find which object is closer to a reference point in order to be selected (Object_B in this example).
I was thinking to find the distance of the centroid of each object to the reference point (in this example the centroid of the reference point X = 360, Y = 330), but this will not work because in few cases the centroid of the far object could be closer to the reference point as I tried to explain in the figure below.
Is there any way to find the closest object to a reference point?
Any help and suggestion will be appreciated.
Meshoo

Best Answer

It's trivial. Just use bwboundaries to get the list of (x,y) coordinates of the boundary and then put in a for loop, calculating the distance using the Pythagorean Theorem to get the boundary that is the closest. In the for loop, you can vectorize it and use min().
boundaries = bwboundaries(binaryImage);
overallMinDistance = inf;
for b = 1 : length(boundaries)
thisBoundaryX = boundaries{b}(:, 1);
thisBoundaryY = boundaries{b}(:, 2);
distances = sqrt((thisBoundaryX - refx).^2 + (thisBoundaryY - refy).^2);
[minDistance, indexOfMin] = min(distances);
if minDistance < overallMinDistance
% This boundary is the closer one.
.............you finish the rest - it's easy.
end