Introduction
This text tries to clear out the mystery of how to make motion detection using a webcam in C#. My friend Walied wants to capture video in his office with a webcam for 24 hours, but the problem is that the space required on a hard disk is very extreme. So, he asked me to find a way to save disk space. Walied proposed to make a motion-detection circuit (IR, ultrasonic) 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 webcam to start capturing video.
So my idea was to take a picture from a webcam 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; otherwise, we will free memory from the old picture and make the new picture the current picture.
But there are two big problems:
- How do you communicate with your webcam and grab a frame (picture) from it?
- How do I compare the two pictures?
Solution
- 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 3rd party 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 msec.
Try
This is my algorithm:
First, grab an image from a webcam called Old
. Second, grab another image from a webcam after a while, called Cur
. Compare Cur
& Old
by comparing each pixel color. If the difference is greater than the tested value (according to the quality of the webcam & light system you are using at 60 or 50 Hz), then save the two pictures. Finally, make the old picture the Cur
picture. Back to the 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 a new Windows project, paste three
PictureBox
es in your form, paste two Button
s and finally, paste a Timer
control and set its enabled
property to false
.
Your form looks something like this:
Catch
This program will not work as fast as I need because of the time for IO operations. So I use another technique to make it fast, by capturing a video on a panel and then grabbing an image from it. This makes the application work as fast as I need. This application is called CatchItV, and the first one is called CatchIt (please try both and send me your comments).