java语言的科学与艺术(灰度图像)

 1 import acm.graphics.*;
 2 import acm.program.*;
 3 
 4 public class imageConvert extends GraphicsProgram {
 5     public void run(){
 6         GImage image = new GImage("Penguins.jpg");
 7         image = applyAveragingFilter(image);
 8         add(image);
 9     }
10     /*
11      * Creates a new image by applying an averaging filter to the original.
12      * Each pixel in the original image is replaced by a grayscale pixel with the 
13      * average luminosity of the current pixel and its four immediate neighbors.
14      */
15     private GImage applyAveragingFilter(GImage image) {
16         int[][] array = image.getPixelArray();
17         int height = array.length;
18         int width = array[0].length;
19         for(int i = 0; i < height; i++) {
20             for(int j = 0; j < width; j++) {
21                 int xx = averageNeighborLuminosity(array, i, j);
22                 array[i][j] = (0xFF << 24) | (xx << 16) | (xx << 8) | xx;
23             }
24         }
25         return new GImage(array);
26     } 
27     
28     /*
29      * Computes the average luminosity of the pixel at array[i][j] and its four
30      * immediate neighbors (up, down, left, and right).
31      */
32     private int averageNeighborLuminosity(int[][] array, int i, int j) {
33         int sum = getLuminosity(array, i, j);
34         int count = 1;
35         if(i > 0) {
36             sum += getLuminosity(array, i - 1, j);
37             count++;
38         }
39         if(i < array.length - 1) {
40             sum += getLuminosity(array, i + 1, j);
41             count++;
42         }
43         if(j > 0) {
44             sum += getLuminosity(array, i, j - 1);
45             count++;
46         }
47         if(j < array.length - 1) {
48             sum += getLuminosity(array, i, j + 1);
49             count++;
50         }
51         return GMath.round((double) sum / count);
52     }
53     
54     /* Determines the luminosity of the pixel at array[i][j] */
55     private int getLuminosity(int[][] array, int i, int j){
56         int pixel = array[i][j];
57         int red = (pixel >> 16) & 0xFF;
58         int green = (pixel >> 8) & 0xFF;
59         int blue = pixel & 0xFF;
60         return GMath.round(0.299 * red + 0.587 * green + 0.114 * blue);
61     }
62 }

 

posted on 2012-12-31 17:56  mybluecode  阅读(256)  评论(0编辑  收藏  举报