我最近读到了有关卷积滤波器的内容,并决定尝试一下。我想编写使图像模糊的代码,但最终的结果是使图像变亮。我已经检查我的代码有一段时间了,找不到任何错误。有人可以帮忙吗?
这是我的代码:
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();
}
最佳答案
为了获得您想要的结果,有两种选择。
您可以创建一个总和为 1 的过滤器矩阵(就像@Spektre 在上面的评论中提到的那样),或者将像素的新值乘以因子 1/sum(filterMatrix)
。
对于模糊概念的一个很好的初学者教程,我建议: Concept of Blurring - www.TutorialsPoint.com
关于java - 卷积模糊滤镜不起作用并使图像变亮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40498083/