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
5
  • Well, this certainly works: image[30:60,20:90] = pixel. You just need to convert your rectangles into ranges. Commented Nov 25, 2021 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? Commented Nov 25, 2021 at 23:10
  • 1
    You can't do it simultaneously. It's going to take a loop. Commented Nov 25, 2021 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 Commented Nov 26, 2021 at 0:58
  • see accepted solution here: stackoverflow.com/questions/66896138/… Commented Nov 27, 2021 at 11:57

0

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.