Detect a colour based on its RGB

1.1k Views Asked by At

I want to detect red and green objects from webcam. I am using this Trackingjs library. I think with the library, it will track the red, green and blue value of an object and detect the colour according to the built-in colour library in their code.

Their built-in colours are defined like this:

  tracking.ColorTracker.registerColor('purple', function(r, g, b) {
    var dx = r - 120;
    var dy = g - 60;
    var dz = b - 210;
    if ((b - g) >= 100 && (r - g) >= 60) {
      return true;
    }
    return dx * dx + dy * dy + dz * dz < 3500;
  });

In the example above, objects which has their blue - green >= 100 and red -green >= 60 will be purple.

Can someone explain this to me how this works. And if I want to detect red/ reddish and green/greenish, how should I do with the same function.

2

There are 2 best solutions below

2
On BEST ANSWER

If you look at the colour RGB(120,60,210) it is this purple:

enter image description here

Now, dx measures the distance that the passed in colour is from the red component in that purple, dy measures the distance that the passed in colour is from the green component of that purple and dz measures the distance that the passed in colour is from the blue component.

The return value at the end, calculates, using 3-D Pythagorus, the square of the distance that the passed in colour is from purple in the 3-D colour cube with black at one corner, white diagonally opposite and R, G and B at the corners. So, it effectively defines a "sphere" of colour around the purple.

If you want to detect reddish tones, you will want something like

if ((r-g)>50 && (r-b)>50) { return true;}

which just says you want there to be more red than green and more red than blue.

If you want to detect greenish tones, you will want something like

if ((g-r)>50 && (g-b)>50) { return true;}

which just says you want there to be more green than red and more green than blue.

0
On

RGB Colour Parser. this is what you need. And of course it can be used for color verification.

From the description:

A JavaScript class that accepts a string and tries to figure out a valid color out of it. Some accepted inputs are for example:

rgb(0, 23, 255)
#336699
ffee66
fb0
red
darkblue
cadet blue

DEMO: Demo