1

I have

  • an (height x width x 3) RGB image img
  • a (256 x 256 x 256) matrix color_mapping mapping colors
  • a (height x width) matrix pixel_result which I want to fill with the elements mapped with color_mapping for each pixel of the image

How can I fill that last matrix efficiently?

So far, I simply run through all the pixels in for loops, but I'm wondering if there is a more efficient way to do it

for i in range(width):
    for j in range(height):
        pixel_result[j,i] = color_mapping[img[j,i,0],img[j,i,1],img[j,i,2]]

1 Answer 1

1

You can implement this by subscripting the color_mapping:

pixel_result = color_mapping[img[:,:,0], img[:,:,1], img[:,:,2]]

For example if test the performance with:

>>> def f():
...   for i in range(width):
...     for j in range(height):
...         pixel_result[j,i] = color_mapping[img[j,i,0],img[j,i,1],img[j,i,2]]
... 
>>> def g():
...     pixel_result = color_mapping[img[:,:,0], img[:,:,1], img[:,:,2]]
>>> color_mapping = np.random.randn(256,256,256)

Then for a small image: img = np.random.randint(0, 256, (12, 7, 3)), we get:

>>> timeit(f, number=10000)
0.5247259399620816
>>> timeit(g, number=10000)
0.032307324931025505

For larger images, like img = np.random.randint(0, 256, (1920, 1080, 3)), we get:

>>> timeit(f, number=10)
18.934733690926805
>>> timeit(g, number=10)
0.5807857210747898

or for a 72×128 image:

>>> timeit(f, number=100)
0.6014469779329374
>>> timeit(g, number=100)
0.011570235947147012
Sign up to request clarification or add additional context in comments.

6 Comments

It's actually 15 times slower
@user3548298: the assignment is of course done once, so not in a for loop. I've tested this for both small and large images, and got a speedup of approximately 32 for large images, and 16 for small images.
Oh ... right I'm an idiot... I forgot to take it out of the loop
@user3548298: you noticed that there are two loops that you need to remove? :) I got a speedup of 52x for that.
@user3548298: not with numpy. Here I used floating point values as well (notice that np.random.randn(..)). You can try to use a tool like cudamap to process this on a GPU.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.