在图像处理中有时候会遇到对数变换、幂律变换等较为复杂的计算,相应的处理时间也会增多,这时候就需要使用查找表来实现图像处理加速。由于图像灰度值是一个[0,255]的有限集合,那么只需要提前对[0,255]内所有数字进行计算,生成以输入值为索引位置,输出值为对应值的数组,实际对图像进行计算时,不需要再进行相应计算,只需要根据对应灰度值为索引查找数组中相应的值。
以对数变换为例:
对数变换公式:s=c*log(r+1)
第一步,初始化一个大小为256的int数组作为查找表,通过循环生成0~255个索引,对每个索引位置根据索引值进行对数变换计算;
第二步,对图像进行操作,根据图像每个像素取出RGB值后,以RGB值为索引,通过查找表找到RGB值对数变换对应的值,以该值赋值到对应像素上即可完成对数变换。
处理一张7592*5304大小的照片,直接使用对数变换对每个RGB值进行操作用时为8548毫秒,使用查找表用时为4657毫秒,图像越大节省的时间越明显。
Demo如下:
/**
* 对数变换
* @author admin
*
*/
public class LogTransform {
private int[] table;
//初始化对数变换查找表
private int[] initLogTable() {
table = new int[256];
for (int i = 0; i < 256; i++) {
table[i] = (int) Math.round(255 * Math.log(i + 1) / Math.log(256));
}
return table;
}
/**
* 对数变换
*
* @param image
* @return
*/
public BufferedImage logTransform(BufferedImage image) {
BufferedImage resultImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
initLogTable();
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int rgb = image.getRGB(i, j);
int R = (rgb >> 16) & 0xff;
int G = (rgb >> 8) & 0xff;
int B = rgb & 0xff;
rgb = (255 & 0xff) << 24 | (clamp(table[R]) & 0xff) << 16 | (clamp(table[G]) & 0xff) << 8
| (clamp(table[B]) & 0xff);
resultImage.setRGB(i, j, rgb);
}
}
return resultImage;
}
// 判断r,g,b值,大于256返回256,小于0则返回0,0到256之间则直接返回原始值
private int clamp(int rgb) {
if (rgb > 255)
return 255;
if (rgb < 0)
return 0;
return rgb;
}
public static void main(String[] args) throws Exception{
File input = new File("C:/Users/admin/Desktop/1.jpg");
File output = new File("C:/Users/admin/Desktop/3.jpg");
BufferedImage image = ImageIO.read(input);
long time1 = System.currentTimeMillis();
BufferedImage result = new LogTransform().logTransform(image);
long time2 = System.currentTimeMillis();
System.out.println(time2 - time1);
ImageIO.write(result, "jpg", output);
}
}