Motion Detection In Flash (AS2 and AS3) and C#
Currently working on some motion detection with flash/c# and webcams right now. Here’s a basic overview of some motion detection source files and tricks. Most motion detection is based on snapshots and finding brightness of a pixel with all combined colors, then comparing that to previous snapshots to detect enough variance and thus movement. If you have a webcam hooked up, this sample in Flash AS3 highlights this well showing the camera on the left, then the brightness snapshots on the right. It also has an indicator to the amount of movement due to much brightness.
C#
Here is a nice example of motion detection using various motion detection algorithms in C#. This is built on the very slick AForge.NET Computer Imaging Library.

If you ever wanted your own motion detection or recording it is all possible with the basics of checking brightness and snapshots in the most simple form checking how much change or variance their was to bright pixels or the count of bright pixels compared to previous snapshots.
// Calculate white pixels
private int CalculateWhitePixels( Bitmap image )
{
int count = 0;
// lock difference image
BitmapData data = image.LockBits( new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed );
int offset = data.Stride - width;
unsafe
{
byte * ptr = (byte *) data.Scan0.ToPointer( );
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, ptr++ )
{
count += ( (*ptr) >> 7 );
}
ptr += offset;
}
}
// unlock image
image.UnlockBits( data );
return count;
}
Flash AS2
For instance the basics here show how you can compare each pixel and the change in the brightness for each pixel:
//accuracy
tolerance=10;
//color of the current pixel in the current snapshot
nc=now.getPixel(x,y);
//red channel
nr=nc>>16&0xff;
//green channel
ng=nc>>8&0xff;
//blue channel
nb=nc&0xff;
//brightness
nl=Math.sqrt(nr*nr + ng*ng + nb*nb)
//color of the same pixel in the previous snapshot
bc=before.getPixel(x,y);
//red channel
br=bc>>16&0xff;
//green channel
bg=bc>>8&0xff;
//blue channel
bb=bc&0xff;
//brightness
bl=Math.sqrt(br*br + bg*bg + bb*bb);
//difference in brightness between now and before
d=Math.round(Math.abs(bl-nl));
if(d>tolerance)
{
//there was a change in this pixel
}
Flash AS3
Here is a link to grab a conversion of the AS2 Flash motion detection above to AS3.
Source of AS3 motion detection here.
C# or other hardware accelerated capable kits are faster but AS3 and Flash with the new AVM2 virtual machine should be about 10 times faster than AS2 as much of the improvement in performance and the virtual machine is on iteration speed increases such as loops (i.e. pixel loop).







