Reputation: 16013
I found some bitshift code in the Java implementation of Hough Transform on Rosetta code, I understand in general what the code does, except this part:
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
I think it takes the average of all 3 pixels, that is at least what it looks like when I output the result. But how does this work? What are these magic numbers?
Method in which this function is used, pasted for convenience:
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; }
Upvotes: 1
Views: 92
Reputation: 726479
This is the trick that converts a 24-bit RGB value to a grayscale value using coefficients 0.3
, 0.59
, and 0.11
(note that these values add up to 1
).
This operation (rgbValue & 0xFF0000) >>> 16
cuts out bits 17..24, and shifts them right to position 0..7, producing a value between 0 and 255, inclusive. Similarly, (rgbValue & 0xFF00) >>> 8
cuts out bits 8..16, and shifts them to position 0..7.
This Q&A talks about the coefficients, and discusses other alternatives.
Upvotes: 2