Java - 查找两个图像相同的位置

时间:2015-05-29 03:49:56

标签: java bufferedimage

我正在研究一种阈值算法。我试图使用两种不同的算法,然后将结果图像找到它们都放置黑色像素的位置。

这是我写的代码:

public static BufferedImage andImage(BufferedImage one, BufferedImage two)
{  
    BufferedImage result = new BufferedImage(one.getWidth(), one.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    result.getGraphics().drawImage(one, 0, 0, null);
    WritableRaster rasterOne = result.getRaster();
    WritableRaster rasterTwo = two.getRaster();

    int[] pixelsOne = new int[one.getWidth()];
    int[] pixelsTwo = new int[two.getWidth()];

    for (int y = 0; y < two.getHeight(); y++) 
    {
        rasterOne.getPixels(0, y, one.getWidth(), 1, pixelsOne);
        rasterTwo.getPixels(0, y, two.getWidth(), 1, pixelsTwo);

        for (int i = 0; i < pixelsOne.length; i++) 
        {
            if (pixelsTwo[i] == 255 && pixelsOne[i] == 255)
            {
                pixelsOne[i] = 255;
            }
            else 
                pixelsOne[i] = 0;
        }
        rasterOne.setPixels(0, y, one.getWidth(), 1, pixelsOne);
    }

    return result;
}  

它提出的是两个图像的OR。我觉得这是一个非常简单的问题,但我似乎无法找到问题所在。

编辑: 所有像素都是0或255。

1 个答案:

答案 0 :(得分:0)

我有黑白交换的数字。它应该是:

public static BufferedImage andImage(BufferedImage one, BufferedImage two)
{  
    BufferedImage result = new BufferedImage(one.getWidth(), one.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    result.getGraphics().drawImage(one, 0, 0, null);
    WritableRaster rasterOne = result.getRaster();
    WritableRaster rasterTwo = two.getRaster();

    int[] pixelsOne = new int[one.getWidth()];
    int[] pixelsTwo = new int[two.getWidth()];

    for (int y = 0; y < two.getHeight(); y++) 
    {
        rasterOne.getPixels(0, y, one.getWidth(), 1, pixelsOne);
        rasterTwo.getPixels(0, y, two.getWidth(), 1, pixelsTwo);

        for (int i = 0; i < pixelsOne.length; i++) 
        {
            if (pixelsTwo[i] == 0 && pixelsOne[i] == 0)
                pixelsOne[i] = 0;
            else 
                pixelsOne[i] = 255;
        }
        rasterOne.setPixels(0, y, one.getWidth(), 1, pixelsOne);
    }

    return result;
}