Detect Intruders Using the Camera Object in Flash CS4
videos

Detect Intruders Using the Camera Object in Flash CS4

The rise of Flash Video and Web 2.0 over the past few years has also sparked an increase in the use of video as a communication tool. Along with this increased awareness there has also been a corresponding increase in the use of web cams that are either hard wired into the computer or sold as separate add ons.

In this tutorial I am going to show you, firstly, how to feed a web cam signal into Flash and, secondly, how to get in touch with your inner spy and use your web cam to detect intruders.

Intruder icon by Kyle Carrozza. No-Good Nicky occasionally appears in “Frog Raccoon Strawberry” weekends at dummcomics.com.

Before I Start

There is a caveat: This tutorial will play locally or in a web page. It will not cover how to broadcast the content you see to others on he web. To actually broadcast your feed- you and Aunt Phoebe waving to each other across oceans- you need to use a Flash Media Server 3.5 and that, my friends, is way out of the scope of this piece.

Step 1: Open Flash CS4 Professional

Create a New Document. When the document opens rename layer 1 to “Camera” and add a new layer named “actions”. Lock the actions layer.

Step 2: Add a Video Object

Click the Library tab and select New Video … from the Library options pop down. When the Video Properties dialog box opens be sure that Video (Actionscript – controlled) is selected and click OK. You will see a small video camera appear in your Library. This is the Video Object.

Step 3: Drag the Video Object to the Stage

With the Video Object selected, click the properties tab and change the Width and Height properties to 320 and 240. Give the selected object the Instance name of vidObj.

Step 4: Actions

Click once on the first frame of the actions layer and open the Script editor by selecting Window>Actions or pressing the F9 (PC) or Option-F9 (Mac) keys.

Step 5: Code

var myCam : Camera =  Camera.getCamera();
vidObj.attachCamera (myCam);

If you have never done this before, let’s step through the code.

The first line gives your web cam a variable name and, using the Camera class, tells Flash to hunt down the camera attached to your computer. I only have the iSight camera in my MacBook Pro working away which is why there is no value in the getCamera() method’s parameter. If I were to have a two cameras, let’s say a Logitech web cam, connected to the computer and I wanted to use it instead of the iSight I would enter getCamera(“1″). Note that cameras are strings not names. They are added in index order rather than alphanumeric order.

The second line simply attaches the video feed from the web cam to the video object on the stage. It is also important that you know when the attachCamera() method is used at runtime, the user will be prompted, by the Flash Player, to allow the use of the camera.

Step 6: Test the Movie.

There you go, only two lines of Actionscript and you’re now a movie star.

If you aren’t seeing anything the odds are practically 100 % that you have multiple cameras attached to your computer and Flash has picked the wrong one. Here’s how to fix that:

Step 7: Settings

Open the swf’s Context menu and select Settings. Right click (PC) or ctrl-click (Mac) on the object in the swf to open the swf’s Context menu.Select Settings to open the Flash Player Settings dialog box.

Step 8: Camera Icon

Click on the camera icon in the Flash Player settings. You will be presented with a list of cameras attached to your computer. Select the camera and click the Close button.

Step 9: Capturing Movement Using the Camera Object

In this example, borrowed from my book Foundation Flash Video CS3 by friendsofEd, we are, as I said earlier, “going to get in touch with our inner spy”. Though web cams are commonly used for “broadcast” purposes there is a method in the Camera class – setMotionLevel - that can be used to to turn on the camera when it “detects” a certain degree of motion and to then shoot and display an image from that capture. This is sort of how those infamous "Nanny Cams" work.

As an extra bonus, we won’t be using a Video Object, we are going to let ActionScript handle the lifting on that one. Here’s how:

Step 10: New Document

Open a new Flash document and set the stage dimension to 665 pixels wide and 450 pixels high.

Step 11: First Frame

Select the first frame of the movie and open the Actions panel.

Step 12: Bitmap and BitmapData

Enter the following ActionScript:

import flash.display.Bitmap;
import flash.display.BitmapData;

To start this project we will need a means of displaying the images captured by the web cam at the bottom of the stage. These two classes – Bitmap and BitmapData – make this possible.

Step 13: Housekeeping

Press the Return/Enter key twice and add the following code:

  var myBitmaps:Array = new Array();
  var myBitmapData:Array = new Array();
  for(var i:Number = 0; i < 4; i++){
  myBitmapData[i] = new BitmapData(320,240,false,0x00333333)
  myBitmaps[i] = new Bitmap(myBitmapData[i]);
  myBitmaps[i].x = 5 + 165 * i;
  myBitmaps[i].y = 315;
  myBitmaps[i].scaleX = 0.5;
  myBitmaps[i].scaleY = 0.5;
  addChild(myBitmaps[i]);
  }
  

Having called in the Bitmap and BitmapData classes, you now put them to work.

