1

Given a lookup table:

colors = [  [0,0,0],\
            [0, 255, 0],\
            [0, 0, 255],\
            [255, 0, 0]]

And an index numpy matrix input 2x2:

a = np.array([[0,1],[1,1]])

How can I map a to a 2x2x3 matrix b, where b[i][j] = colors[a[i][j]]? I want to avoid using a for loop here.

1 Answer 1

2

Have you tried:

colors[a]

Here's a full example:

import numpy as np

colors = np.array([[0,0,0],
                   [0, 255, 0],
                   [0, 0, 255],
                   [255, 0, 0]
                  ])
a = np.array([[0, 1], [1, 1]])

new = colors[a]
new.shape
# (2, 2, 3)
new
# array([[[  0,   0,   0],
#         [  0, 255,   0]],
#
#        [[  0, 255,   0],
#         [  0, 255,   0]]])
Sign up to request clarification or add additional context in comments.

2 Comments

Note that you redefine colors here using numpy array otherwise you get an error with "OP colors".
@agstudy, very true. If colors is a list of lists you can only index it using slices or integers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.