圖像對比度就是對圖像顏色和亮度差異感知,對比度越大,圖像的對象與周圍差異性也就越大,反之亦然。
調整圖像對比度的方法大致如下:(前提為對比度系數用戶輸入范圍為【-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);
}
}
測試代碼同上
