0

Let's say that we have two numpy ndarrays with shapes:

video.shape = (v, h, w, 3) and image.shape = (h, w, 3)

We also have an array with shape img.shape = (h,w) that is integer and tells me which "frame" v to pick for each position h,w. To do this, one can use the loop:

for j in range(w):
    for i in range(h):
        image[i, j, :] = video[img[i, j], i, j, :]

However, this is very slow. Is it possible to do it without loops? Maybe reshaping the 2D coordinates into one and then reshaping it back?

0

1 Answer 1

3

Here is one straightforward way

import numpy as np

v, h, w = 40, 50, 60

video = np.random.random((v,h,w,3))
img = np.random.randint(0, v, (h, w))

i, j = img.shape
i, j = np.ogrid[:i, :j]

image = video[img, i, j, :]

# check

for j in range(w):
    for i in range(h):
        assert np.all(image[i, j, :] == video[img[i, j], i, j, :])
Sign up to request clarification or add additional context in comments.

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.