Java BuffereImage获得单像素亮度
我想把彩色图像转换成单色,我想循环所有像素,但我不知道如何测试它们是亮还是暗Java BuffereImage获得单像素亮度,java,image,monochrome,Java,Image,Monochrome,我想把彩色图像转换成单色,我想循环所有像素,但我不知道如何测试它们是亮还是暗 for(int y=0;y<image.getHeight();y++){ for(int x=0;x<image.getWidth();x++){ int color=image.getRGB(x, y); // ???how to test if its is bright or dark?
for(int y=0;y<image.getHeight();y++){
for(int x=0;x<image.getWidth();x++){
int color=image.getRGB(x, y);
// ???how to test if its is bright or dark?
}
}
for(int y=0;y我建议首先将像素转换为灰度,然后应用阈值将其转换为纯黑白
有一些库可以为您实现这一点,但如果您想了解图像的处理方式,请访问:
彩色到灰度
有各种转换公式(请参阅一篇好文章),我更喜欢“光度”公式。因此:
我不知道您使用什么API来操作图像,因此我将上面的公式作为一般术语保留。pRed
,pGreen
和pBlue
是像素的红色、绿色和蓝色级别(值)
灰度到黑白
现在,您可以通过以下方式应用阈值:
int bw = grayscalePixel > THRESHOLD? 1: 0;
甚至:
boolean bw = grayscalePixel > THRESHOLD;
如果高于阈值,像素将为白色,如果低于阈值,像素将为黑色。通过稍微试验找到正确的阈值。这取决于“亮”和“暗”的含义。也许设置阈值会有所帮助?我如何设置阈值?请注意,有比手动检查所有像素更简单的方法:如何实现此操作以获得整个图像的亮度?、求和和和除法?@ZOLDIK Yup。简单平均。
int color = image.getRGB(x, y);
// extract each color component
int red = (color >>> 16) & 0xFF;
int green = (color >>> 8) & 0xFF;
int blue = (color >>> 0) & 0xFF;
// calc luminance in range 0.0 to 1.0; using SRGB luminance constants
float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;
// choose brightness threshold as appropriate:
if (luminance >= 0.5f) {
// bright color
} else {
// dark color
}
int color = image.getRGB(x, y);
// extract each color component
int red = (color >>> 16) & 0xFF;
int green = (color >>> 8) & 0xFF;
int blue = (color >>> 0) & 0xFF;
// calc luminance in range 0.0 to 1.0; using SRGB luminance constants
float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;
// choose brightness threshold as appropriate:
if (luminance >= 0.5f) {
// bright color
} else {
// dark color
}