图像对比度就是对图像颜色和亮度差异感知,对比度越大,图像的对象与周围差异性也就越大,反之亦然。
调整图像对比度的方法大致如下:(前提为对比度系数用户输入范围为【-100~100】)
1)读取每个RGB像素值Prgb, Crgb= Prgb/255,使其值范围为【0~1】
2)基于第一步计算结果((Crgb -0.5)*contrast+0.5)*255
3)第二步中得到的结果就是处理以后的像素值
注意:必须检查处理以后的像素值,如果值大于255,则255为处理后的像素值,如果小于0,则0为处理以后的像素值;Contrast为对比度系数,其取值范围为【0~2】
代码如下:
package chapter4;
import java.awt.image.BufferedImage;
/**
* Created by LENOVO on 18-1-29.
*/
public class ContrastFilter extends AbstractBufferedImageOp {
private float contrast;
public ContrastFilter(){
this(1.5f);
}
public ContrastFilter(float contrast){
this.contrast = contrast;
}
public float getContrast() {
return contrast;
}
public void setContrast(float contrast) {
this.contrast = contrast;
}
public BufferedImage filter(BufferedImage src,BufferedImage dest){
int width = src.getWidth();
int height = src.getHeight();
if(dest == null){
dest = creatCompatibleDestImage(src,null);
}
//判断输入对比度系数contrast是否在【-100~100】之间
if(contrast<-100){
contrast = -100;
}
if(contrast > 100){
contrast = 100;
}
contrast = 1+contrast/100.0f;//控制对比度系数范围
int[] inpixels = new int[width*height];
int[] outpixels = new int[width*height];
getRGB(src,0,0,width,height,inpixels);
int index = 0;
for(int row=0;row<height;row++){
int ta = 0,tr = 0,tg = 0,tb = 0;
for(int col=0;col<width;col++){
index = row*width+col;
ta = (inpixels[index] >> 24) & 0xff;
tr = (inpixels[index] >> 16) & 0xff;
tg = (inpixels[index] >> 8) & 0xff;
tb = (inpixels[index]) & 0xff;
//
float cr = ((tr/255.0f-0.5f)*contrast);
float cg = ((tg/255.0f-0.5f)*contrast);
float cb = ((tb/255.0f-0.5f)*contrast);
//
tr = (int)((cr + 0.5f)*255.0f);
tg = (int)((cg + 0.5f)*255.0f);
tb = (int)((cb + 0.5f)*255.0f);
outpixels[index] = (ta << 24) | (clamp(tr) << 16) | (clamp(tg) << 8) | clamp(tb);
}
}
setRGB(dest,0,0,width,height,outpixels);
return dest;
}
public int clamp(int value){//检查处理以后的像素值
return value>255 ? 255:((value<0) ? 0:value);
}
}
测试代码同上