2

I want to create a batch of zero images with several channels and with some one given pixel per image with value one.

If the images are indexed only by the number of channels, the following code do the work just fine:

num_channels = 3
im_size = 2
images = np.zeros((num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                           size=(num_channels, 2))
images[np.arange(num_channels), pixels[:, 0], pixels[:, 1]] = 1

However, the analogous code fails if we want to consider the batch too:

batch_size = 4
num_channels = 3
im_size = 2
images = np.zeros((batch_size, num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                           size=(batch_size, num_channels, 2))
images[np.arange(batch_size), np.arange(num_channels), pixels[:, :, 0], pixels[:, :, 1]] = 1

which gives the error

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (4,) (3,) (4,3) (4,3) 

The following code will do the work, using an inefficient loop:

batch_size = 4
num_channels = 3
im_size = 2
images = np.zeros((batch_size, num_channels, im_size, im_size))

# random locations for the ones
pixels = np.random.randint(low=0, high=im_size,
                       size=(batch_size, num_channels, 2))
for k in range(batch_size):
    images[k, np.arange(num_channels), pixels[k, :, 0], pixels[k, :, 1]] = 1

How would you obtain a vectorized solution?

1 Answer 1

1

A simple vectorized using advanced-indexing would be -

I,J = np.arange(batch_size)[:,None],np.arange(num_channels)
images[I, J, pixels[...,0], pixels[...,1]] = 1

Alternative easier way to get those I,J indexers would be with np.ogrid -

I,J = np.ogrid[:batch_size,:num_channels]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I had no idea of the existence of this advanced-indexed stuff! Sorry my reputation is so low I cannot upvote you.

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.