0

I have a NumPy array with shape (300, 500). Consider this as an image with size (300, 500) and there are 100 objects on it that I want to fill each of them with a different value.

image = np.zeros((300, 500))

I have bounding-box coordinates (x_min, x_max, y_min, y_max) for each of these objects. Then I create indexing arrays using these bounding-box coordinates.

array_of_x_indexing_arrays = []
array_of_y_indexing_arrays = []

for obj in objects:
   x_indices, y_indices = np.mgrid[obj.x_min: obj.x_max + 1, obj.y_min: obj.y_max + 1]
   x_indices, y_indices = x_indices.ravel(), y_indices.ravel()
   array_of_x_indexing_arrays.append(x_indices)
   array_of_y_indexing_arrays.append(y_indices)

Then, I want to assign a different value to image for each of these objects. I stored them the values for each object in an array with shape (100,)

data = np.array((100,))
# Assume that I filled data such as
# data[0] = 10
# data[1] = 2
# ...
# data[99] = 3

Then what I want to do is following

for i in range(len(objects)):
   image[array_of_y_indexing_arrays[i], array_of_x_indexing_arrays[i]] = data[i]

But I want to do this in NumPy way, I have tried the following but does not work

image[array_of_y_indexing_arrays, array_of_x_indexing_arrays] = data
The Exile
  • 644
  • 8
  • 14
  • Well, this certainly works: `image[30:60,20:90] = pixel`. You just need to convert your rectangles into ranges. – Tim Roberts Nov 25 '21 at 23:04
  • @TimRoberts Yeah but I need to have array of slices (or ranges). I mean, let's say for object1, I want to do this `image[30:60, 20:90] = 2` and for object2 `image[50:85, 0:10] = 4`. How can I do this in a vectorized way, simultaneously? – The Exile Nov 25 '21 at 23:10
  • 1
    You can't do it simultaneously. It's going to take a loop. – Tim Roberts Nov 25 '21 at 23:19
  • 1
    you can use variable `image[y1:y2, x1:x2] = value` and then you can get values from list or array and assign to variables `y1,y2,x1,x2,value` - but it may need `for`-loop – furas Nov 26 '21 at 00:58
  • see accepted solution here: https://stackoverflow.com/questions/66896138/python-numpy-insert-2d-array-into-bigger-2d-array-on-given-posiiton – pippo1980 Nov 27 '21 at 11:57

0 Answers0