Home > Mobile >  Create numpy array with shape of one array and values from a list
Create numpy array with shape of one array and values from a list

Time:05-23

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.

CodePudding user response:

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]])

CodePudding user response:

I would use the numpy.where function for this:

from numpy import *
arr1=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]).reshape((9,9,))
arr2=array([0, 1, 0, 0, 0, 1, 0, 1])
for i in range(len(arr2)):
    arr1=where(arr1==i,arr2[i],arr1)

The arr1 array wil contain the output.

  • Related