Boio
Boio

Reputation: 867

Invert structure of array

I have an array representing a video. Currently the way it is set up is the first element is an array of all the values of the first pixel at all the different time steps, then the second element is of the second pixel and so on. I want it so the first element would be an array of all the pixels at the first time step.

So for two frames of a 2x2 video, I would want

[
  [
    [a1, a2, a3], [b1, b2, b3]
  ],
  [
    [c1, c2, c3], [d1, d2, d3]
  ]
]

to become

[
 [
  [a1, b1],
  [c1, d1]
 ],
 [
  [a2, b2],
  [c2, d2]
 ],
 [
  [a3, b3],
  [c3, d3]
 ],
]

My current implementation is this:

def remap_image(seq):
    # seq = np.array(seq)
    s = seq.shape
    a = np.zeros((s[2], s[0], s[1]))

    for x, px in enumerate(tqdm(seq)):
        for y, py in enumerate(px):
            for p_counter, value in enumerate(py):
                a[p_counter][x][y] = value/100.
    return a

This works as intended however this approach is incredibly slow. Is there any faster way to do this?

Upvotes: 0

Views: 92

Answers (3)

Alain T.
Alain T.

Reputation: 42133

I'm not sure it's going to be much faster but you could use zip():

a = [
  [
    ["a1", "a2", "a3"], ["b1", "b2", "b3"]
  ],
  [
    ["c1", "c2", "c3"], ["d1", "d2", "d3"]
  ]
]

b = (list(map(list,zip(*r))) for r in a)
b = list(map(list,zip(*b)))

print(b)

[
 [
    ['a1', 'b1'],
    ['c1', 'd1']
 ],
 [
    ['a2', 'b2'],
    ['c2', 'd2']
 ],
 [
    ['a3', 'b3'],
    ['c3', 'd3']
 ]
]

If your data is in a numpy array, then b = np.transpose(a,axes=(2,0,1)) would do it directly and very fast.

Upvotes: 0

Boio
Boio

Reputation: 867

Following what Mateen Ulhaq said, simply

def remap_image(seq):
    return seq.transpose(2, 0, 1)
    

Upvotes: 0

Yu-Sheng Li
Yu-Sheng Li

Reputation: 94

You can use einops with better semantics. For your case, the following simple code works.

from einops import rearrange

def remap_image(seq):
    return rearrange(seq, 'w h t -> t w h')

Upvotes: 2

Related Questions