Find closest point of labelled area to a point in an image with Matlab

381 Views Asked by At

I'm trying to find the closes point to an area in an image with Matlab:

consider this example code:

myimg = rgb2gray(imread('tissue.png')); %load grayscale example image of cells
BW=bwareaopen(myimg<150,10); %only look at dark pixels, remove small objects
BW=bwlabel(imfill(BW,'holes')) %fill holes of structures, label structures
figure; 
imagesc(BW); %display image

I'd like to find the closest point of the closest structure to a point e.g. [0,0]. My approach so far is to get all centroids of all connected structures, then loop through all of them to find the closest one (inaccurate and inefficient).

1

There are 1 best solutions below

0
On BEST ANSWER

If you just want to find a single closest point, you can use bwdist with a second output argument. This will give you a matrix which at each point contains the linear index of the closest non-zero point of the input image. You then just need to select the index corresponding to the point you are interested in. The input image to bwdist should be binary, so in your case you could try something like

% Make the image binary
binaryimage = BW > 0;

% Get the linear indices of the closest points
[~, idx] = bwdist(binaryimage);

% Find the linear index for point (3, 2)
x = 3;
y = 2;
pointindex = sub2ind(size(binaryimage), y, x);

% Find the index of the closet point from the segmentation
closestpointindex = idx(pointindex);

% Get coordinates of the closest point
[yc, xc] = ind2sub(size(binaryimage), closestpointindex);

This will give you the coordinates (xc, yc) and the matrix index (closestpointindex) of the pixel with a non-zero value in the binary image which is closest to the point (x,y), where x and y are Matlab indices, remembering that Matlab indices start at 1 and rows are first, i.e. BW(y,x).