有没有一种方便的方法可以将查找表应用于 numpy 中的大型数组? [英] Is there a convenient way to apply a lookup table to a large array in numpy?
问题描述
我已将一张图像读入 numpy,结果数组中有相当多的像素.
I’ve got an image read into numpy with quite a few pixels in my resulting array.
我计算了一个包含 256 个值的查找表.现在我想做以下事情:
I calculated a lookup table with 256 values. Now I want to do the following:
for i in image.rows:
for j in image.cols:
mapped_image[i,j] = lut[image[i,j]]
是的,这基本上就是 lut 所做的.
唯一的问题是:我想高效地完成它,在 python 中调用该循环会让我等待几秒钟才能完成.
Yep, that’s basically what a lut does.
Only problem is: I want to do it efficient and calling that loop in python will have me waiting for some seconds for it to finish.
我知道numpy.vectorize()
,它只是一个调用相同python代码的便捷函数.
I know of numpy.vectorize()
, it’s simply a convenience function that calls the same python code.
推荐答案
如果 lut
是一维.
这是在 NumPy 中建立索引的入门:
http://www.scipy.org/Tentative_NumPy_Tutorial8604c88c88608c8c8c8c8c8c8c8c8c8c8c8c8c8c8c8c8c8c5c8c4d
You can just use image
to index into lut
if lut
is 1D.
Here's a starter on indexing in NumPy:
http://www.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c
In [54]: lut = np.arange(10) * 10
In [55]: img = np.random.randint(0,9,size=(3,3))
In [56]: lut
Out[56]: array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [57]: img
Out[57]:
array([[2, 2, 4],
[1, 3, 0],
[4, 3, 1]])
In [58]: lut[img]
Out[58]:
array([[20, 20, 40],
[10, 30, 0],
[40, 30, 10]])
请注意索引从 0
这篇关于有没有一种方便的方法可以将查找表应用于 numpy 中的大型数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!