dspeyer
dspeyer

Reputation: 3036

Fast way to apply a mapping array to all elements in a numpy array?

Right now, I have code that basically looks like:

for x in range(img.shape[0]):
    for y in range(image.shape[1]):
        output[x,y] = map[ input[x,y] ]

where output, input and map are all numpy arrays (map is size 256, all are type uint8).

This works, but it's slow. Loops like this should be in C. That's what numpy is for.

Is there a numpy function (or a cv2 function, I'm already importing that anyway) that will do this?

Upvotes: 1

Views: 675

Answers (2)

Eelco Hoogendoorn
Eelco Hoogendoorn

Reputation: 10759

How about?

output = map[input]

Upvotes: 3

arra
arra

Reputation: 136

You're looking for np.take which is as simple as map.take(input). Both this and Eelco's solution are much faster than yours; this is about 70 percent faster than Eelco's system though your mileage may vary, and for input.shape >> (1e4, 1e4) you'll need a better solution.

One place to start is [Performance of various numpy fancy indexing methods, also with numba] (Performance of various numpy fancy indexing methods, also with numba) which details various performance-related facts for this generic problem (i.e. how do we use one k-dimensional array to index some other n-dimensional array in more than just trivial ways).

If you have something like Anaconda installed, you could try to use Numba to jit np.ndarray.take(...) and see how much performance you can buy. The link above explains this as well.

Upvotes: 0

Related Questions