2013-11-03 203 views
0

我有一个程序,它使用getRed(),getGreen()getBlue(),它工作正常。我正在寻找是否可以找到一些其他的算法,这些算法也可以为灰度图像着色,不管它或多或少都是准确无误的,它只是用来比较方法和准确性的东西。 我决定使用类似的方法,只需对图像1,2和3使用getRed()(相对于1),并对每种颜色除以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()); 

预先感谢

回答

2

的getRGB()返回一个像素的INT表示,包括alpha通道。因为int是4个字节(32位),这个中断将是这样的:

01010101 11111111 10101010 11111111 
    Alpha  Red  Green Blue 

当您添加三个值,这是一个使用alpha通道太多,所以我想这是使你得到奇怪的结果。另外,以这种方式添加int会导致其中一个通道出现“溢出”。例如,如果一个像素的蓝色值为255,另一个像素的值为2,那么总和的值将为绿色,值为1。

要从int中提取每个颜色通道,可以执行此操作。

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

(这是什么颜色的类内部做内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()); 
+0

啊,这是有道理的,谢谢。当我使用你发布的代码时,我得到一个错误,说int不能被解除引用,只能按照以前的方式使它工作,对此有什么想法?感谢您的帮助 – user2517280

+0

我通过编译代码更新了我的答案 – Evans

+0

非常感谢,正如我所说的,我很欣赏它。图像是完全组合的,但是,输出图像只是灰色。我能想到的唯一原因是它不超过255,所以除以3时R,G,B值通常是相同的,导致灰色? – user2517280