Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convenient way to apply a lookup table to a large array in numpy?

I’ve got an image read into numpy with quite a few pixels in my resulting array.

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]] 

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.

I know of numpy.vectorize(), it’s simply a convenience function that calls the same python code.

like image 451
Profpatsch Avatar asked Jan 21 '13 23:01

Profpatsch


People also ask

Is NumPy indexing fast?

Indexing in NumPy is a reasonably fast operation.

Why NumPy array operations are faster?

Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.

Can NumPy arrays efficiently store data?

NumPy arrays are efficient data structures for working with data in Python, and machine learning models like those in the scikit-learn library, and deep learning models like those in the Keras library, expect input data in the format of NumPy arrays and make predictions in the format of NumPy arrays.

Which method is used to search for a value in a NumPy array?

You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.


1 Answers

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]]) 

Mind also the indexing starts at 0

like image 167
tzelleke Avatar answered Sep 20 '22 18:09

tzelleke