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

zaig

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.

TaQ

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

creating a java bitmap image from a 3d byte array which contains 3 channel pixel information

Max of each 2D matrix in 4D NumPy array

Creating 4D numpy array by repeating values from 2D numpy array

Storing an image dataset into 4D array then showing each image leads to distorted colors

4D array from 2D arrays

Extract pixel values from image (2d array) at specific coordinates using mask

Python reshaping a np 4D array into a 2D array. Kaggle Image data

Return 2d array from 3d array masked by 2d array

reshape batch matrices (3d array, each matrix is an image) to 2d (a grid of images)

Usind 3d array to index 4d array

How to add (not append) a 2d array to each 2d array of a 3d array?

Creating a gray-scale image from an 2D array of pixel values

Taking different columns from each 2D slice of a 3D numpy array

How to get 2D array from 3D array of an image by removing black pixels, i.e. [0,0,0], in python

Convert 3D array image into 2D array

Subtract vector from 3d array

Prepending 1d array onto each 2d array of a 3d array

Generating 3D array from 2D array

Numpy: Subtract Numpy argmin from 3D array

Adding 3D array to 4D array

2D RGB image construction from 3D array in SimpleITK

Get a list of values from 3D array using 2D index array in Matlab

How to convert 4D image array to 3D image array

Convert a 3d array to a 4d array

Finding the indices of the minimum in each 2D array from a 3D array

How to make a 4D numpy array from 2 2D numpy array?

NumPy 3D Array: Get items from a list of 2D co-ordinates

How to efficiently normalise each 2d array in 4d numpy array

Get 2D elements from 3D numpy array, corresponding to 2D indices