Suppose we have two arrays of shape (480, 640, 3) and (480, 640), say RGB and grayscale image. How you divide elementwise first array by the second? So far I use the following code, but is there a better snippet for it?
arr1[:, :, 0] /= arr2
arr1[:, :, 1] /= arr2
arr1[:, :, 2] /= arr2
You can add another axis to arr2 so that it will broadcast.
>>> a = np.ones((2,2,3))
>>> b = np.ones((2,2)) * 2
>>> a
array([[[ 1., 1., 1.],
[ 1., 1., 1.]],
[[ 1., 1., 1.],
[ 1., 1., 1.]]])
>>> b
array([[ 2., 2.],
[ 2., 2.]])
>>> a = a / b[:, :, np.newaxis]
>>> a
array([[[ 0.5, 0.5, 0.5],
[ 0.5, 0.5, 0.5]],
[[ 0.5, 0.5, 0.5],
[ 0.5, 0.5, 0.5]]])
>>>
Hmm... you could perhaps duplicate your grayscale array and just do one division?
arr1 /= arr2.repeat(3).reshape(np.shape(arr1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With