寻找分段区域的极大值

3

我有两个相同维度的3D灰度图像。

第一张图像(img)是三维体积的原始数据(使用显微镜获得),包含各种细胞。原始3D图像示例切片

第二张图像(imglab)是原始图像的掩膜版本,其中每个已识别的细胞都被填充了一个单独的唯一值(即细胞1 = 全部为1,细胞2 = 全部为2)。所有非细胞区域均为零。掩膜3D图像示例切片

我现在正在尝试找到与标记掩码数组对应的原始数据中每个细胞的最大值的坐标。

目前,我有一个极其低效的循环。我怀疑有一种方法可以使用单个np.where调用设置多个条件,但我无法弄清楚如何做到这一点。当前的for循环方法如下:

coordinates = []
for i in range(1, int(imglab.max())): # Number of cells = max value of label image
    max_val = np.max(img[imglab == i])
    max_coord = np.where((img == max_val) & (imglab == i))
    coordinates.append(max_coord)

使用regionprops:http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops - Cris Luengo
1个回答

0

当编写高效且与numpy兼容的代码变得困难时,但使用for循环的代码却很简单,您可以使用numba中的njit

它最适合处理平坦数组,因此首先让我们在numba中编写一个函数,以1d的方式执行您要求的操作:

from numba import njit, int64

@njit
def fast_max_flat(img_flat, imglab_flat):
    n_cells =int(imglab_flat.max())  # number of cells
    max_values = np.full(n_cells, - np.inf)  # stores the n_cells max values seen so far
    max_coords = np.zeros(n_cells, dtype=int64)  # stores the corresponding coordinate
    n_pixels = len(img)
    for i in range(n_pixels):
        label = imglab_flat[i]
        value = img_flat[i]
        if max_values[label] < value:
            max_values[label] = value
            max_coords[label] = i
    return max_coords

然后编写一个Python包装器,将数组展平,应用先前的函数,并将坐标作为列表检索:
def wrapper(img, imglab):
    dim = img.shape
    coords = fast_max_flat(img.ravel(), imglab.ravel())
    return [np.unravel_index(coord, dim) for coord in coords]

在我的电脑上,使用一个大小为100 x 100 x 100的3个单元格图像,这种方法比您的方法快大约50倍。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接