Java 48 位 TIFF 图像处理





0/5 (0投票)
使用 JAI (Java Advanced Imaging Library) 进行 48 位图像处理
引言
本文详细介绍了如何使用 Java 处理 48 位 TIFF 图像,这里的处理是指修改 48 位图像中每个像素的 RGB 分量并保存结果图像。
背景
可以使用 JAI(Java Advanced Imaging API)在 Java 中轻松处理 TIFF 图像。有很多示例说明如何处理 24 位图像(RGB 中的每个分量为 8 位)。但是,没有关于如何处理 48 位图像(RGB 中的每个分量为 16 位)的示例或文章。
用法
TIFF 图像生成大型图像,并用于不允许质量损失的场景,例如科学图像处理、医学成像、天文图像等。通过使用提供的代码,将更容易操作高质量的 TIFF 图像。
使用代码
此代码接收多个 48 位单页 TIFF 图像,从所有图像的每个像素中提取红色、绿色和蓝色分量。然后,它计算每个分量的平均值,重新创建像素并生成新图像。
样本图像和输出如下:(
+
)/2= 
所有图像尺寸完全相同,看起来相似,并且像素颜色存在一些差异。
将 TIFF 图像读取为 Raster
以下代码片段将 TIFF 图像读取为 Raster,反过来将用于从中读取像素。
File file = new File(fileName.get(i));
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
/*
* ImageDecoder is from com.sun.media.jai.codec.ImageDecoder package
*/
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
raster[i] = dec.decodeAsRaster();
从源图像创建可写入的 Raster
以下代码使用源图像的一个属性创建可写入的 Raster。
if (wRaster == null) { // Create a writable raster and get the color
// model.We'll use this to write the image
cm = image.getColorModel();
wRaster = image.getData().createCompatibleWritableRaster();
}
获取像素并计算平均值并更新可写入的 Raster
以下代码片段获取每个像素的 RGB 分量,计算平均值,然后使用计算出的平均值更新可写入的 Raster。
int w = raster[0].getWidth(), h = raster[0].getHeight();
int averagePixel[][][] = new int[w][h][3];
for (int i = 0; i < totalFiles; i++) {
for (int width = 0; width < w; width++) {
for (int height = 0; height < h; height++) {
int[] pixelA = null;
pixelA = raster[i].getPixel(width, height, pixelA);
averagePixel[width][height][0] += pixelA[0];
averagePixel[width][height][1] += pixelA[1];
averagePixel[width][height][2] += pixelA[2];
if (i == totalFiles - 1) // update the raster while
// processing last file
{
averagePixel[width][height][0] /= totalFiles;
averagePixel[width][height][1] /= totalFiles;
averagePixel[width][height][2] /= totalFiles;
wRaster.setPixel(width, height,
averagePixel[width][height]);
}
}
}
}
创建结果 TIFF 图像
以下代码将 Raster 保存到 TIFF 图像。
File file = new File(directoryName + "\\Output_"
+ System.currentTimeMillis() + ".tiff");
FileOutputStream fileoutput = new FileOutputStream(file);
TIFFEncodeParam encParam = null;
ImageEncoder enc = ImageCodec.createImageEncoder("tiff", fileoutput,
encParam);
enc.encode(wRaster, cm);
fileoutput.close();
值得关注的点
这只是一个示例,说明如何访问、处理和重新创建 48 位图像。以此作为起点,我们可以对图像进行高级处理,例如
- 查找方差
- 处理 alpha 分量
- 处理图像的不同通道/波段
- 处理其他尺寸的图像