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

后端 未结 3 1651
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 03:56

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:

3条回答
  •  生来不讨喜
    2020-12-15 04:10

    TheodrosZelleke's answer in correct, but I just wanted to add a little undocumented wisdom to it. Numpy provides a function, np.take, which according to the documentation "does the same thing as fancy indexing."

    Well, almost, but not quite the same:

    >>> import numpy as np
    >>> lut = np.arange(256)
    >>> image = np.random.randint(256, size=(5000, 5000))
    >>> np.all(lut[image] == np.take(lut, image))
    True
    >>> import timeit
    >>> timeit.timeit('lut[image]',
    ...               'from __main__ import lut, image', number=10)
    4.369504285407089
    >>> timeit.timeit('np.take(lut, image)',
    ...               'from __main__ import np, lut, image', number=10)
    1.3678052776554637
    

    np.take is about 3x faster! In my experience, when using 3D luts to convert images from RGB to other color spaces, adding logic to convert the 3D look-up to a 1D flattened look-up allows a x10 speed up.

提交回复
热议问题