In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

背景差分 2値化 background sbtraction binary

Get Adobe Flash player
by ton 01 Dec 2010
/*
 * flashで背景差分のテスト
 * 2値化バージョン
 * 
 * [set background]ボタンを押したときのキャプチャ画像と現在のキャプチャ画像で差分をとります
 * スライダーで閾値を調節できます
 */
package {
	import com.bit101.components.HUISlider;
	import com.bit101.components.Label;
	import com.bit101.components.PushButton;
	import flash.display.*;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.system.Security;
	import net.hires.debug.Stats;

    public class BackgroundSubtraction extends Sprite {
        private const BG_COLOR:uint = 0xFFFFFFFF;
        private const DIFF_COLOR:uint = 0xFF0077FF;
        private const DEFAULT_THRESHOLD:uint = 0x30;

        private var video:Video;
        private var bgBmd:BitmapData;
        private var nowBmd:BitmapData;
        private var p:Point = new Point();
        private var slider:HUISlider;
        private var button:PushButton;
        private var threshold:uint;
        
        public function BackgroundSubtraction():void {
			Security.allowDomain("*");
            var camera:Camera = Camera.getCamera();
            if (!camera) {
                new Label(this, 10, 10, "can't use camera");
                return ;
            }
            
            camera.setMode(stage.stageWidth, stage.stageHeight, 30);
            video = new Video(camera.width, camera.height);
            video.attachCamera(camera);
            
            bgBmd = new BitmapData(video.width, video.height, false);
            nowBmd = new BitmapData(video.width, video.height, false);
			
            addChild(new Bitmap(nowBmd));
            
            addChild(new Stats());

            slider = new HUISlider(this, 100, 10, "threshold", setThreshold);
            slider.setSliderParams(0, 0xFF, DEFAULT_THRESHOLD);
            slider.tick = 1;
            
            button = new PushButton(this, 350, 10, "set background", function():void {bgBmd.draw(video);});
            
            setThreshold();
            
            addEventListener(Event.ENTER_FRAME, update);
        }
        
        private function setThreshold(e:Event = null):void {
            var v:uint = slider.value;
            threshold = 0xFF000000 | v << 16 | v << 8 | v;
        }

        private function update(e:Event):void {
            nowBmd.draw(bgBmd);
            nowBmd.draw(video, null, null, BlendMode.DIFFERENCE);
            nowBmd.threshold(nowBmd, nowBmd.rect, p, "<=", threshold, BG_COLOR);
            nowBmd.threshold(nowBmd, nowBmd.rect, p, "!=", BG_COLOR, DIFF_COLOR);
        }
    }
}