bordeo bordeo - 7 months ago 12
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

(image_count,height,width,3)


I am adjusting the individual pixels by a random amount I calculated on the side, of shape:
(image_count,3)
.

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

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,:]