计算图像蒙版中的点到一组点的最小距离

Calculate minimum distance of point in image mask to a set of points

我有一个像这样的图像遮罩(differenceM):

对于每个白色像素(像素值!= 0),我想计算从该像素到一组点的最小距离。点集是外部轮廓上的点,将存储为 [x_val y_val] 的 numpy 数组。我正在考虑这样做:

...
def calcMinDist(dilPoints):
    ...

#returns 2d array (same shape as image)
def allMinDistDil(dilMask):
    dilPoints = getPoints(dilMask)
    ...
    return arrayOfMinValues

#more code here

blkImg = np.zeros(maskImage.shape,dtype=np.uint8)
blkImg.fill(0) 

img_out = np.where(differenceM,allMinDistDil(dilatedMask),blkImg)

....

但问题是,为了计算从一个像素点到一组点(从 getPoints 函数获得)的最小距离,我还需要传入像素点(索引?) .但是(如果我的理解是正确的,)对于这个 where 函数,它只检查第一个参数中的 true 和 false 值......所以我编写 np.where() 函数的方式将不起作用。

我考虑过使用嵌套 for 循环来解决这个问题,但我试图避免使用 for 循环,因为我有很多图像要处理。

我可以寻求解决这个问题的建议吗?任何帮助将不胜感激!

(没有足够的代表发表评论)至于你可能想要的距离 scipy.spatial.distance.cdist( X, Y ) 。您可以简单地计算最小距离:

from scipy.spatial import distance

def min_distance(points, set_of_points):
    return distance.cdist(np.atleast_1d(point), set_of_points).min()

至于np.where你能提供更多关于你的数据结构的信息吗?大多数时候,一个简单的布尔掩码就可以完成工作...

我没有使用 np.where() 函数来查找不为零的特定像素,而是应用了:

diffMaskNewArray = np.transpose(np.nonzero(binaryThreshMask))

获取值不为零的点。有了这个点数组,我遍历了这个数组中的每个点,并将它与掩码的边界点数组进行比较,并使用:

shortestDistDil = np.amin(distance.cdist(a, b, 'euclidean'))

找到点和边界点集之间的最小距离。