This “housekeeping” code block creates the four Bitmap and BitmapData objects used to display the captured images at the bottom of the stage.The block starts by creating a list that will be used to store the images and their background colors.

That process is the task of the for loop in the third line. In plain English it simply sets the number of images that can be displayed under the camera feed to 4.

The next line creates the boxes that hold those 4 images and makes sure they are 320×240 pixels in size, that they are not transparent – false – and that each box is filled with a dark gray color.

The remaining six lines place the captured images over the gray backgrounds and scale each one to fit. The last line – addChild(myBitmaps[i]); – is how the images will get stuck on the stage.

Step 14: Counter

Press the Return/Enter key twice and add the following line of ActionScript:

  var bitmapCounter:int = 0;
  

If there is a lot of movement the camera will be taking a lot of images that will need to be displayed. This counter ensures that only four images will be visible at any one time.

Step 15: Get it Working

Press the Return/Enter key twice and enter the following code block:

  var myCam:Camera = Camera.getCamera();
  myCam.setMotionLevel(70,50);
  var myVideo:Video = new Video();
  myVideo.attachCamera(myCam);
  myVideo.x = 172;
  myVideo.y = 10;
  addChild(myVideo);
  

This code block gets the web camera working. It starts with identifying which camera is is used through the getCamera() method. The next line of code is where the “magic” in this exercise happens.

The Camera class contains a setMotionLevel method that requires only two parameters. The first parameter is how much motion needs to be detected (Flash calls this an “Activity” event) before the camera fires up. The values here can be anything between 0 and 100. Think of this number as being a highly sensitive motion detector. The higher the value added the more motion must be detected to shoot the image. If someone is stealing apples from your apple tree a value of 0 would work because there really isn’t a lot going on. If you live on a residential street and the neighbors are tearing up and down the street in their sports cars, a level of 80 or 90 would be enough to capture an image you can show to the police.

The second parameter, though optional, specifies how many milliseconds of nothing happening must elapse before Flash gets bored and tells the camera to stand down. The default value is 2000 milliseconds (2 seconds). In this example we have dialed up the sensitivity by using a value of 50 milliseconds.

The final four lines create a “virtual” video object named myVideo and plugs the camera into it. That object is placed 172 pixels along the x axis and is flush with the top of the stage. The last line puts the object, called a Sprite, on the stage. For those of you new to “Sprites”, think of them as movieclips without a timeline.

Step 16: Detection

Press the Return/Enter key twice and add this final code block:

  myCam.addEventListener(ActivityEvent.ACTIVITY,motionHandler);
  function motionHandler(evt:Object) :void {
  myBitmapData[bitmapCounter].draw(myVideo);
  bitmapCounter++;
  if (bitmapCounter == 4){
  bitmapCounter = 0;
  }
  }
  

This code block black tells Flash what to do when the alarm goes off and motion is detected. In this case the Flash Player has detected an ActivityEvent based upon the setMotionLevel parameters. Having detected that event it fires the motionHandler function.

The motionHandler function tells Flash to do a frame grab and stick it at the bottom of the stage. The if statement makes sure that only 4 images are displayed at any one time.

Step 17: Wrap it Up

Save and test the movie.

Conclusion:

In this tutorial you have discovered that the world of Flash Video isn’t limited to stuff you shoot with a recorder or to youTube. It also allows you to use a web cam.

The first example showed you how only two lines of code are required to "get in the game".

The second example used a web cam to create a "Nanny Cam" based on the motion detected by the web cam. Once that motion is detected the movement is captured and an image from that capture is created and displayed at the bottom of the stage. The other interesting aspect of this example was the fact that the entire project was driven by ActionScript. There was nothing in the library and the Flash files consisted of nothing more than a few lines of basic code.

I hope you enjoyed following along!

