C:\ece595_06\image>java gray1 Elapsed time 72.2954 milliseconds 327 x 215 Area 0.0703050 megapixels Time per megapixel 1028.31 milliseconds
gray1.javaimport java.awt.*;
import java.awt.image.*;
import java.awt.color.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class gray1 {
public static void main(String [] args) {
String filename = "bld.jpg";
if (args.length>0) filename = args[0];
showImage f1 = new showImage(filename);
f1.setLocation(100,100);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int w = f1.getWidth();
int h = f1.getHeight();
long start = System.nanoTime();
BufferedImage grayImage = rgb2gray(f1.img);
long etime = System.nanoTime() - start;
double elapsed_time = 1e-6*(double)etime;
System.out.format("Elapsed time %g milliseconds%n",elapsed_time);
double area = f1.img.getWidth()*f1.img.getHeight()*1e-6;
System.out.format("%d x %d Area %g megapixels%n",f1.img.getWidth(),
f1.img.getHeight(), area);
System.out.format("Time per megapixel %g milliseconds%n",elapsed_time/area);
showImage f2 = new showImage(grayImage,"gray version");
f2.setLocation(120+w,100);
f2.writeImage("gray","png");
}
public static BufferedImage rgb2gray(BufferedImage img) {
int w1 = img.getWidth();
int h1 = img.getHeight();
// int value[][] = new int[w1][h1];
BufferedImage gray = new BufferedImage(w1, h1, 1);// new image
int value, alpha, r, g, b;
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
value = img.getRGB(i, j); // read and store pixel value
alpha = get_alpha(value);
r = get_red(value);
g = get_green(value);
b = get_blue(value);
value = (r + g + b) / 3; // grey by averaging the pixels
r = g = b = value;
value = create_rgb(alpha, r, g, b);
gray.setRGB(i, j, value);
}
}
return gray;
}
public static int create_rgb(int alpha, int r, int g, int b) {
int rgb = (alpha << 24) + (r << 16) + (g << 8) + b;
return rgb;
}
public static int get_alpha(int rgb) {
return (rgb >> 24) & 0xFF;
// return rgb & 0xFF000000;
}
public static int get_red(int rgb) {
return (rgb >> 16) & 0xFF;
// return rgb & 0x00FF0000;
}
public static int get_green(int rgb) {
return (rgb >> 8) & 0xFF;
}
public static int get_blue(int rgb) {
return rgb & 0xFF;
}
}
Maintained by John Loomis, updated Thu Oct 10 12:02:08 2013