加速应用于numpy 3d的scipy ndimage测量

2024-04-19 18:50:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个大的标记为numpy2d数组(10000x10000)。对于每个标签(具有相同编号的连接单元格),我想根据另一个numpy三维数组(mean、std、max等)的值计算多个测量值。这是有可能的scipy.ndimage.labeld_理解工具,如果3-d numpy转换为2-d,但是,由于标签的数量和数组的大小相当大,计算需要相当长的时间。我当前的代码似乎是多余的,因为我现在迭代输入图像的每个三维的相同标签。我想知道是否有方法来加速我的代码(例如,将这三种方法结合起来scipy.ndimage.labeld_理解计算到单个计算中)。在

使用shape(42003000,3)和283047个标签的测试数据集,计算花费了10:34分钟


测试数据

example_labels=np.array([[1, 1, 3, 3],
   [1, 2, 2, 3],
   [2, 2, 4, 4],
   [5, 5, 5, 4]])

unique_labels=np.unique(example_labels)
value_array=np.arange(48).reshape(4,4,3)

当前代码和期望输出

^{pr2}$

Tags: 方法代码标记numpylabelsexamplenpscipy
1条回答
网友
1楼 · 发布于 2024-04-19 18:50:24

在处理大型阵列时,mean_std_测量的附加列表可能会形成一个瓶颈。labeled_comprehension将单独返回一个数组,因此第一步是让scipy在幕后处理数组构造。在

labeled_comprehension只能应用输出单个值的函数-我怀疑这就是为什么您首先使用列表结构-但是我们可以通过让函数输出一个复杂值来欺骗这一点。另一个选择是使用结构化数据类型作为输出,如果返回的值超过2个,这将是必需的。在

import numpy as np
from scipy import ndimage
example_labels=np.array([[1, 1, 3, 3],
   [1, 2, 2, 3],
   [2, 2, 4, 4],
   [5, 5, 5, 4]])

unique_labels=np.unique(example_labels)
value_array=np.arange(48).reshape(4,4,3)
# return a complex number to get around labled_comprehension limitations
def mean_std_measurement(x):
    xmean = x.mean()
    xstd = x.std()
    return np.complex(xmean, xstd)

def calculate_measurements(labels, unique_labels, value_array):
    val1 = ndimage.labeled_comprehension(value_array[:,:,0],labels,unique_labels,mean_std_measurement,np.complex,-1)
    val2 = ndimage.labeled_comprehension(value_array[:,:,1],labels,unique_labels,mean_std_measurement,np.complex,-1)
    val3 = ndimage.labeled_comprehension(value_array[:,:,2],labels,unique_labels,mean_std_measurement,np.complex,-1)
    # convert the complex numbers back into reals
    return np.column_stack((np.unique(labels),
                            val1.real,val1.imag,
                            val2.real,val2.imag,
                            val3.real,val3.imag))

相关问题 更多 >