Clamping by image shape: replace X,Y coordinates by different rules in Numpy array

Viewed 384

I have a picture of shape (225, 400, 3) and a set of x,y coordinates:

polygon = np.array([[150, 80], [350, 80], [420, 280], [350, 250], [150, 250]], np.int32)

I want to clamp those values to dimensions of my image, so any given pair of coordinates won't be outside of my image. This means that I need to replace all x-coordinates [X > 400, ...] with 400 and all y-coordinates [..., Y > 225] with 225.

I tried to replace all Y coordinates greater than 255 without success, it also clamps X coordinates.

polygon[(polygon > 225).all(axis=1)] = 225

What's the correct way of clamping Numpy array values by different rules in this case?

2 Answers

IIUC and by coordinates you mean that each row contains a (x,y) coordinate (note that this is not the same as axis), then you can index and use clip:

polygon[:,0] = polygon[:,0].clip(max=400)
polygon[:,1] = polygon[:,1].clip(max=255)

print(polygon)

array([[150,  80],
       [350,  80],
       [400, 255],
       [350, 250],
       [150, 250]])

You can use np.where:

polygon[:,0]  = np.where(polygon[:,0] > 400, 400, polygon[:,0])
polygon[:,1]  = np.where(polygon[:,1] > 225, 225, polygon[:,1])

You will obtain the next output:

array([[150,  80],
       [350,  80],
       [400, 225],
       [350, 225],
       [150, 225]])
Related