I'm writing a program that will do image processing on a 16 bit tiff image (5 bit red, 6 bit green, 5 bit blue) but unfortunately the code I've written to do so treats the image data as 8 bit.
To elaborate with code, I read the image into memory with ImageIO utility class like so:
BufferedImage image = ImageIO.read(imageFile);
and later on use this loop to retrieve pixel information:
Matrix imageMatrix = new Matrix(image.getHeight(), image.getWidth());
Raster raster = image.getData();
double[] pixelColor = new double[4];
for (int x = 0; x < image.getWidth(); x = x + 1) {
for (int y = 0; y < image.getHeight(); y = y + 1) {
raster.getPixel(x, y, pixelColor);
double pixelColorAverage = (pixelColor[0] + pixelColor[1] + pixelColor[2]) / 3.0;
imageMatrix.set(y, x, pixelColorAverage);
}
}
return imageMatrix;
The problem is that raster.getPixel(x, y, pixelColor);
returns each RGB value in 8 bits (in my test image, the 0,0 pixel value is returned as 24,24,24 [8 bit values] when it should be 6168,6168,6168 [16 bit values]).
I've tried changing the simplistic ImageIO.read(imageFile)
to the following lines of code based on another stack overflow tiff question:
BufferedImage image = ImageIO.read(file);
BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_USHORT_565_RGB);
convertedImage.createGraphics().drawRenderedImage(image, null);
But this time, the raster.getPixel(x, y, pixelColor);
returns 3,6,3 which isn't correct either.
Based on the fact that ImageIO has support for tiff images and buffered image has a 5-6-5 style 16 bit image format, I can only assume this is possible, but I'm stumped as to what I'm missing.