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

Question:

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.

Asked By: zaig

||

Answers:

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

Answered By: TaQ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.