Search code examples
pythonmatrixrotationmatrix-multiplicationimage-rotation

Matrix rotation with multiple values


I am using Python 3.7.1.

Given the following one dimensional array (of numbers in the range -1000 to 1000):

[x00,y00,z00, x10,y10,z10, x20,y20,z20, x30,y30,z30,
 x01,y01,z01, x11,y11,z11, x21,y21,z21, x31,y31,z31,
 x02,y02,z02, x12,y12,z12, x22,y22,z22, x32,y32,z32]

I want to use this rotation matrix to rotate.

|0 -1|
|1  0|

Wanted output:

[x30,y30,z30, x31,y31,z31, x32,y32,z32,
 x20,y20,z20, x21,y21,z21, x22,y22,z22,
 x10,y10,z10, x11,y11,z11, x12,y12,z12,
 x00,y00,z00, x01,y01,z01, x02,y02,z02]

I know how this can be done on a normal array, but I want to keep the x, y and z values grouped.


Solution

  • I have been able to do it using @DatHydroGuy suggestion about numpy.rot90. Here is an examples of how to do it. Note that I first group the x,y,z values in tuples within the list. Then create a numpy array of tuples as objects, rotate it, then flatten the array into a list using list comprehension.

    import numpy as np
    
    a = [5, 0, 3, 3, 7, 9, 3, 5, 2, 4, 7, 6, 8, 8, 1, 6, 7, 7, 8, 1, 5, 9, 8, 9, 4, 3, 0, 3, 5, 0, 2, 3, 8, 1, 3, 3]
    sh = (4,3) # Shape
    
    a_tup = [tuple(a[i:i+3]) for i in range(0, len(a), 3)] # Group list into tuples (x,y,z)
    print(a_tup)
    # [(5, 0, 3), (3, 7, 9), (3, 5, 2), (4, 7, 6), (8, 8, 1), (6, 7, 7), (8, 1, 5), (9, 8, 9), (4, 3, 0), (3, 5, 0), (2, 3, 8), (1, 3, 3)]
    b=np.empty(sh, dtype=object) # Initialize numpy array with object as elements (for the tuples) and your shape sh
    for j in range(sh[1]): # Assign tuples from list  to positions in the array
      for i in range(sh[0]):
        b[i,j] = a_tup[i+j]
    print(b)
    # [[(5, 0, 3) (3, 7, 9) (3, 5, 2)]
    #  [(3, 7, 9) (3, 5, 2) (4, 7, 6)]
    #  [(3, 5, 2) (4, 7, 6) (8, 8, 1)]
    #  [(4, 7, 6) (8, 8, 1) (6, 7, 7)]]
    c = np.rot90(b)
    print(c)
    # [[(3, 5, 2) (4, 7, 6) (8, 8, 1) (6, 7, 7)]
    #  [(3, 7, 9) (3, 5, 2) (4, 7, 6) (8, 8, 1)]
    #  [(5, 0, 3) (3, 7, 9) (3, 5, 2) (4, 7, 6)]]
    print([item for sublist in c.flatten() for item in sublist]) # Flatten the numpy array of tuples to a list of numbers
    # [3, 5, 2, 4, 7, 6, 8, 8, 1, 6, 7, 7, 3, 7, 9, 3, 5, 2, 4, 7, 6, 8, 8, 1, 5, 0, 3, 3, 7,9, 3, 5, 2, 4, 7, 6]