Question

I want detect if each pixel of an image is in a range between two colors. I get the pixel color with getImageData but now I don´t know how know if it is in the range. any idea? thanks

Was it helpful?

Solution

In HSL colors, the H means Hue (what we normally think of as the color). If you use HSL colors, you can do as Stano suggests and just calculate the linear distance between any pixel hue and your specified hue(s).

HueDesired – HuePixel

But computer images are normally defined in the RGB color model. RGB uses a blend of colors to make your desired color. With RGB you can determine if 2 colors are “close” by calculating their Euclidian distance from each other on the color wheel.

Here’s a function to calculate the Euclidian distance between a specified color and a pixel color:

// find Euclidian distance from the pixel color to the specified color 
//
function colorDistance(colorRed,colorGreen,colorBlue,pixelRed,pixelGreen,pixelBlue){

    var diffR,diffG,diffB;

    // distance to color
    diffR=( colorRed - pixelRed );
    diffG=( colorGreen - pixelGreen );
    diffB=( colorBlue - pixelBlue );
    return(Math.sqrt(diffR*diffR + diffG*diffG + diffB*diffB));

}

Since you want to compare the pixel to 2 colors, just run this function for both of your 2 colors.

It’s up to you to determine what is an “acceptable” distance between your 2 colors and the pixel color, but this function will give you a measuring tool to work with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top