jump to navigation

Webcam in C#: Simple frame difference February 28, 2009

Posted by haryoktav in Taipei.
trackback

Moving object detection can be done by subtracting current image from background model. This is a simple example to subtract current image with previous image (as a background model) taken from webcam on your laptop.  It was written in C# 2005 using OpenCVDotNet.

The procedures are:

  1. Get current image from webcam
  2. if (the program just started) previous image = current image
  3. if (current image – previous image) < threshold then go to 5
  4. result = current image, go to 6
  5. result = zero (black)
  6. previous image = current image
  7. loop to step 1

and here is the code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenCVDotNet; //don't forget to add opencvdotnet.dll as Reference

namespace Webcam2
{
    public partial class Form1 : Form
    {
        private CVCapture capture;          //buffer for captured image from webcam
        private CVImage backgnd, diffe;     //buffer for previous image and subtract's result
        private byte threshold;             //threshold value

        private bool only_first = false;    //flag

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = !(timer1.Enabled); //toggle start/stop
            if (timer1.Enabled)
                capture = new CVCapture(0);     //start camera when timer enabled
            else
                capture.Release();              //stop camera when timer disabled
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            using (CVImage frame = capture.QueryFrame())  //get camera frame
            {
                frame.Resize(160, 120); //resize image to 160x120 pixel
                if (only_first  == false)   //only first time
                {
                    backgnd  = diffe = new CVImage(frame);  //copy buffer to get the same size
                    only_first = true;  //disable flag forever
                }
                //gray scale conversion
                for (int row = 0; row &amp;lt; frame.Height; ++row)
                {
                    for (int col = 0; col &amp;lt; frame.Width; ++col)
                    {
                        CVRgbPixel pixel = frame[row, col]; //get current pixel
                        byte bwValue = pixel.BwValue;   //get the gray color
                        frame[row, col] = new CVRgbPixel(bwValue, bwValue, bwValue);    //set current pixel to gray
                    }
                }
                //get different (subtraction)
                //if abs(current-previous)&amp;gt;threshold
                // then result=current
                // else result=black
                for (int row = 0; row &amp;lt; frame.Height; ++row)
                {
                    for (int col = 0; col &amp;lt; frame.Width; ++col)
                    {
                       if (Math.Abs(frame[row, col].BwValue - backgnd[row, col].BwValue)&amp;gt;threshold)
                            diffe[row, col] = frame[row, col];
                        else
                            diffe[row, col] = new CVRgbPixel(0,0,0);
                    }
                }
                backgnd = frame.Clone();    // save current to previous buffer
                pictureBox1.Image = frame.ToBitmap();  //display image
                pictureBox3.Image = diffe.ToBitmap();  

            }
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            threshold = (byte)trackBar1.Value;  //if slider changed, get new value
            label3.Text = threshold.ToString(); //print the value
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            trackBar1_Scroll(sender, e);    //when program started, get current slider value
        }

    }
}

Of course the result is not good enough. You can apply more complicated algorithm to perform. Using OpenCVDotNet is another big problem to me. It is hard to find the examples. I am thinking to use another wrapper e.g. AForge.

The project can be downloaded here. This is a rar-file. Please change the file extension after download from “.doc” to “.rar”.

Here, the snapshot.

webcam2

My friend in lab.

About these ads

Comments»

1. Ngo Xuan Dang - July 22, 2009

Hi,
Thanks for you code.
But I found that after each time do : backgnd = frame.Clone();
the memory usage is increase about 1MB, so that after run a few minute the memory is full.
Do you have other ways?
Thank you.

2. haryoktav - August 5, 2009

#Dang
Wow, I didn’t know about this.
You are right, at that time, I’ve just tried that the algorithm is working ^^
thanks for the feedback.
I am also still learn about memory management.

3. behdad - January 24, 2010

hi
thanks for your code.
can you help me????
how to setting or changing frame rate to rang(15-30)fps?

4. Naim Khan - March 4, 2010

hello friend,
will you please tell where could download .DLL file for this application still not getting any DLL .. if you have than plz send me at my email id…

5. AnhNgaLT - April 6, 2010

You can go to homepage of AForge to get DLL files
http://www.aforgenet.com/framework/downloads.html

6. Dionne Monic - July 5, 2010

I’ve been trying to use OpenCVDotNet but I’ve got this : ‘System.IO.FileNotFoundException?’
how can i resolve this problem ?

7. Prapan - December 9, 2010

Hello Hary,
I am very new programmer. I am trying running your shared code with visual studio ver 2008. I installed OpenCV 1.0 and CVopenDotnet 0.7 as suggestion, but I found that the error like this “Could not load file or assembly ‘OpenCVDotNet, Version=1.0.2615.24735, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)”. I am not sure if the dll file is compatible with VS2008. Could you help me!

8. prabakaran38 - September 27, 2011

I am prabakaran

I am trying running your shared code with visual studio ver 2010. I installed OpenCV 1.0 and CVopenDotnet 0.7 as suggestion, but I found that the error like this “Could not load file or assembly ‘OpenCVDotNet, Version=1.0.2615.24735, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)”. I am not sure if the dll file is compatible with VS2008. Could you help me!

9. prabakaran38 - September 27, 2011

I am prabakaran

I am trying running your shared code with visual studio ver 2010. I installed OpenCV 1.0 and CVopenDotnet 0.7 as suggestion, but I found that the error like this “Could not load file or assembly ‘OpenCVDotNet, Version=1.0.2615.24735, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)”. I am not sure if the dll file is compatible with VS2010. Could you help me!

10. Jimmy - November 5, 2011

got the same problem here..

I am trying running your shared code with visual studio ver 2010. I installed OpenCV 1.0 and CVopenDotnet 0.7 as suggestion, but I found that the error like this “Could not load file or assembly ‘OpenCVDotNet, Version=1.0.2615.24735, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)”. I am not sure if the dll file is compatible with VS2010. Could you help me!

11. Shaimaa - December 1, 2011

Please help…I keep getting the error “Could not load file or assembly ‘OpenCVDotNet, Version=1.0.2615.24735, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)”. on VS2005


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: