setting values on multiple indexes in a numpy array

Viewed 406

I have the following fragment of python code:

import numpy as np


# Some random array
x = np.random.rand(34, 176, 256)
# Get some indexes
pos_idx = np.argwhere(x > 0.5)
# Sample some values from these indexes
seeds = pos_idx[np.random.choice(pos_idx.shape[0], size=5, replace=False), :]
# Now create another array
y = np.zeros_like(x, np.uint8)
y[seeds] = 1

The last line given an error something along the lines of:

index 77 is out of bounds for axis 0 with size 34

But I am not sure how this can happen as all the sampled indexes should be valid as they are a subset.

3 Answers

It considers the values in seeds as indexes of the first dimension. To access the elements by their indexes in seeds, you can use:

y[seeds[:,0],seeds[:,1],seeds[:,2]] = 1

This code will help you setting the values to 1

import numpy as np

# Some random array
x = np.random.rand(34, 176, 256)
# Get some indexes
pos_idx = np.argwhere(x > 0.5)
# Sample some values from these indexes
seeds = pos_idx[np.random.choice(pos_idx.shape[0], size=5, replace=False), :]
# Now create another array
y = np.zeros_like(x, np.uint8)
for i in seeds:
    y[tuple(i)] = 1

Does seeds have the right shape? If I understand correctly, x has random values; y has the same shape as x but is all zeros; and seeds is some index values, and these locations will be set to one.

print('x    : ', x.ndim, x.shape)
print('y    : ', y.ndim, y.shape)
print('seeds: ', seeds.ndim, seeds.shape)

x    :  3 (34, 176, 256)
y    :  3 (34, 176, 256)
seeds:  2 (5, 3)
Related