how can i split a three dimensional list into a two diensional list in python

Viewed 97

how can i write a function that receives an image (three-dimensional list) which channels X columns X rows and returns a three-dimensional list, Whose dimensions are columns X rows X channels, that is, a list of two-dimensional images that each represent a color channel Single. for example: how i can split this list:

[[[1,2,3],[4,5,6],[17,18,19],[21,22,23]],[[7,8,9],[10,11,12],[17,18,19],[21,22,23]]]

to get this list:

[[[1,4,17,21],[7,10,17,21]],[[2,5,18,22],[8,11,18,22]],[[3,6,19,23],[9,12,19,23]]]
3 Answers

You can use below:

first_array = [[[1,2,3],[4,5,6],[17,18,19],[21,22,23]],[[7,8,9],[10,11,12],[17,18,19],[21,22,23]]]
result = []
len_x = len(first_array)  # number of items in array
len_y = len(first_array[0][0])  # number of items in first element
for iy in range(len_y):
    elem = []  # to create brand new array for below for loop
    for ix in range(len_x):
        elem.append([y[iy] for y in first_array[ix]])  # append only what we need from the inner array
    result.append(elem)
print(result)

This is not the most effective/performant way to achieve it but I tried to keep it simple for you. Python is a powerful language, there are numerous ways to solve any problem.

You can use numpy to achieve this transformation:

import numpy as np

data = [
 [[1, 2, 3], [4, 5, 6], [17, 18, 19], [21, 22, 23]],
 [[7, 8, 9], [10, 11, 12], [17, 18, 19], [21, 22, 23]]
]

out = np.transpose(data, axes=[2, 0, 1])

print(out)
array([[[ 1,  4, 17, 21],
        [ 7, 10, 17, 21]],

       [[ 2,  5, 18, 22],
        [ 8, 11, 18, 22]],

       [[ 3,  6, 19, 23],
        [ 9, 12, 19, 23]]])

Check the output:

expected_result = np.asarray([
  [[1,4,17,21],[7,10,17,21]],
  [[2,5,18,22],[8,11,18,22]],
  [[3,6,19,23],[9,12,19,23]]
])

>>> np.allclose(out, expected_result)
True

In case you could use numpy, here is a simple solution:

import numpy as np
output = np.moveaxis(x, 0, -1)
Related