Home > Mobile >  opencv / numpy how to get the sum of each pixel
opencv / numpy how to get the sum of each pixel

Time:04-07

I've got an image 2d array with each pixel containing rgb value (bgr in opencv i guess) and i'm trying to get the a new 2d array which has the sum of each pixel instead.

e.g.

start image:

shape: (1080,1920,3)

[[[255,255,255], [0,0,0]], [[0,120,255], [0,255,0]]]

result:

shape: (1080,1920,1)

[[[765],[0]], [[375],[255]]]

I'm sure there's a simple Numpy solution that I just do not know yet...

Any help would be greatly appreciated!

CodePudding user response:

Are you sure it's a 2-d array? Usually image arrays are 3-d, with shape (height, width, n_channels). If you have an array like that, you can use the sum method on an array, summing across the channel axis.

eg.

In [1]: a = np.random.randint(0, 10, (2, 3, 4))

In [2]: a
Out[2]: 
array([[[5, 1, 7, 0],
        [7, 3, 1, 5],
        [5, 7, 0, 2]],

       [[5, 2, 0, 9],
        [4, 7, 4, 4],
        [0, 7, 1, 3]]])

In [3]: a.sum(axis=-1)
Out[3]: 
array([[13, 16, 14],
       [16, 19, 11]])

CodePudding user response:

mono = rgb.sum(axis=2)

That produces a shape (1080,1920). If you really need it to have a third dimension, you can use reshape.

By the way, if you're really trying to produce monochrome, this is not the way to do it. There's a formula to convert RGB to mono, and OpenCV has tools to do it.

  • Related