取两个 RGB 值的平均值结果不一致

Inconsistent results from taking average of two RGB values

为什么那些像素RGB值有时相等有时不相等?我正在学习图像处理。如果有人在这里帮助我,那就太好了。

public class ColorTest1 {

    Color p1;
    Color p2;

    ColorTest1() throws IOException, InterruptedException {
        BufferedImage bi = ImageIO.read(new File("d:\x.jpg"));
        for (int y = 0; y < bi.getHeight(); y++) {
            for (int x = 0; x < bi.getWidth() - 1; x++) {
                p1 = new Color(bi.getRGB(x, y));
                p2 = new Color(bi.getRGB(x + 1, y));

                int a = (p1.getAlpha() + p2.getAlpha()) / 2;
                int r = (p1.getRed() + p2.getRed()) / 2;
                int g = (p1.getGreen() + p2.getGreen()) / 2;
                int b = (p1.getBlue() + p2.getBlue()) / 2;

                int x1 = p1.getRGB();
                int x2 = p2.getRGB();

                int sum1 = (x1 + x2) / 2;

                int sum2 = a * 16777216 + r * 65536 + g * 256 + b;
                System.out.println(sum1 == sum2);
            }
        }
    }

    public static void main(String... areg) throws IOException, InterruptedException {
        new ColorTest1();
    }
}

这是图片:

取两个像素。一种是黑色的。另一个几乎是黑色的,但里面有一点点红色,只有 1/255。忽略阿尔法。 r 将为 (0 + 1) / 2 = 0。gb 也将为 0。 x1 将是 0。x2 将是 65536,对吗?所以 sum1 将是 65536 / 2 = 32768。sum2 显然是 0。

每当两种颜色的红色或绿色之和为奇数时,int 除法将设置 RGB 中下一种颜色的高位,从而导致意外结果。