开发者

Compare two colors in image?

I'm trying to compare t开发者_如何学Pythonhe given pixel to Color.BLACK. But the problem is it yields false for all the images. (I made a black image and it also returned false!)

public int isItBlackOrWhite(int x , int y)
{
     int c = bimg.getPixel(x, y);   
     if(c == Color.BLACK)
         {System.out.println("Helooo");return 0;}    
     else
      return 1;
}

Also I tried to compare it with Color.White but the application quit and force closed!

public int isItBlackOrWhite(int x , int y)
{
     int c = bimg.getPixel(x, y);   
     if(c == Color.WHITE)
         {System.out.println("Helooo");return 0;}    
     else
      return 1;
}

NOTE: bimg is an Bitmap image taken from the camera.


First, use LogCat for printing comments and variables. (Eclipse -> Window -> Show View -> Android -> LogCat. Then you should see the error in the Log.

That will help us to locate the error.


I don't know the specifics of the pixel formats you're using, but you're trying to compare a 32-bit integer representation of a color (most probably in ARGB format) with an object of type Color. You need to first get the ARGB representation of the Color object (probably by calling Color.getRGB() ) before comparing it to the result of getPixel().


As for the "black" image: you need another test image. Taking a picture with the camera will never get you a truly black photo. So finding truly black pixels will be hard too.

(Just add a debug statement to print the value of c to validate that. For Color.BLACK you should get -16777216, or hexadecimal 0xff000000.)


Color.BLACK is Color but not int. You need to cast them to the same type before comparing.


Ugly solution, but the answers below doesn't give actual solution to your problem. Try this:

Color white = new Color(0,0,0); // for white
Color black = new Color(255,255,255); // for black
if(yourPixel.equals(white)) { // operate }

You can also create a Color Constants class and use it accordingly and I think you can find one from the internet. If you're willing to implement that class, RGB value of colors.


The problem might be your usage of ==, which doesnt quite have the meaning you intend. In java it checks that two objects are the same object, and the color you get from your picture will never be equal to the value recorded in Color.BLACK

What you want to do is check that the color's values are the same, the red, green, blue, and alpha channels. This is a context dependent equality, which is usually implemented as the .equals() function of an object.

Try this one:

c.equals(Color.BLACK)

instead of

c == Color.BLACK
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