Page 217 - The Definitive Guide to Building Java Robots
P. 217

Preston_5564C06.fm  Page 198  Friday, September 23, 2005  5:13 AM



                 198    CHAPTER 6  ■  VISION



                        Example 6-18. getMean()
                        public int[] getMean(BufferedImage srcImg) {

                                int h = srcImg.getHeight();
                                int w = srcImg.getWidth();

                                BufferedImage dstImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

                                double red = 0;
                                double green = 0;
                                double blue = 0;

                                for (int y = 0; y < h; ++y) {
                                    for (int x = 0; x < w; ++x) {
                                        int srcPixel = srcImg.getRGB(x, y);
                                        // tally total colors for 3 components
                                        red = red + new Color(srcPixel).getRed();
                                        green = green + new Color(srcPixel).getGreen();
                                        blue = blue + new Color(srcPixel).getBlue();
                                    }
                                }
                                // get averages
                                int redAvg = (int) (red / (h * w));
                                int greenAvg = (int) (green / (h * w));
                                int blueAvg = (int) (blue / (h * w));
                                System.out.println("color mean=" + redAvg + "," + greenAvg + "," + blueAvg);
                                return new int[] { redAvg, greenAvg, blueAvg };
                            }

                        Code Objective

                        The objective here is to calculate the average red, green, and blue values of the image, using the
                        javax.media.jai.Histogram class.

                        Code Discussion

                        The first thing we do is set the number of bins and the minimum and maximum of the histograms.
                        Then we construct the histogram with those parameters. After that, we create a parameter block for
                        the operation. This is very similar to what I did with the FilterParameter class.
                            Next because Java Advanced Images uses PlanarImages instead of BufferedImages, we
                        have to create an output image to perform the operation. Once the operation completes, we
                        simply extract the histogram property from the output image and get the mean values for the
                        red, green, and blue of the image before writing the output to System.out. See Example 6-19.
   212   213   214   215   216   217   218   219   220   221   222