bordeo bordeo - 1 year ago 68
Python Question

NumPy Broadcast: Adding an ndarray across elements (a,b) in (M,A,B,N) shaped array

I have an array of images with rgb pixels, so the array has dimensions


I am adjusting the individual pixels by a random amount I calculated on the side, of shape:

Right now, I have an interpreted loop to add the adjustment to the individual pixels.

How do I broadcast this addition so that, for each pixel, I do the following operation:

image_set[i,h,w,:] += pixel_adj[i,:]

Answer Source

Introduce new axes with None/np.newaxis at appropriate dimensions for pixel_adj to make it 4D, just like image_set and then perform the summation adjustment to bring in broadcasting, like so -

image_set += pixel_adj[:,None,None,:]