简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM