Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm new to numpy and trying to understand the following example from here. I'm having trouble understanding the output of

>>> palette[image] 

When the indexed array a is multidimensional, a single array of indices refers to the first dimension of a. The following example shows this behavior by converting an image of labels into a color image using a palette.

>>> palette = array( [ [0,0,0],                # black
...                    [255,0,0],              # red
...                    [0,255,0],              # green
...                    [0,0,255],              # blue
...                    [255,255,255] ] )       # white
>>> image = array( [ [ 0, 1, 2, 0 ],           # each value corresponds to a color in the palette
...                  [ 0, 3, 4, 0 ]  ] )
>>> palette[image]                            # the (2,4,3) color image
array([[[  0,   0,   0],
        [255,   0,   0],
        [  0, 255,   0],
        [  0,   0,   0]],
       [[  0,   0,   0],
        [  0,   0, 255],
        [255, 255, 255],
        [  0,   0,   0]]])
share|improve this question

2 Answers 2

up vote 2 down vote accepted

You are creating a 3D array, where first 2D array (withing 3D array) is given by extracting rows from palette as given by indices of image[0] and the second array is given by extracting rows from palette as given by indices of image[1].

>>> palette = array( [ [0,0,0],                # black
...                    [255,0,0],              # red
...                    [0,255,0],              # green
...                    [0,0,255],              # blue
...                    [255,255,255] ] )       # white
>>> image = array( [ [ 0, 1, 2, 0 ],           # each value corresponds to a color in the palette
...                  [ 0, 3, 4, 0 ]  ] )
>>> palette[image]                            # the (2,4,3) color image
array([[[  0,   0,   0], # row at index 0 of palete
        [255,   0,   0], # index 1
        [  0, 255,   0], # index 2
        [  0,   0,   0]], # index 0
       [[  0,   0,   0], # index 0
        [  0,   0, 255], # index 3
        [255, 255, 255], # index 4
        [  0,   0,   0]]]) # index 0
share|improve this answer

This might help you understand:

array([[[  0,   0,   0],   # palette[0]
        [255,   0,   0],   # palette[1]
        [  0, 255,   0],   # palette[2]
        [  0,   0,   0]],  # palette[0]

       [[  0,   0,   0],   # palette[0]
        [  0,   0, 255],   # palette[3]
        [255, 255, 255],   # palette[4]
        [  0,   0,   0]]]) # palette[0]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.