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

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



                 192    CHAPTER 6  ■  VISION




















                        Figure 6-11. Threshold image: 0 min, 127 max

                            Next, I want to detect the motion in a webcam. The easiest way to do this is to subtract
                        frames from another. The resulting difference would be a frame of motion. Depending on the
                        number of frames per second, this will determine the size of the image.

                        Code Objective

                        The objective here is to detect motion.

                        Code Discussion

                        In this case, all we did was store the previous image globally, and then when the next image
                        comes in, we subtract the grey pixel difference. For this to work, I created a class-level field
                        called lastImage. This static image will be set at the end of the method for the next iteration.
                        Also, this will take some time to process, so I’ve reduced the frames per second to 5. See
                        Example 6-15 and the results in Figure 6-12.

                        Example 6-15. backgroundSubtract()
                            // get motion by subtracting background between current old image
                            public BufferedImage backgroundSubtract(BufferedImage srcImg) {
                               // make sure to set the frames per second to about 5!
                                int h = srcImg.getHeight();
                                int w = srcImg.getWidth();

                                // create dst image
                                BufferedImage dstImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

                                if (lastImage != null) {
                                    for (int y = 0; y < h; ++y) {
                                        for (int x = 0; x < w; ++x) {
                                            // get grey of image
                                            int srcPixel = getGrey(srcImg.getRGB(x, y));
                                            // get color of last image
                                            int diffPixel = getGrey(lastImage.getRGB(x, y));



                   97022d2480fe4a63cfdfa123a6e70098
   206   207   208   209   210   211   212   213   214   215   216