在RGB模型中,如果R=G=B时,则彩色表示一种灰度颜色,其中R=G=B的值叫灰度值,因此,灰度图像每个像素只需一个字节存放灰度值(又称强度值、亮度值),灰度范围为0-255。
图像灰度化处理方式:
(引用原博客地址:https://www.cnblogs.com/finlay/p/3665302.html)
1. 分量法
将彩色图像中的三分量的亮度作为三个灰度图像的灰度值,可根据应用需要选取一种灰度图像。
2. 最大值法
将彩色图像中的三分量亮度的最大值作为灰度图的灰度值。
3. 平均值法
将彩色图像中的三分量亮度求平均得到一个灰度值。
4. 加权平均法
根据重要性及其它指标,将三个分量以不同的权值进行加权平均。由于人眼对绿色的敏感最高,对蓝色敏感最低,因此,按下式对RGB三分量进行加权平均能得到较合理的灰度图像。
代码实现:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class demo {
public static void main(String[] args) {
try {
long l = System.currentTimeMillis();
BufferedImage image = ImageIO.read(new File("beb9894fc1a505976f996163f8c20361.jpg"));
BufferedImage image1 = new demo().grayProcessing(image);
ImageIO.write(image1, "jpg", new File("a.jpg"));
l = System.currentTimeMillis() - l;
System.out.println(l);
} catch (IOException e) {
e.printStackTrace();
}
}
int getGray(int R, int G, int B, String index) {
int gray;
switch (index) {
case "R":
case "r":
gray = R;
break;
case "G":
case "g":
gray = G;
break;
case "B":
case "b":
gray = B;
break;
case "max":
case "Max":
gray = Math.max(R, Math.max(G, B));
break;
case "MIN":
case "min":
gray = Math.min(R, Math.min(G, B));
break;
case "AVG":
case "avg":
gray = (R + G + B) / 3;
break;
case "WAVG":
case "WAvg":
case "wavg":
gray = (int) (0.2989 * R + 0.578 * G + 0.114 * B);
break;
default:
throw new RuntimeException("灰度化算法选择错误!");
}
return gray;
}
public BufferedImage grayProcessing(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
System.out.println("宽度:" + width);
System.out.println("高度:" + height);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int color = image.getRGB(i, j);
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = color & 0xff;
int gray = getGray(r, g, b, "min");
color = 0;
color |= (gray << 16);
color |= (gray << 8);
color |= gray;
image.setRGB(i, j, color);
}
}
return image;
}
}