This text tries to clear out the mystery of how to make motion detection using web cam with C#. My friend Walied want to capture video to his office by a web cam for 24 hrs, but the problem is that the space required on hard-disk is very extreme. So, he asked me to make a way to save disk space. Walied proposed to make a motion-detection circuit (IR, Ultra sonic) and connect it to the PC serial port and check for input every period of time. If there is any input then run the record program and start to capture video. But I replied that it’s a bad way because the thief will run away before the slow computer requests a web cam to start capturing video.
So my idea was to take a picture from a web cam every period of time (make it the current picture) and compare it with a previous picture and if we find a big difference between them we will save both pictures else will free memory from the old picture and make the new picture the current picture.
But there are two big problems:
- How to talk with your web cam and grab frame (picture) from it?
- How to compare the two pictures?
- There are two ways to talk to a web cam:
- Use DirectX's component called DirectShow (but unfortunately, DirectX doesn't provide DirectShow component for C#. NETMaster made an assembly to face this problem in his article DirectShow.NET). //Elgitaro: check this.
- Use a 3RDPARTY like cam server (you can find it in Laurent Kempé 's article Dynamic Webcam Image).
- There are also two ways to compare 2 pictures:
- By comparing each pixel's color for both pictures.
- Using filters to detect edges, then object recognition...
I think method (a) will work faster because we are talking about a period of 3 m secs.
This is my algorithm:
First, grab image from web cam called
Old. Second, grab another image from web cam after a while, called
Old by comparing each pixel color. If difference is greater than tested value (according to the quality of your web cam & light system you are using is 60 or 50 Hz), then save the two pictures. Finally, make the old picture the
Cur picture. Back to second step (infinite loop).
Let's write some code:
- Get the camserver.dll & ijl15.dll (copy both files to c:\windows\system32 and then write regsvr32 camserver.dll in Start->Run to register the COM component).
- Make new Windows project, paste three
PictureBoxes in your form, paste two
Buttons and finally, paste a
Timer control and set its
enabled property to
Your form looks something like this:
This program will not work as fast as I need because of the time for IO operation. So I use another technique to make it fast, by capturing a video to a panel and then grabbing image from it. This makes the application work faster as I need. This application is called CatchItV, and the first one called CatchIt (please try both and send me your comments).