0

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?

3
  • Looks like you have a (2,2,3) shape, and you want to transpose to (3,2,2) Commented Aug 28, 2021 at 5:22
  • 1
    seq.transpose(2, 0, 1) Commented Aug 28, 2021 at 5:27
  • @MateenUlhaq works perfectly, thanks! Commented Aug 28, 2021 at 5:38

3 Answers 3

2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Cool package. Apparently I've starred it but never used it after that. It is an additional dependency after all.
0

Following what Mateen Ulhaq said, simply

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.