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

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



                 196    CHAPTER 6  ■  VISION




















                        Figure 6-15. The blue threshold

                            Still another way to use color is to filter it. So, rather than getting certain color components,
                        I’ll just show certain colors as greyscale images.

                        Code Objective
                        In this section, the objective is to use a color filter to show only the red pixels of an image in
                        greyscale, where higher reds appear white, and lower reds appear black.

                        Code Discussion

                        Here, instead of thresholding, we’re just converting the red components of an image into grey-
                        scale. See Example 6-17 and Figure 6-16.


                        Example 6-17. filterColor()
                        public BufferedImage filterColor(BufferedImage srcImg, Color c) {
                                int h = srcImg.getHeight();
                                int w = srcImg.getWidth();

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

                                for (int y = 0; y < h; ++y) {
                                    for (int x = 0; x < w; ++x) {
                                        int srcPixel = srcImg.getRGB(x, y);
                                        int colorValue = 0;
                                        // gets colors
                                        if (c == null) {
                                            colorValue = getGrey(srcPixel);
                                        } else if (c == Color.RED) {
                                            colorValue = new Color(srcPixel).getRed();
   210   211   212   213   214   215   216   217   218   219   220