java - 通过平均组合灰度图像

标签 java image algorithm image-processing colors

我有一个使用 getRed()getGreen()getBlue() 的程序,效果很好。我想看看我是否能找到一些其他算法也可以为灰度图像着色,无论它更准确还是更不准确都没有关系,这只是我正在研究比较这些方法及其准确性的东西。 我决定使用类似的方法,只需对图像 1、2 和 3(而不是仅使用 1)使用 getRed() 并将每种颜色除以 3,理论上可以达到平均红色, 3 个图像中的绿色和蓝色值,并从中创建一个新图像。

生成的图像很奇怪;颜色不统一,即每个像素的颜色都是随机的,你几乎看不出图像的任何特征,因为它是如此颗粒状,我想这是描述它的最好方式。它看起来像一张普通的照片,但到处都有颜色噪点。只是想知道是否有人知道为什么会这样?这不是我的意图,而是期待更正常,与原始方法非常相似,但每种方法的颜色可能更柔和/更亮。

有人知道为什么会这样吗?好像不太对。除了标准的 getRGB() 方法之外,还有其他方法可以用来为图像着色吗?

BufferedImage combinedImage = new BufferedImage(image1.getWidth(), image1.getHeight(), image1.getType());
        for(int x = 0; x < combinedImage.getWidth(); x++)
            for(int y = 0; y < combinedImage.getHeight(); y++)
                combinedImage.setRGB(x, y, new Color(
                new Color((image1.getRGB(x, y) + image2.getRGB(x, y) + image3.getRGB(x, y))/3).getRed(), 
                new Color((image1.getRGB(x, y) + image2.getRGB(x, y) + image3.getRGB(x, y))/3).getGreen(), 
                new Color((image1.getRGB(x, y) + image2.getRGB(x, y) + image3.getRGB(x, y))/3).getBlue()).
                getRGB());

提前致谢

最佳答案

getRGB() 返回像素的 int 表示,包括 alpha channel 。由于 int 是 4 字节(32 位),因此该 int 将如下所示:

01010101 11111111 10101010 11111111
  Alpha     Red     Green    Blue

当您添加三个值时,这也使用了 alpha channel ,所以我猜这会让您得到奇怪的结果。此外,以这种方式添加整数可能会导致其中一个 channel “溢出”。例如,如果一个像素的蓝色值为 255,而另一个像素的值为 2,则总和的绿色值为 1,蓝色值为 1。

要从 int 中提取每个颜色 channel ,您可以这样做。

red = (rgb >> 16) & 0xFF;
green = (rgb >>8 ) & 0xFF;
blue = (rgb) & 0xFF;

(这是 Color 类在 getRed()、getBlue() 和 getGreen() 内部所做的事情 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/awt/Color.java#Color.getRed%28%29 )

然后,像这样组合颜色:

combinedImage.setRGB(x, y, new Color(
((image1.getRGB(x, y) >> 16 & 0xFF) + (image1.getRGB(x, y) >> 16 & 0xFF) + (image1.getRGB(x, y) >> 16 & 0xFF))/3, 
((image1.getRGB(x, y) >> 8 & 0xFF) + (image1.getRGB(x, y) >> 8 & 0xFF) + (image1.getRGB(x, y) >> 8 & 0xFF))/3, 
((image1.getRGB(x, y) & 0xFF) + (image1.getRGB(x, y) & 0xFF) + (image1.getRGB(x, y) & 0xFF))/3).
getRGB());

或者对每张图片每次都使用new Color(image1.getRGB(x, y)).getRed()

combinedImage.setRGB(x, y, new Color(
    (new Color(image1.getRGB(x, y)).getRed() + new Color(image2.getRGB(x, y)).getRed() + new Color(image3.getRGB(x, y)).getRed())/3, 
    (new Color(image1.getRGB(x, y)).getGreen() + new Color(image2.getRGB(x, y)).getGreen() + new Color(image3.getRGB(x, y)).getGreen())/3, 
    (new Color(image1.getRGB(x, y)).getBlue() + new Color(image2.getRGB(x, y)).getBlue() + new Color(image3.getRGB(x, y)).getBlue())/3).
    getRGB());

关于java - 通过平均组合灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756201/

相关文章:

arrays - 求数组中 K 个连续项的最小总和

java - MongoDB 是否会复制具有相同数据的子文档?

java - 如何通过向其传递运行时参数来使用命令模式

javascript - Instagram API,/media/recent 只显示当年的图像?

python - 在 Python 中以对数方式缩放二维数组

algorithm - 沿着兴趣点寻找路线

json - 范围匹配查找的数据结构

java - 如何显示 Dialog fragment ?

java - 在非静态内部类中使用泛型

c# - 构建一个位图,用较小的图像填充它