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?