Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[[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

>Solution :

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],    # int.from_bytes(bytes([  1, 105,  15,  26]), 'little') == 437217537
        [ 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading