我有以下数据:
img
:表示形状为(200,200,256)的高光谱图像的3D numpy阵列,即200 x200像素,每个像素在均匀间隔的波长(波段)处保持256个整数反射率值reference_spectrum
:一个numpy数组,包含256个整数反射率值(类似于单个像素)dist
:一个距离函数,接受两个相同长度的numpy数组并返回一个真实的
我想得到一个2D numpy数组result
,形状为(200,200),使得result[i, j] == dist(img[i, j], reference_spectrum)
。
首先,我写了一个明显的嵌套for循环:
result = np.zeros((img.shape[0], img.shape[1]))
for i in range(img.shape[0]):
for j in range(img.shape[1]):
result[i, j] = dist(img[r, c], reference_spectrum)
这是缓慢的,看起来很丑。
然后我使用距离函数$dist(a,B)= \sum_{i=0}^{n}| a_i-b_i|我写了下面的代码:
temp = np.zeros(img.shape)
for k in range(img.shape[2]):
temp[: , :, k] = abs(img[: , :, k] - reference_spectrum[k])
result = np.sum(temp, axis=2)
这更快,但仅适用于特定的距离函数。
我正在寻找一个快速和模块化(w.r.t.距离函数)解。
1条答案
按热度按时间mefy6pfw1#
可以扩展参照的暗显,并在最后一个暗显上应用操作。例如,假设您想要
mse
错误:还有
numpy.apply_along_axis
,它提供了沿着一个轴应用func的可能性