Accessibility

Table of Contents

Webcam Motion Detection: Using the BitmapData API in Flash 8

Changing the Color of Pixels

You can change the color of any specific pixel in a BitmapData object using the setPixel() method. I could have used this method to check every pixel to see whether it is black (0xFF000000), and if it isn't, then I can change the color of the pixel to green (0xFF00FF00), as follows:

w=now.width;
h=now.height;
for(x=0;x<w;++x)
{
    for(y=0;y<h;++h)
    {
        if(now.getPixel(x,y) != 0xFF000000)
        {
            now.setPixel(x,y,0xFF00FF00);
        }
    }
}

However, the larger the image, the more times this code will have to run. This could potentially slow down the Flash Player due to excessive loop iterations. Luckily there is another method of the BitmapData class called threshold() that you can use to isolate and replace ranges of colors in a bitmap. Because it is a native method, it is written in C code and thus it is lightning fast compared to the above code:

now.threshold(now,now.rectangle,now.rectangle.topLeft,">",0xFF111111,0xFF00FF00,0x00FFFFFF,false);

The above snippet of code basically instructs Flash Player to copy the pixels from the bitmap called now into the bitmap called now (itself), changing any pixels that have a color value that is greater than almost black (0xFF111111) to green (0xFF00FF00).

Where to Go from Here

Download the full source code and look at how everything works together in context to achieve the desired effect. I've commented the code to help you understand it. Visit Set Pixel and Flight404 for some inspirational webcam experiments—they should inspire you to develop some ideas of your own. Try and take this experiment to the next level, by using the motion detection to actually move things around the screen or to create interactive special effects. If you create something cool, send me an e-mail—I'd love to see it!