基本思想:
RGB像素的亮度是由RGB各个分量值的大小决定的,分量越大,亮度越大。看上去
好像光照效果越明显,光源退化效果是模拟光照在图像的中心点上,慢慢扩散到周
围,越靠近中心点像素,图像越亮,越远离图像越暗。原理可以说是非常的简单,
只要计算图像中每个像素到中心像素的欧几里德距离,归一化以后得到scale值(0
到1之间)乘以原来的RGB像素值即得到每个像素处理以后的RGB像素值。
效果如下:
关键代码解释:
中心像素点坐标取得:
int centerX = width/2;
int centerY = height/2;
任意一个像素点到中心像素的距离计算:
double xx = (centerX - px)*(centerX - px);
double yy = (centerY - py)*(centerY - py);
return (int)Math.sqrt(xx + yy);
距离归一化以及衰减因子考虑:
double scale = 1.0 - getDistance(centerX, centerY, col,row)/maxDistance;
for(int i=0; i<factor; i++) {
scale = scale * scale;
}
计算每个像素点的新RGB值:
tr = (int)(scale * tr);
tg = (int)(scale * tg);
tb = (int)(scale * tb);
滤镜源代码如下:
package com.gloomyfish.filter.study;
import java.awt.image.BufferedImage;
public class SpotlightFilter extends AbstractBufferedImageOp {
// attenuation coefficient, default is 1 means line decrease...
private int factor;
public SpotlightFilter() {
factor = 1;
}
public void setFactor(int coefficient) {
this.factor = coefficient;
}
@Override
public BufferedImage filter(BufferedImage src, BufferedImage dest) {
int width = src.getWidth();
int height = src.getHeight();
if ( dest == null )
dest = createCompatibleDestImage( 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 centerX = width/2;
int centerY = height/2;
double maxDistance = Math.sqrt(centerX * centerX + centerY * centerY);
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;
double scale = 1.0 - getDistance(centerX, centerY, col, row)/maxDistance;
for(int i=0; i<factor; i++) {
scale = scale * scale;
}
tr = (int)(scale * tr);
tg = (int)(scale * tg);
tb = (int)(scale * tb);
outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;
}
}
setRGB( dest, 0, 0, width, height, outPixels );
return dest;
}
private double getDistance(int centerX, int centerY, int px, int py) {
double xx = (centerX - px)*(centerX - px);
double yy = (centerY - py)*(centerY - py);
return (int)Math.sqrt(xx + yy);
}
}
转载请注明出处