【发布时间】:2017-04-10 19:07:58
【问题描述】:
我有一个数组的中心点,
center_point = (array.shape[0]/2.,array.shape[1]/2.)
我有一个二进制图像数组array,它的形状相关像素设置为 0(所有其他像素为 255)。
对于所有设置为零的像素,我需要到数组中心的平均距离,并且我需要对其进行矢量化(它不能在 python 级别解释——速度很慢)。
这就是我所拥有的,现在我被卡住了,因为我找到的其他答案指向 SciPy,但服务器 only 支持 numpy。
centerpoint = array_center_point(shape_array)
distance_shape = np.zeros(size=shape_array.shape,dtype=float)
distance_shape[shape==0] = ...???
avg_distance = np.sum(distance_shape) / len(np.where(shape_array == 0)[0])
如果不多次调用 np.where 并使用 python for 循环遍历形状索引,我无法弄清楚如何做到这一点。一定有办法在 numpy 代码中完成这项工作...??
这是有效的非矢量化版本:
def avg_distance_from_center(shape_array):
center_point = array_center_point(shape_array)
distance_shape = np.zeros(shape=shape_array.shape, dtype=float)
shape_pixels = np.where(shape_array == 0)
total_distance = 0.
for i in range(len(shape_pixels[0])):
i_ind = float(shape_pixels[0][i])
j_ind = float(shape_pixels[1][i])
total_distance += ((i_ind - center_point[0])**2.0 + (j_ind - center_point[1])**2.0)**0.5
avg_distance = total_distance / len(shape_pixels[0])
return avg_distance
【问题讨论】:
-
编写一个我们可以尝试矢量化的有效循环实现?
-
@Divakar 好的,会的……等一下
-
如果你说“只有 numpy”是否包括 cython(构建依赖)?
-
@MSeifert 基本上,如果代码有标题,
import numpy as np它将在服务器上运行。除此之外,我不能说。将在几秒钟内建立循环版本
标签: python arrays performance numpy vectorization