我经常想要像素桶/像素桶一个numpy数组,这意味着,用单个像素替换N连续像素组,这是N替换像素的总和。例如,从值开始:
x = np.array([1, 3, 7, 3, 2, 9])如果桶大小为2,则转换为:
bucket(x, bucket_size=2)
= [1+3, 7+3, 2+9]
= [4, 10, 11]据我所知,没有numpy函数专门这样做(如果我错了,请纠正我),所以我经常使用自己的函数。对于一维numpy数组,这并不坏:
import numpy as np
def bucket(x, bucket_size):
return x.reshape(x.size // bucket_size, bucket_size).sum(axis=1)
bucket_me = np.array([3, 4, 5, 5, 1, 3, 2, 3])
print(bucket(bucket_me, bucket_size=2)) #[ 7 10 4 5]...however,我很容易被多维案例弄糊涂了,最后我一次又一次地把我自己的“容易”问题的解决方案翻了个底朝天。如果我们能建立一个很好的N维参考实现,我会很高兴的。
bucket(x, bucket_size=(2, 2, 3)))的不同的bin大小。正如Divakar所建议的,下面是我想要的2-D示例中的行为:
x = np.array([[1, 2, 3, 4],
[2, 3, 7, 9],
[8, 9, 1, 0],
[0, 0, 3, 4]])
bucket(x, bucket_size=(2, 2))
= [[1 + 2 + 2 + 3, 3 + 4 + 7 + 9],
[8 + 9 + 0 + 0, 1 + 0 + 3 + 4]]
= [[8, 23],
[17, 8]]...hopefully我的算术做得很正确;)
发布于 2016-03-28 20:02:47
要为ndarray案例的每个轴指定不同的装箱大小,可以在每个轴上迭代地使用np.add.reduceat,如下所示-
def bucket(x, bin_size):
ndims = x.ndim
out = x.copy()
for i in range(ndims):
idx = np.append(0,np.cumsum(bin_size[i][:-1]))
out = np.add.reduceat(out,idx,axis=i)
return out样本运行-
In [126]: x
Out[126]:
array([[165, 107, 133, 82, 199],
[ 35, 138, 91, 100, 207],
[ 75, 99, 40, 240, 208],
[166, 171, 78, 7, 141]])
In [127]: bucket(x, bin_size = [[2, 2],[3, 2]])
Out[127]:
array([[669, 588],
[629, 596]])
# [2, 2] are the bin sizes along axis=0
# [3, 2] are the bin sizes along axis=1
# array([[165, 107, 133, | 82, 199],
# [ 35, 138, 91, | 100, 207],
# -------------------------------------
# [ 75, 99, 40, | 240, 208],
# [166, 171, 78, | 7, 141]])
In [128]: x[:2,:3].sum()
Out[128]: 669
In [129]: x[:2,3:].sum()
Out[129]: 588
In [130]: x[2:,:3].sum()
Out[130]: 629
In [131]: x[2:,3:].sum()
Out[131]: 596https://stackoverflow.com/questions/36269508
复制相似问题