Home > Net >  Subtract 2D array from each pixel of a 3D image and get a 4D array
Subtract 2D array from each pixel of a 3D image and get a 4D array

Time:08-09

I have a 2D array of shape (10, 3) and an image represented as a 3D array of shape (480, 640, 3). I'd like to perform a difference between each pixel and each element of the 2D array, to get a final result of shape (10, 480, 640, 3). For now, my code looks like this:

arr_2d = np.random.rand(10, 3)
arr_3d = np.random.rand(480, 640, 3)
res = np.ones_like(arr_3d)
res = np.tile(res, (10, 1, 1, 1))

for i in range(10):
    res[i] = arr_3d - arr_2d[i]

My question is if there's a way to do this without the for loop, only using numpy operations.

CodePudding user response:

You can try broadcasting with np.array like this

arr_2d = arr_2d.reshape(-1,1,1,3)
arr_3d = arr_3d.reshape((-1,*arr_3d.shape))
res = arr_3d - arr_2d

This should give the same result as your original code

  • Related