I am trying to make the Hadamard product of a 3-D with a 2-D array. The 2-D array shares the shape of the first two axes of the 3-D array and should be moved along the 2 axis (thus, the 3rd) for the multiplications, meaning: make Hadamard product with slice 0, then slice 1, and so on (cf. image, schematic).
The original 3-D array is an opencv
image, thus has a shape of f.e. (1080, 1920, 3)
. The 2-D-array is one slice of this image, thus has a shape of (1080, 1920)
Is there a way to do this without loops or specifying each slice on its own? Or are loops the way to go here?
What works is:
img_new = np.zeros(shape=img.shape[:2])
img_new[0] = (img[:, :, 1] * img[:, :, 0])[0]
img_new[1] = (img[:, :, 2] * img[:, :, 0])[1]
However, I would prefer not to have this calculation 2 times in the code.
I have tried:
img_new = np.multiply(img_cvt[:, :, 1:3], img[:, :, 0])
Although this works when using a 2-D and a 1-D array
>>> a = np.array(((1,2),(3,4)))
>>> b = np.array((5,8))
>>> np.multiply(a,b)
array([[ 5, 16],
[15, 32]])
It gives a broadcasting error in the 3-D/2-D case:
ValueError: operands could not be broadcast together with shapes (1080,1920,2) (1080,1920)
Same applies to np.apply_along_axis
:
img_new = np.apply_along_axis(np.multiply, 2, img[:, :, 1:3], img[:, :, 0])
Which yields the following:
ValueError: operands could not be broadcast together with shapes (2,) (1080,1920)
But I guess this could not work because it is designed for 1d functions...