Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide RGB image by grayscale elementwise in numpy

Tags:

python

numpy

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
like image 732
DikobrAz Avatar asked Feb 27 '26 15:02

DikobrAz


2 Answers

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]]])
>>>
like image 123
wwii Avatar answered Mar 01 '26 03:03

wwii


Hmm... you could perhaps duplicate your grayscale array and just do one division?

arr1 /= arr2.repeat(3).reshape(np.shape(arr1))
like image 36
NJM Avatar answered Mar 01 '26 03:03

NJM