是的,这是可以做到的,但是需要大量使用
np.broadcasting
.
生成数据和
I
:
import time
N = 10000
q = 28
P = q*q
ps = 3
I = np.random.rand(N,P)
IDX = np.random.randint(0,P,(N,1))
I_copy = I.copy()
现在运行循环解决方案。我切换
x0
和
y0
:
t0=time.clock()
for i in range(N):
img = I[i].reshape(q,q)
x0, y0 = np.unravel_index(IDX[i,0],(q,q))
for x in range(ps):
for y in range(ps):
if (x0+x < q) and (y0+y < q):
img[x0+x,y0+y] = 2.0
I[i] = img.reshape(1,q*q)
print('With loop: {:.2f} ms'.format(time.clock()*1e3-t0*1e3))
在我的机器上大约276毫秒。现在广播:
t0 = time.clock()
x_shift, y_shift = np.meshgrid(range(ps), range(ps))
x, y = np.unravel_index(IDX, (q,q))
#roi for region of interest
roix = x[:,:,None]+x_shift;
roiy = y[:,:,None]+y_shift;
roix[roix>q-1] = q-1; roiy[roiy>q-1] = q-1;
I_copy.reshape(N,q,q)[np.arange(N)[:, None, None], roix, roiy] = 2.0
print('No loop: {:.2f} ms'.format(time.clock()*1e3-t0*1e3))
print(np.array_equal(I, I_copy))
大约快80倍