Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of colorvalues of an image

I am looking for a way to sum the color values of all pixels of an image. I require this to estimate the total flux of a bright source (say a distant galaxy) from its surface brightness image. Would anyone please help me how can I sum the colour values of all pixels of an image.

For example: Each pixel of the following image has a colour value in between 0 to 1. But when I read the image with imread the colour values of each pixel I get is an array of 3 elements. I am very new in matplotlib and I do not know how can I convert that array to single values in the scale of 0 to 1 and add them.

enter image description here

like image 490
user3503692 Avatar asked Apr 06 '14 15:04

user3503692


1 Answers

If you have a PIL image, then you can convert to greyscale ("luminosity") like this:

from PIL import Image
col = Image.open('sample.jpg')
gry = col.convert('L') # returns grayscale version.

If you want ot have more control over how the colors are added, convert to a numpy array first:

arr = np.asarray(col)
tot = arr.sum(-1)  # sum over color (last) axis
mn  = arr.mean(-1) # or a mean, to keep the same normalization (0-1)

Or you can weight the colors differently:

wts = [.25, .25, .5]    # in order: R, G, B
tot = (arr*wts).sum(-1) # now blue has twice the weight of red and green

For large arrays, this is equivalent to the last line and faster, but possibly harder to read:

tot = np.einsum('ijk, k -> ij', arr, wts)

All of the above adds up the colors of each pixel, to turn a color image into a grayscale (luminosity) image. The following will add up all the pixels together to see the integral of the entire image:

tot = arr.sum(0).sum(0) # first sums all the rows, second sums all the columns

If you have a color image, tot will still have three values. If your image is grayscale, it will be a single value. If you want the mean value, just replace sum with mean:

mn = arr.mean(0).mean(0)
like image 167
askewchan Avatar answered Oct 03 '22 09:10

askewchan