这个java bitshift做了什么?

时间:2016-11-11 04:39:03

标签: java bit-shift

我在Rosetta代码的Java implementation of Hough Transform中找到了一些bithift代码,我通常理解代码的作用,除了这一部分:

rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);

我认为它需要所有3个像素的平均值,这至少是我输出结果时的样子。但这是如何工作的?这些神奇的数字是什么?

使用此功能的方法,为方便起见粘贴:

public static ArrayData getArrayDataFromImage(String filename) throws  IOException
{
    BufferedImage inputImage = ImageIO.read(new File(filename));
    int width = inputImage.getWidth();
    int height = inputImage.getHeight();
    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
    ArrayData arrayData = new ArrayData(width, height);
    // Flip y axis when reading image
    for (int y = 0; y < height; y++)
    {
      for (int x = 0; x < width; x++)
      {
        int rgbValue = rgbData[y * width + x];

       // What does this do?
        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
        arrayData.set(x, height - 1 - y, rgbValue);
      }
    }
    return arrayData;
}

1 个答案:

答案 0 :(得分:2)

这是使用系数0.30.590.11将24位RGB值转换为灰度值的技巧(请注意,这些值加起来为{{1} }})。

此操作1删除位17..24,并将它们右移到位置0..7,产生0到255之间的值,包括0和255。同样,(rgbValue & 0xFF0000) >>> 16会将位8..16切掉,并将它们移到位置0..7。

This Q&A讨论系数,并讨论其他替代方案。