我有三个阵列,一个src
形状的阵列(width, height, 3)
,一个template
形状的阵列(640, 480, 3)
和img_map
形状的阵列(width, height, 2)
。
img_map
存储src
和之间的x,y关系template
,即src[4, 5] = template[img_map[0,4,5], img_map[1,4,5]]
。当映射建议的索引超出范围时,将不会分配任何值。
如何在不使用python的numpy的for循环的情况下实现这种值分配?
使用for循环将是这样,但是它太慢了。
for x in range(0, width):
for y in range(0, height):
u = img_map[x,y,0]
v = img_map[x,y,1]
if (u >= 0) and (v >= 0) and (u < 640) and (v < 480):
src[x,y,:] = template[u,v,:]
这是一个应该执行此任务的衬板版本:
src = template[img_map[:,:,0].ravel(),img_map[:,:,1].ravel(),:].reshape((width,height,3))
这是一个验证结果准确性并评估性能改进的小代码:
import numpy as np
import time
# Preparation of testdata
(width, height, depth) = (1000, 1000, 3)
template = np.random.randint(0, 256, (640,480,depth))
img_map = np.concatenate((
np.random.randint(0, template.shape[0], (width*height,1)),
np.random.randint(0, template.shape[1], (width*height,1))
), axis=1
).reshape(width,height,2)
# For loop verion
t_start = time.time()
src = np.zeros((img_map.shape[0],img_map.shape[1],template.shape[2]))
for x in range(0, img_map.shape[0]):
for y in range(0, img_map.shape[1]):
u = img_map[x,y,0]
v = img_map[x,y,1]
if (u >= 0) and (v >= 0) and (u < template.shape[0]) and (v < template.shape[1]):
src[x,y,:] = template[u,v,:]
print(f'Timer 1: {time.time()-t_start}s')
# One line version
t_start = time.time()
src2 = template[img_map[:,:,0].ravel(),img_map[:,:,1].ravel(),:].reshape((width,height,depth))
print(f'Timer 2: {time.time()-t_start}s')
# Verify that both gives the same result
print('Results are equal' if np.linalg.norm(src-src2)==0 else 'Results differ')
结果是相等的,并且执行时间大大缩短:
% python3 script.py
Timer 1: 2.7333829402923584s
Timer 2: 0.0499570369720459s
Results are equal
如有任何疑问,请不要犹豫。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句