Anyone know of a simple way of converting the RGBint value returned from <BufferedImage> getRGB(i,j)
into a greyscale value?
I was going to simply average the RGB values by breaking them up using this;
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
and then average red,green,blue.
But i feel like for such a simple operation I must be missing something...
After a great answer to a different question, I should clear up what i want.
I want to take the RGB value returned from getRGB(i,j), and turn that into a white-value in the range 0-255 representing the "Darkness" of that pixel.
This can be accomplished by averaging and such b开发者_C百科ut I am looking for an OTS implementation to save me a few lines.
This tutorial shows 3 ways to do it:
By changing ColorSpace
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
BufferedImage image = op.filter(bufferedImage, null);
By drawing to a grayscale BufferedImage
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(colorImage, 0, 0, null);
g.dispose();
By using GrayFilter
ImageFilter filter = new GrayFilter(true, 50);
ImageProducer producer = new FilteredImageSource(colorImage.getSource(), filter);
Image image = this.createImage(producer);
this isn't as simple as it sounds because there is no 100% correct answer for how to map a colour to greyscale.
the method i'd use is to convert RGB to HSL then 0 the S portion (and optionally convert back to RGB) but this might not be exactly what you want. (it is equivalent to the average of the highest and lowest rgb value so a little different to the average of all 3)
Averaging sounds good, although Matlab rgb2gray uses weighted sum.
Check Matlab rgb2gray
UPDATE
I tried implementing Matlab method in Java, maybe i did it wrong, but the averaging gave better results.
精彩评论