我最近阅读过卷积滤镜,并决定尝试一下。我想制作模糊图像的代码,但最终它做的是让它变亮。我一直在看我的代码一段时间,并且找不到任何错误。谁能帮忙?卷积模糊滤镜不起作用并使图像变亮
这里是我的代码:
final static int filterHeight =3;
final static int filterWidth = 3;
static double filter[][] = new double[][]{
{1,1,1},
{1,1,1},
{1,1,1}
};
public static void main(String[] args) {
BufferedImage img;
BufferedImage result;
try
{ File in = new File("in.jpg");
File out = new File("out.jpg");
img = ImageIO.read(in);
Color[][] pixels = new Color[img.getWidth()][img.getHeight()];
for(int i=0;i<img.getWidth();i++){
for(int j=0;j<img.getHeight();j++){
pixels[i][j]=new Color(img.getRGB(i,j),true);
}
}
result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
for(int x=0;x<img.getWidth();x++){
for(int y=0;y<img.getHeight();y++){
int r=0,g=0,b=0;
for(int i=0;i<filterWidth;i++){
for(int j=0;j<filterHeight;j++){
int imageX = (int)(x - filterWidth/2 + i + img.getWidth()) % img.getWidth();
int imageY = (int)(y - filterHeight/2 + j + img.getHeight()) % img.getHeight();
if(imageX<0 || imageY<0) System.out.println("ERROR: "+imageX+" "+imageY);
r+=pixels[imageX][imageY].getRed()*filter[i][j];
g+=pixels[imageX][imageY].getGreen()*filter[i][j];
b+=pixels[imageX][imageY].getBlue()*filter[i][j];
}
if(r>255) r=255;
if(r<0) r=0;
if(g>255) g=255;
if(g<0) g=0;
if(b>255) b=255;
if(b<0) b=0;
Color color = new Color(img.getRGB(x,y),true)
Color colorBlur = new Color(r,g,b,color.getAlpha());
result.setRGB(x, y, colorBlur.getRGB());
}
}
}
ImageIO.write(result, "JPG", out);
}
catch (IOException e)
{
e.printStackTrace();
}
我相信你缺少的分频系数的参数应该是过滤器矩阵的总和,你的情况,'9 '。否则,你正在做一个'9'像素的总和,这很可能意味着'> 255'。 – Elia
@Elia你应该添加它作为一个答案...更通常的是划分(规范化)矩阵本身,所以总和为1,所以你不需要在每个像素上划分... – Spektre