numpy efficient method to create grids around points

Viewed 154

I'm trying to add black boxes to a numpy RGB image frame array with the shape (4000,4000,3). The center x,y points of the black boxes are in a second numpy array shape (100,2). My issue is I don't know an efficient way in numpy to create a third array of all points that I want to color black that are x,y +/- 2 for every box center point in the second array.

1 Answers

The idea is to create all the coordinates by offsetting the points' coordinates. Let's try broadcasting:

size = 4000

from itertools import product
nbhds = np.array([list(product(np.arange(-2,3), np.arange(-2,3)))])

s = (nbhds + points[:,None] ).reshape(-1,2).clip(0,size-1)
frame[s[:,0], s[:,1]] = 0

Trying the above on a small sample:

size = 100
frame = np.ones((size,size,3)).astype("uint8")*255 
np.random.seed(42)
points = np.random.randint(0,size,(100,2))

gives:

enter image description here

Related