Nicholas
Nicholas

Reputation: 37

Classifying RGB values in python

Using Pillow

im = Image.open("GameShot.png");
pix = im.load();
PixelColor = pix[x,y]
if PixelColor == green:
    # do stuff

My Issue

pix[x,y] returns an RGB value and in my image the colour that I'm looking for doesn't stay the same.

Upvotes: 2

Views: 5442

Answers (1)

Jacob Ritchie
Jacob Ritchie

Reputation: 1401

You need some kind of function to classify a RGB value as belonging to a particular color.

One simple way to get close to this is to define a specific value for each color you want to consider (in your case, red and green, as you say in your comment below) and then calculate the manhattan distance between your RGB value and each of those points. Then you can pick the point that is the smallest distance away and say your pixel belongs to that color.

This will work for any number of colors that you specify and though it may not always be 100% accurate, it's good enough as a first approximation.

Note: I don't have access to Pillow, so I'm not sure what data structure im.load() returns. I'm using (R,G,B) tuples to give a rough idea.

def classify(rgb_tuple):
    # eg. rgb_tuple = (2,44,300)

    # add as many colors as appropriate here, but for
    # the stated use case you just want to see if your
    # pixel is 'more red' or 'more green'
    colors = {"red": (255, 0, 0),
              "green" : (0,255,0),
              }

    manhattan = lambda x,y : abs(x[0] - y[0]) + abs(x[1] - y[1]) + abs(x[2] - y[2]) 
    distances = {k: manhattan(v, rgb_tuple) for k, v in colors.items()}
    color = min(distances, key=distances.get)
    return color

Upvotes: 4

Related Questions