user1291468
user1291468

Reputation: 139

rgb image convert binary image in java bufferedImage

I have a rgb image and i want to convert binary image 0-255.

I calculate threshold in rgb image and pixel which in gray level image bigger than threshold, i set red = 255 green=255 and blue=255 and lower than threshold i set red = 0 green=0 and blue=0

private static int colorToRGB(int alpha, int red, int green, int blue) {
    int newPixel = 0;
    newPixel += alpha;
    newPixel = newPixel << 8;
    newPixel += red; newPixel = newPixel << 8;
    newPixel += green; newPixel = newPixel << 8;
    newPixel += blue;
    System.out.println("asd"  + newPixel);
    return newPixel;
}

newPixel's value -16777216 if pixel is white newPixel's value -1 if pixel is black

alpha value is constant 255 Where am i wrong because i want to pixel's value 0 and 255.

BufferedImage type is TYPE_INT_ARGB

Thank you for helping

Upvotes: 0

Views: 4283

Answers (3)

Shawn
Shawn

Reputation: 1

A pixel won't have the value 0 - 255 unless is was a transparent blue color (0 alpha, 0 red, 0 green, 0-255 blue). Alpha, Red, Green, Blue could be in the range 0 - 255 each, but put together they're going to be much larger. With an alpha value that is 255, you'll end up with a leading 1 on your integer. Leading ones denote that the integer is negative. your final value is correct. Also, Torious is just shortening your equation, but both of your calculations work fine.

Upvotes: 0

Renard
Renard

Reputation: 6929

Honestly your question doesn't make much sense to me. So i answer your question making some assumptions:

  1. you have a global threshold [0-255]
  2. the threshold should be applied to a grayscale value so you need to convert the rgb pixels to grayscale values
  3. the procedure should be as fast as possible
  4. you want to do it in java

This function takes the rgb color and the threshold and returns either black or white.

public static int treshold(final int sourceColor, final int treshold) {
    // green channel is a good approximation of rgb intensity
    int green = (sourceColor >> 8) & 0xFF;
    if (green < treshold) {
        return 0xFF000000;
    } else {
        return 0xFFFFFFFF;
    }
}

Upvotes: 1

Torious
Torious

Reputation: 3424

int newPixel = (alpha << 24) | (red << 16) | (green << 8) | blue;

This results in the color encoded as 0xAARRGGBB, which is probably what you want.

Upvotes: 0

Related Questions