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.

asked Jun 20, 2014 at 0:08

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]]])
answered Jun 20, 2014 at 0:15
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.