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

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



                 194    CHAPTER 6  ■  VISION


                        6.3 Color Processing

                        In the last section, we processed pixels but did not use their individual color components for
                        anything. To illustrate how we can use the colors of an image, we’ll threshold the colors of an
                        image versus the image’s greyscale. In the next few examples, I’ll threshold three colors—red,
                        green, and blue—for the three beverage cans.

                        Code Objective

                        The objective here is to perform a threshold operation on the three different color
                        components.


                        Code Discussion
                        This method is similar to thresholding except for the added parameter Color. This color is then
                        used to get the specific color component for the threshold. You can see from the three images
                        that you can almost make out which cans are red, green, and blue. See Example 6-16 and
                        Figures 6-13, 6-14, and 6-15.


                        Example 6-16. thresholdColor()
                        public BufferedImage thresholdColor(BufferedImage srcImg, int min, int max,
                                    Color c) {
                                // get h & w
                                int h = srcImg.getHeight();
                                int w = srcImg.getWidth();
                                //destination image
                                BufferedImage dstImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                                // get pixels
                                for (int y = 0; y < h; ++y) {
                                    for (int x = 0; x < w; ++x) {
                                        // get color
                                        int srcPixel = srcImg.getRGB(x, y);
                                        int colorValue = 0;
                                        // get color values for color sent
                                        if (c == null) {
                                            colorValue = getGrey(srcPixel);
                                        } else if (c == Color.RED) {
                                            colorValue = new Color(srcPixel).getRed();
                                        } else if (c == Color.GREEN) {
                                            colorValue = new Color(srcPixel).getGreen();
                                        } else if (c == Color.BLUE) {
                                            colorValue = new Color(srcPixel).getBlue();
                                        }
   208   209   210   211   212   213   214   215   216   217   218