Home > Enterprise >  How do I convert a matrix of integers to a matrix of lists of integers in numpy?
How do I convert a matrix of integers to a matrix of lists of integers in numpy?

Time:09-13

I'm quite new to numpy, I tried with vstack but it seems really wrong since it creates a copy in memory everytime.

The initial structure is:

[[1,2,3],     
 [1,2,3],
 [1,2,3]]

and it will be mapped to:

[[[3,2,1,2], [4,5,2,7], [7,4,1,3]],
 [[3,2,1,2], [4,5,2,7], [7,4,1,3]],
 [[3,2,1,2], [4,5,2,7], [7,4,1,3]]]

The numbers here don't have any meaning, it's just to show the structure, basically each integer is decoded to a list of integers N -> [N_1, N_2, N_3, N_4]

For context I have pixels encoded in 32bits and I have to decode them to argb

CodePudding user response:

Create uint8 view:

>>> ar = np.random.randint(0, 2 ** 31, (3, 3))
>>> ar
array([[ 437217537,  524850213,  771706759],
       [ 467263015,  219221544, 1712453711],
       [1444860139,  625411292, 1224272631]])
>>> ar[1:] = ar[0]    # make the layout the same as the example of OP
>>> ar
array([[437217537, 524850213, 771706759],
       [437217537, 524850213, 771706759],
       [437217537, 524850213, 771706759]])
>>> ar.view(np.uint8).reshape(3, 3, -1)
array([[[  1, 105,  15,  26],
        [ 37, 148,  72,  31],
        [135,  79, 255,  45]],

       [[  1, 105,  15,  26],
        [ 37, 148,  72,  31],
        [135,  79, 255,  45]],

       [[  1, 105,  15,  26],
        [ 37, 148,  72,  31],
        [135,  79, 255,  45]]], dtype=uint8)
>>> int.from_bytes(bytes(_[0, 0]), 'little') == ar[0, 0]
True
  • Related