【发布时间】:2016-08-20 09:18:20
【问题描述】:
我有一个 2d numpy 数组,我想从中知道落在两个堆叠内核中指定的两个值之间的所有像素的计数。边界应从计数中排除。
例如:
input = np.array([[1, 0, 0, 2, 1],
[0, 2, 1, 1, 7],
[2, 0, 6, 4, 1],
[1, 2, 3, 0, 5],
[6, 5, 4, 3, 2]])
kernel_min=np.array([[0, 1, 0],
[0, 1, 2],
[0, 0, 1]])
kernel_max=np.array([[2, 3, 2],
[2, 2, 4],
[2, 2, 3]])
min_max = np.dstack((kernel_min,kernel_max))
outcome= [[0, 0, 0, 0, 0],
[0, 7, 7, 9, 0],
[0, 8, 8, 8, 0],
[0, 8, 8, 8, 0],
[0, 0, 0, 0, 0]]
为此,我创建了一个循环遍历输入数组中所有元素的脚本。在每个元素周围提取内核大小的区域,并对内核范围内的单元格进行计数。
def create_heatmap(input,min_max):
input_selection=np.zeros(shape(min_max ),dtype='f')
heatmap = np.zeros(shape(input),dtype='uint16')
length,width=shape(input)
center=shape(min_max )[0]/2
#exclude edge pixels
for i in range(0+center,length-center):
for j in range(0+center,width-center):
# Mask area the size of the kernel around the selected cell
input_selection= input[i-center:i+center+1,j-center:j+center+1]
# Count the number of cells within kernel range:
heatmap[i,j]= shape(np.where((input_selection>=min_max [:,:,0]) & (input_selection<=min_max [:,:,1])))[1]
return heatmap`
然而,这种遍历所有元素的循环非常耗时(我有一个巨大的数组)。有没有办法加快两个内核范围内的像素计数?例如,计算所有值的移动窗口函数。
【问题讨论】:
标签: python arrays numpy pandas scipy