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).
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 tobwdist
should be binary, so in your case you could try something likeThis 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)
, wherex
andy
are Matlab indices, remembering that Matlab indices start at1
and rows are first, i.e.BW(y,x)
.