0

I'm working on Bitmap images in Android Studio, and I would know how to do to detect all red pixels for examples, but not just the pixels that are strictly equals to Color.RED. I just give an example with RED color, but I want to do it with all different color possible.

I tried to do this:
...
int[] pixels = new int[width * height];
myBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 0; i < width * height; i++) {
    if (pixels[i] == Color.RED) {
        // color detected
    }
...

But this doesn't work as my image does not contains red pixel that is (255, 0, 0) but contains pixels that could be (251, 30, 77) or (239, 23, 42), which is also "red", etc...

So how could I do to such thing ? I also tried something like :

int reference; // color as rgb
if ( (Color.red(pixels[i]) > Color.red(reference) - 20) &&
     (Color.red(pixels[i]) < Color.red(reference) + 20 &&
...
{
   // pixel detected
}
...

Where I suppose that (r +- 20, g +- 20, b +-20) is part of (r, g, b) (I mean, for human eye)

Any idea on how I can do that ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
rlasvenes
  • 19
  • 8
  • To get the similarity of two colors you can calculate the euclidean distance between them. – SilverMonkey Oct 20 '18 at 16:43
  • You can find some discussion and simple methods on color matching here - https://stackoverflow.com/questions/27374550/how-to-compare-color-object-and-get-closest-color-in-an-color/27375621#27375621 – Anhayt Ananun Oct 20 '18 at 17:35
  • Consider converting to HSl/HSV colorspace https://en.wikipedia.org/wiki/HSL_and_HSV and finding pixels where the Hue is <10 or greater than 350 degrees. – Mark Setchell Oct 21 '18 at 20:32

1 Answers1

1

You can accept all pixels that are within a certain distance of the color you want. Assuming you want RED and everything within euclidian distance of 10 of RED:

boolean distance(int a, int b) {
return Math.sqrt(Math.pow(Color.red(a) - Color.red(b), 2) + Math.pow(Color.blue(a) - Color.blue(b), 2) + Math.pow(Color.green(a) - Color.green(b), 2));
}
....
int reference = Color.RED;
if (distance(reference, pixels[i]) < 10) {
//pixel accepted
}