Tags: Videos
  • http://www.woodswoodswoods.com Justin Woods

    Demo isn’t working for me… FF 3.5.4 with latest flash plugin

    • Brad Sedito

      right click on your vid preview, (i’m assuming your on a mac because i had the same problem), go to settings, select the camera pic, and under the drop down I had to choose USB video to get my built in iSight to work. If not, try the other options… good luck!

      Brad

      • http://www.woodswoodswoods.com Justin Woods

        Tried all of that and still didn’t work for me. I am on an iMac though.

      • http://snaptin.com Ian Yates
        Staff

        It should work just as Tom described (?) Brad’s advice should also have helped (his USB video tip does apply to iMacs – I checked)..

      • André

        When you code the tutorial there is a little trick that you can do for mac users:

        Using the Camera.names, wich returns an array, you can check wich one returns the name “USB Video Class Video”, if find it return that camera, if not fint return just Camera.getCamera();

      • burnandbass

        I am also on macbook and doesn’t work for me. A couple of mounths ago, when I tried augumented reality a friend of mine showed me the trick with Camera.names (as Andre said) and from now on doesn’t have any problems in my app. So just change the code. I go something like custom array class like

        static public function has(array:Array, what:*):Boolean {
        if (what is Function) {
        return array.filter(what).length > 0
        }else {
        return array.indexOf(what) >= 0
        }
        }

        var cameras:Array = Camera.names;
        if(cameras.has(“USB Video Class Video”)){
        myCam = Camera.getCamera(“USB Video Class Vide”)
        } else {
        myCam = Camera.getCamera()
        }

  • http://www.msdevstudio.com Mário Santos

    Nice, this can be very useful!!

    Waitting for the next one!

    Cheers

  • Pingback: uberVU - social comments

  • Pingback: Detect Intruders Using the Camera Object in Flash CS4 - Activetuts+ at Flash Designers

  • http://www.glasgoweb.co.uk will craig

    Adobe pulled together to celebrate the 10′th anniversary of Flash.

    wooow

    thats something to put on your CV

    i guess your never short of work

    its nice to see the big players in design on sites like this

    speak volumes for both the designer and flash den

    • http://snaptin.com Ian Yates
      Staff

      It’s “I guess you’re never short of work”.

      Your comment is much appreciated.

  • Pingback: Digital Signage Blog by Mirada Media » Blog Archive » Add Motion Capture to your Digital Signage

  • Pingback: Detect Intruders Using the Camera Object in Flash CS4 - Activetuts+ Virtual Library VLChina

  • Pingback: Detect Intruders Using the Camera Object in Flash CS4 - Activetuts+

  • Pingback: Detect Intruders Using the Camera Object in Flash CS4 - Activetuts+ | Camera case live today

  • André

    Now i say WOW, even you didnt use document class yet it´s very usefull tutorial, i really liked it. Thanks and congratulations

  • Pingback: Detect Intruders Using the Camera Object in Flash CS4 – Activetuts+

  • http://labs.dariux.com Dario Gutierrez

    Wow excellent application Tom I like it very much, It will help me to my new website. Thanks for this excellent tut.

  • http://everythingi.us/ Ninja

    great tut…….

    thanks heaps Tom

    keep up the good work!

  • http://everythingi.us/ Ninja

    also…

    how would you go about saving all of the images captured onto your hard drive?

    thanks

  • Scott

    Thanks Tom!!!
    Taking it to the next level, do you know of any code that will have one video object get “webcam 1″ and another video object get a second webcam hooked up to the same computer?

    In other words, two web cams through one computer into one Flash movie.

    Keep up the good work!

    • http://www.defsoft.com bharat saini

      try this……i’m adding cameras to buttons…Name camera1_btn and camera2_btn….on satge…..

      code for camera1_btn
      camera1_btn.addEventListener(MouseEvent.click,Camera1Started)function Camera1Started(evt:MouseEvent):void{

      var camera1:Camera = Camera.getCamera();
      var video1:Video = new Video(200,300);
      video1.x=200;
      video1.y=230;
      video.attachCamera(camera1);
      addChild(video1);
      camera1_btn.removeEventListener(MouseEvent.Click,Camera1Started)

      }

      camera2_btn.addEventListener(MouseEvent.click,Camera2Started)
      function Camera2Started(event:MouseEvent):void{

      var camera2:Camera = Camera.getCamera();
      var video2:Video = new Video(200,300);
      video2.x=400;
      video2.y=230;
      video.attachCamera(camera2);
      addChild(video2);
      camera2_btn.removeEventListener(MouseEvent.Click,Camera1Started)

      }

      when either function will fire just choose the camera name from the drop down ..they must we different otherwise u ll see the two different video’s but with same camera location..if u ll choose different cam whenerver u ll see camera sercurity dilaog box ……there u go the two web camera pointing at u ………

  • Tim

    The Demo COMPLETELY crashed my system. First it crashed the Firefox window it was in (latest version), then crashed a Safari window (latest version) I had open in a separate window, then crashed my windows xp pro system (SP 3). Have any ideas why that would happen?

    • http://www.defsoft.com bharat saini

      before i say the exact reason for this may i know the configruation of your pc please

  • chocorobokun

    hmm it’s weird,the demo only show two screenshot,and then it’s not detecting any motion anymore

  • http://www.defsoft.com bharat saini

    great tutorial but already know the stuff .its work for me if u can let me know how to implement the same method on server …yep u right with flash media player i would greatly appreciate this ..as i ‘m just a rookie on media server..Thanks in advance…

  • frogacult

    greate tutorial!! i want to ask you how i can save these images every time the camera detects motion?

  • Sabir Hussain

    Salam

    YA Ali as MADAD

    sir

    My name is sabir hussian , from pakistan, plase tell me, how can a build flash chat room.
    are you help me
    plase help me

    thanks for you tem

  • falahgs

    great tutorial ….
    very tanks