圖像亮度調整


在RGB色彩空間進行亮度圖像亮度調整的方法步驟:

1)計算像素在R、G、B三個分量上的平均值

2)對三個平均值分別乘以對應的亮度系數brightness,默認為1則表示亮度不變,大於1 表示亮度提高,小於1 表示亮度變暗

3)對每個像素值在R、G、B上的分量,首先減去第一步計算出來的平均值,然后再加上第二步的計算結果。

Pnew = Pold +(brightness -1 )*means

Pnew 處理之后的像素,Pold 處理之前的像素,brightness 亮度系數(取值范圍為【0~3】),means圖像像素的平均值

代碼如下:

package chapter4;

import java.awt.image.BufferedImage;

/**
* Created by LENOVO on 18-1-29.
*/
public class BrightFilter extends AbstractBufferedImageOp {
private float brightness = 1.2f;//定義亮度系數
public BrightFilter(){
//this(1.2f);
}
public BrightFilter(float brightness){
this.brightness = brightness;
}
public float getBrightness() {
return brightness;
}

public void setBrightness(float brightness) {
this.brightness = brightness;
}
public BufferedImage filter(BufferedImage src,BufferedImage dest){
int width = src.getWidth();
int height = src.getHeight();
if(dest == null){
dest = creatCompatibleDestImage(src,null);
}
int[] inpixels = new int[width*height];
int[] outpixels = new int[width*height];
getRGB(src,0,0,width,height,inpixels);

int index = 0;
int[] rgbmeans = new int[3];
double redSum = 0;double greenSum = 0;double blueSum = 0;
double total = width*height;
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;

redSum += tr;
greenSum += tg;
blueSum += tb;
}
}
//1、計算RGB各分量平均值
rgbmeans[0] = (int)(redSum/total);
rgbmeans[1] = (int)(greenSum/total);
rgbmeans[2] = (int)(blueSum/total);

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;

//2、減去平均值
tr -= rgbmeans[0];
tg -= rgbmeans[1];
tb -= rgbmeans[2];

//3、加上平均值乘以亮度系數的值
tr += rgbmeans[0]*brightness;
tg += rgbmeans[1]*brightness;
tb += rgbmeans[2]*brightness;

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);
}
}

測試代碼同上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM