1

I want to realize this function: calculate the average value(or the sum) rgb value of an image. More specifically, the image consists of an 2-d array of a tuple. Here is my code:

rgb = [0.0, 0.0, 0.0]
for r in range(0, 3):
    for ii in range(x, x + X_STEP):
        for jj in range(y, y + Y_STEP):
            rgb[r] += src_pix[ii][jj][r]
rgb = map(lambda a: a / X_STEP / Y_STEP, rgb) #this line does not matter, it is just the difference between sum and average

Question How to prettify it, or make it more pythonic? Maybe a nested map is still not the best. I hope it is like using itertools.

This link provides a solution close to my question. Another link is a possible duplicate of my code but he is not asking the same question.

Thanks a lot.

EDIT I actually hope to calculate the sum of a sub 2-d array.

Community
  • 1
  • 1
Chao Zhang
  • 1,476
  • 2
  • 14
  • 25

1 Answers1

2

It looks like you are using PIL. If so I'd use numpy for this.

Assuming you are using PIL version >= 1.1.6 , you can convert between the PIL object src_pix to numpy array like so:

np_pix = numpy.array(srx_pix)

Then just use numpy.sum :

rgb = numpy.sum(np_pix)

Or calculate the average (as your code above does):

rgb = numpy.mean(np_pix)

For older versions of PIL use numpy.asarray.

If you want to compute the sum of a subarray, you can get that subarray using a slice like so:

rgb_slice = numpy.mean(np_pix[X_start:X_end,Y_start:Y_end])

References:

Community
  • 1
  • 1
Matt W-D
  • 1,605
  • 2
  • 19
  • 22