首先指出,在數字圖像領域內,灰度圖像不是黑白圖像。黑白圖像中,所有像素點的RGB值只有兩種,(0,0,0)或者(255,255,255),我們也可稱它為二值圖像。而灰度圖像則不同,灰度圖像在黑色與白色之間還有許多級的顏色深度,如果灰度圖是8位,就有2的8次方,即256個灰度級。
我們再來分析灰度圖像中的RGB值可以發現,每個像素點的RGB值都滿足R=G=B。
轉換前:

轉換后:

Gray = R*0.299 + G*0.587 + B*0.114
但是為了避免浮點運算,轉換成如下形式:
Gray=(R*30+G*59+B*11)/100
首先我們獲取一張圖片(JPG)每個像素點的RGB值,再存放進數組中,然后再處理數組中的每一個值,最后輸出就完成了。
這里必須要指出一下我們需要知道圖像的位深度是多少,這里我以位深度為24為例,從高位到地位,每8bit分別存儲着R、G、B的值。
1 import java.io.*;
2 import javax.imageio.ImageIO;
3 import java.awt.image.*;
4
5
6 public class imageTest() {
7 public static void main(String args[]){
8 BufferedImage grayImage = null;
9 grayImage = imageTest.imageToGray("C:\\imageForTest.jpg");
10 //會保存在當前工程的目錄下
11 ImageIO.write(grayImage, "JPEG", new File("grayImage.jpg"));
12 }
13
14 public static BufferedImage imageToGray(String imagePath){
15 BufferedImage image = null;
16 BufferedImage grayImage = null;
17 int gray = 0;
18 try {
19 File imagef = new File(imagePath);
20 image = ImageIO.read(imagef);
21
22 if(!imagef.exists()){
23 System.out.println("image not found!");
24 return grayImage;
25 }
26 int height = image.getHeight();
27 int width = image.getWidth();
28 int minX = image.getMinX();
29 int minY = image.getMinY();
30
31 grayImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
32
33 for(int i=minX; i<width; i++) {
34 for(int j=minY; j<height; j++) {
35 int[] RGB = {0, 0, 0};
36 //將24bit中存儲的RGB值單個提取出來,可以理解為byte轉int
37 RGB[0] = (image.getRGB(i, j) & 0xff0000) >> 16;
38 RGB[1] = (image.getRGB(i, j) & 0xff00) >> 8;
39 RGB[2] = (image.getRGB(i, j) & 0xff);
40
41 //這里是將RGB分別乘上一個權重,得出相應的灰度值gray
42 gray = (30*RGB[0] + 59*RGB[1] + 11*RGB[2]) / 100;
43 //將得出的灰度值轉換成計算機中存儲的模式
44 int rgb_togray = ((gray & 0xff)<<16 ) | ((gray & 0xff)<<8) | (gray & 0xff);
45 grayImage.setRGB(i, j, rgb_togray);
46 }
47 }
48 }catch(IOException e) {
49 e.printStackTrace();
50 }
51 return grayImage;
52 }
53 }