gpt4 book ai didi

java - 在 Java 中为 BufferedImage 添加模糊效果

转载 作者:行者123 更新时间:2023-11-30 08:38:20 25 4
gpt4 key购买 nike

我正在编写一个图像处理项目。除了模糊效果,一切都完成了。常见的简单算法说:

  1. 取你的像素和你的像素周围的 8 个像素
  2. 对所有 9 个像素的 RGB 值求平均值并将它们粘贴在当前像素位置
  3. 对每个像素重复

下面我实现了添加模糊效果

BufferedImage result = new BufferedImage(img.getWidth(),
img.getHeight(), img.getType());

int height = img.getHeight();
int width = img.getWidth();

for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++) {

int pixel1 = (x == 0 || y == 0) ? 0 : img.getRGB(x - 1, y - 1);
int pixel2 = (y == 0) ? 0 : img.getRGB(x, y - 1);
int pixel3 = (y == 0 || x >= width-1) ? 0 : img.getRGB(x + 1, y - 1);
int pixel4 = (x == 0) ? 0 :img.getRGB(x - 1, y);
int pixel5 = img.getRGB(x, y);
int pixel6 = (x >= height -1) ? 0 :img.getRGB(x + 1, y);
int pixel7 = (x == 0 || y >= height -1) ? 0 :img.getRGB(x - 1, y + 1);
int pixel8 = (y >= height -1) ? 0 :img.getRGB(x, y + 1);
int pixel9 = (x >= width-1 || y >= height - 1) ? 0 :img.getRGB(x + 1, y + 1);

int newPixel = pixel1 + pixel2 + pixel3 + pixel4 + pixel5
+ pixel6 + pixel7 + pixel8 + pixel9;

newPixel = newPixel/9;

int redAmount = (newPixel >> 16) & 0xff;
int greenAmount = (newPixel >> 8) & 0xff;
int blueAmount = (newPixel >> 0) & 0xff;

newPixel = (redAmount<< 16) | (greenAmount << 8) | blueAmount ;
result.setRGB(x, y, newPixel);
}

我得到的结果是嘈杂的图像,而不是模糊的图像。我想我做错了什么。

提前致谢。注意:任何外部 API 都受到限制,例如 Kernal、AffineTransfomation 等...

最佳答案

这是只有循环的版本:

BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()) ;
final int H = img.getHeight() - 1 ;
final int W = img.getWidth() - 1 ;

for (int c=0 ; c < img.getRaster().getNumBands() ; c++) // for all the channels/bands
for (int x=1 ; x < W ; x++) // For all the image
for (int y=1; y < H ; y++)
{
int newPixel = 0 ;
for (int i=-1 ; i <= 1 ; i++) // For the neighborhood
for (int j=-1 ; j <= 1 ; j++)
newPixel += img.getRaster().getSample(x+i, y+j, c) ;
newPixel = (int)(newPixel/9.0 + 0.5) ;
result.getRaster().setSample(x, y, c, newPixel) ;
}

不要使用 getRGB,它真的很慢而且你必须处理转换。 getSample 为您做一切。

关于java - 在 Java 中为 BufferedImage 添加模糊效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com