'Create numpy array with shape of one array and values from a list

I have a (128x128) array consisting of values of which cluster/super-pixel each pixel belongs to, small 9x9 example:

array([[0, 0, 1, 1, 1, 2, 2, 2, 2],
       [0, 0, 1, 1, 1, 2, 2, 2, 2],
       [0, 0, 1, 1, 1, 2, 2, 2, 2],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [5, 5, 5, 6, 6, 6, 7, 7, 7],
       [5, 5, 5, 6, 6, 6, 7, 7, 7],
       [5, 5, 5, 6, 6, 6, 7, 7, 7]])

I then have a list with the length of the number of super pixels(cluster), e.g:

[0, 1, 0, 0, 0, 1, 0, 1]

I now want to create a new (128,128) array where the value in the list replaces all the pixel values in the corresponding super-pixel(cluster), for this example:

array([[0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 1, 1]])

To clarify, if the first item in the list == 1 I want to create a new (128,128) array where the values which are == to the list index is replacd with the value in my list at that index.



Solution 1:[1]

Use the original array as the index of the mapping array:

>>> arr
array([[0, 0, 1, 1, 1, 2, 2, 2, 2],
       [0, 0, 1, 1, 1, 2, 2, 2, 2],
       [0, 0, 1, 1, 1, 2, 2, 2, 2],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [3, 3, 3, 3, 4, 4, 4, 4, 4],
       [5, 5, 5, 6, 6, 6, 7, 7, 7],
       [5, 5, 5, 6, 6, 6, 7, 7, 7],
       [5, 5, 5, 6, 6, 6, 7, 7, 7]])
>>> mapping = np.array([0, 1, 0, 0, 0, 1, 0, 1])
>>> mapping[arr]
array([[0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 1, 1]])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mechanic Pig