javatypescastingbgr

Average of byte values


I am trying to create a (average) greyscale of an image, and I do not seem to get the values for each pixel. I think I am not doing the right calculations when summarizing the average, but I can not find what is wrong.

public byte[] changePixelValues(byte blue, byte green, byte red) {
            //Convert to greyscale by average
            byte avg;
            int sum = 0;
            sum +=blue;
            sum += green;
            sum += red;
            avg = (byte) (sum / 3);

            //System.out.println("avg: " +  avg);
            byte[] values = new byte[3];

            values[0] = avg;
            values[1] = avg;
            values[2] = avg;

            return values;

Is there something that I missed in the type conversion?

EDIT:

The input is the following where byte[] data is the raw data from a BufferedImage, which in this case does not have an alphaRaster.

for (int i = 0; i < data.length; i += 3) {
      byte [] newData = changer.changePixelValues(data[i], data[i+1], data[i+2]);
      System.arraycopy(newData,0,data,i,3);
}

Solution

  • First of all if you want convert image to greyscale you method should return only one byte value not byte array. If you return one byte you could assign that value to each RGB channel and you get grayscale image or set that value to 8-bit image.

    You need to remember that byte in java is signed (range -128 to 127) so if you have for example R-channel value equal to 200 (channel values could be in range 0 to 255) and you cast it to byte, value is equal to -56. So if you calculate average (lets assume that G=B=100) you have average equals 48 (should be 133).