I'm trying to come up with an algorithm to give images a score for the amount of green that they contain by iterating through the pixels using PIL. I have come up with a few different methods so far but they all seem flawed.
The first one sums all of the values of g in rgb and divides it but the total of all 3 colours.
def percent_green(img_file):
red = 0
green = 0
blue = 0
img = Image.open(img_file)
pixels = img.load()
width, height = img.size
for x in range(width):
for y in range(height):
rgb = pixels[x, y]
red += rgb[0]
green += rgb[1]
blue += rgb[2]
percent = green / (red + blue + green)
return percent * 100
This method succeeds at ranking images by how green they are but an image composed of just rgb(100, 200, 100) for example would only score 50% despite being very green.
The other method I have thought of is simply determining what percentage of pixels contain more green than red or blue.
def percent_green(img_file):
img = Image.open(img_file)
pixels = img.load()
width, height = img.size
total_green = 0
for x in range(width):
for y in range(height):
rgb = pixels[x, y]
if rgb[1] > rgb[0] and rgb[1] > rgb[2]: #if green predominant colour
total_green += 1
percent = total_green /(width * height)
return percent * 100
The problem with this option is that colours like rgb(0, 1, 0) or rgb(244, 255, 244) would be counted as green. I would ideally like some way to rank the "greenness" of a colour.
I would be very grateful for any suggestions of algorithms which can give a better percentage of how green an image is. Any suggestions on which of my current algorithms is better or how to improve them are also welcome.

