Cronicle8 0 Newbie Poster

Good afternoon,

I'm having somee trouble with a functional application, the only thing missing is switching the motion regions with an image. Any help is higly appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using AForge;
using AForge.Imaging;
using AForge.Video;
using AForge.Video.VFW;
using AForge.Video.DirectShow;
using AForge.Vision.Motion;

namespace MotionDetectorSample
{
    public partial class MainForm : Form
    {
        // opened video source
        private IVideoSource videoSource = null;
        // motion detector
        MotionDetector detector = new MotionDetector(
            new TwoFramesDifferenceDetector( ),
            new MotionAreaHighlighting( ) );
        // motion detection and processing algorithm
        private int motionDetectionType = 2;
        private int motionProcessingType = 2;

        // statistics length
        private const int statLength = 15;
        // current statistics index
        private int statIndex = 0;
        // ready statistics values
        private int statReady = 0;
        // statistics array
        private int[] statCount = new int[statLength];

        // counter used for flashing
        private int flash = 0;
        private float motionAlarmLevel = 0.015f;

        private List<float> motionHistory = new List<float>( );
        private int detectedObjectsCount = -1;

        // Constructor
        public MainForm( )
        {
            InitializeComponent( );
            Application.Idle += new EventHandler( Application_Idle );
        }

        // Application's main form is closing
        private void MainForm_FormClosing( object sender, FormClosingEventArgs e )
        {
            CloseVideoSource( );
        }

        // "Exit" menu item clicked
        private void exitToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.Close( );
        }

        // "Open" menu item clieck - open AVI file
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // create video source
                AVIFileVideoSource fileSource = new AVIFileVideoSource(openFileDialog.FileName);

                OpenVideoSource(fileSource);
            }

        }

        // Open local video capture device
        private void localVideoCaptureDeviceToolStripMenuItem_Click( object sender, EventArgs e )
        {
            VideoCaptureDeviceForm form = new VideoCaptureDeviceForm( );

            if ( form.ShowDialog( this ) == DialogResult.OK )
            {
                // create video source
                VideoCaptureDevice videoSource = new VideoCaptureDevice( form.VideoDevice );

                // open it
                OpenVideoSource( videoSource );
            }
        }

        // Open video source
        private void OpenVideoSource( IVideoSource source )
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // close previous video source
            CloseVideoSource( );

            // start new video source
            videoSourcePlayer.VideoSource = new AsyncVideoSource( source );
            videoSourcePlayer.Start( );

            // reset statistics
            statIndex = statReady = 0;

            // start timers
            timer.Start( );
            alarmTimer.Start( );

            videoSource = source;

            this.Cursor = Cursors.Default;
        }

        // Close current video source
        private void CloseVideoSource( )
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // stop current video source
            videoSourcePlayer.SignalToStop( );

            // wait 2 seconds until camera stops
            for ( int i = 0; ( i < 50 ) && ( videoSourcePlayer.IsRunning ); i++ )
            {
                Thread.Sleep( 100 );
            }
            if ( videoSourcePlayer.IsRunning )
                videoSourcePlayer.Stop( );

            // stop timers
            timer.Stop( );
            alarmTimer.Stop( );

            motionHistory.Clear( );

            // reset motion detector
            if ( detector != null )
                detector.Reset( );

            videoSourcePlayer.BorderColor = Color.Black;
            this.Cursor = Cursors.Default;
        }

        // New frame received by the player
        private void videoSourcePlayer_NewFrame( object sender, ref Bitmap image )
        {
            lock ( this )
            {
                if ( detector != null )
                {
                    float motionLevel = detector.ProcessFrame( image );

                    if ( motionLevel > motionAlarmLevel )
                    {
                        // flash for 2 seconds
                        flash = (int) ( 2 * ( 1000 / alarmTimer.Interval ) );
                    }

                    // check objects' count
                    if ( detector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing )
                    {
                        //Aqui é onde  deteta em quadrados
                        //IMPORTANTE-------------------------------------------//**//--------------------------------


                        BlobCountingObjectsProcessing countingDetector = (BlobCountingObjectsProcessing) detector.MotionProcessingAlgorithm;
                        //countingDetector.ObjectRectangles.SetValue("C:\\Documents and Settings\\NEXTV035\\Ambiente de trabalho\\Daniel\\farmer.png", );
                        //videoSourcePlayer.BackgroundImage = Bitmap.FromFile("C:\\Documents and Settings\\NEXTV035\\Ambiente de trabalho\\Daniel\\farmer.png");
                        detectedObjectsCount = countingDetector.ObjectsCount;
                    }
                    else
                    {
                        detectedObjectsCount = -1;
                    }

                    // accumulate history
                    //motionHistory.Add( motionLevel );
                    //if ( motionHistory.Count > 300 )
                    //{
                    //    motionHistory.RemoveAt( 0 );
                    //}

                }
            }
        }

        // Update some UI elements
        private void Application_Idle( object sender, EventArgs e )
        {
            objectsCountLabel.Text = ( detectedObjectsCount < 0 ) ? string.Empty : "Objetos: " + detectedObjectsCount;
        }

        // On timer event - gather statistics
        private void timer_Tick( object sender, EventArgs e )
        {
            IVideoSource videoSource = videoSourcePlayer.VideoSource;

            if ( videoSource != null )
            {
                // get number of frames for the last second
                statCount[statIndex] = videoSource.FramesReceived;

                // increment indexes
                if ( ++statIndex >= statLength )
                    statIndex = 0;
                if ( statReady < statLength )
                    statReady++;

                float fps = 0;

                // calculate average value
                for ( int i = 0; i < statReady; i++ )
                {
                    fps += statCount[i];
                }
                fps /= statReady;

                statCount[statIndex] = 0;

                fpsLabel.Text = fps.ToString( "F2" ) + " fps";
            }
        }

        // Turn off motion detection
        private void noneToolStripMenuItem1_Click( object sender, EventArgs e )
        {
            motionDetectionType = 0;
            SetMotionDetectionAlgorithm( null );
        }

        // Set Two Frames Difference motion detection algorithm
        private void twoFramesDifferenceToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionDetectionType = 1;
            SetMotionDetectionAlgorithm( new TwoFramesDifferenceDetector( ) );
        }

        // Set Simple Background Modeling motion detection algorithm
        private void simpleBackgroundModelingToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionDetectionType = 2;
            SetMotionDetectionAlgorithm( new SimpleBackgroundModelingDetector( true, true ) );
        }

        // Set motion area highlighting
        private void motionAreaHighlightingToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionAreaHighlightingToolStripMenuItem.Checked = true;
            motionBorderHighlightingToolStripMenuItem.Checked = false;
            blobCountingToolStripMenuItem.Checked = false;
            gridMotionAreaProcessingToolStripMenuItem.Checked = false;
            motionProcessingType = 4;
            SetMotionProcessingAlgorithm( new MotionAreaHighlighting( ) );
        }

        // Set motion borders highlighting
        private void motionBorderHighlightingToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionAreaHighlightingToolStripMenuItem.Checked = false;
            motionBorderHighlightingToolStripMenuItem.Checked = true;
            blobCountingToolStripMenuItem.Checked = false;
            gridMotionAreaProcessingToolStripMenuItem.Checked = false;
            motionProcessingType = 3;
            SetMotionProcessingAlgorithm( new MotionBorderHighlighting( ) );
        }

        // Set objects' counter
        private void blobCountingToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionAreaHighlightingToolStripMenuItem.Checked = false;
            motionBorderHighlightingToolStripMenuItem.Checked = false;
            blobCountingToolStripMenuItem.Checked = true;
            gridMotionAreaProcessingToolStripMenuItem.Checked = false;
            motionProcessingType = 2;
            SetMotionProcessingAlgorithm( new BlobCountingObjectsProcessing( ) );
        }

        // Set grid motion processing
        private void gridMotionAreaProcessingToolStripMenuItem_Click( object sender, EventArgs e )
        {
            motionAreaHighlightingToolStripMenuItem.Checked = false;
            motionBorderHighlightingToolStripMenuItem.Checked = false;
            blobCountingToolStripMenuItem.Checked = false;
            gridMotionAreaProcessingToolStripMenuItem.Checked = true;
            motionProcessingType = 1;
            SetMotionProcessingAlgorithm( new GridMotionAreaProcessing( 32, 32 ) );
        }

        private void SetMotionDetectionAlgorithm( IMotionDetector detectionAlgorithm )
        {
            lock ( this )
            {
                detector.MotionDetectionAlgorithm = detectionAlgorithm;
                motionHistory.Clear( );

                if ( detectionAlgorithm is TwoFramesDifferenceDetector )
                {
                    if (
                        ( detector.MotionProcessingAlgorithm is MotionBorderHighlighting ) ||
                        ( detector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing ) )
                    {
                        //motionProcessingType = 1;
                        SetMotionProcessingAlgorithm( new MotionAreaHighlighting( ) );
                    }
                }
            }
        }

        // Põe o método de deteção
        private void SetMotionProcessingAlgorithm( IMotionProcessing processingAlgorithm )
        {
            lock ( this )
            {
                detector.MotionProcessingAlgorithm = processingAlgorithm;
            }
        }

        private void motionToolStripMenuItem_DropDownOpening( object sender, EventArgs e )
        {
            ToolStripMenuItem[] motionDetectionItems = new ToolStripMenuItem[]
            {
                simpleBackgroundModelingToolStripMenuItem
            };
            ToolStripMenuItem[] motionProcessingItems = new ToolStripMenuItem[]
            {
                motionAreaHighlightingToolStripMenuItem,
                motionBorderHighlightingToolStripMenuItem,
                blobCountingToolStripMenuItem,
                gridMotionAreaProcessingToolStripMenuItem
            };

            bool enabled = ( motionDetectionType != 1 );
            motionBorderHighlightingToolStripMenuItem.Enabled = enabled;
            blobCountingToolStripMenuItem.Enabled = enabled;
        }

        private void defineMotionregionsToolStripMenuItem_Click( object sender, EventArgs e )
        {
            if ( videoSourcePlayer.VideoSource != null )
            {
                Bitmap currentVideoFrame = videoSourcePlayer.GetCurrentVideoFrame( );

                if ( currentVideoFrame != null )
                {
                    MotionRegionsForm form = new MotionRegionsForm( );
                    form.VideoFrame = currentVideoFrame;
                    form.MotionRectangles = detector.MotionZones;

                    if ( form.ShowDialog( this ) == DialogResult.OK )
                    {
                        Rectangle[] rects = form.MotionRectangles;

                        if ( rects.Length == 0 )
                            rects = null;

                        detector.MotionZones = rects;
                    }

                    return;
                }
            }

            MessageBox.Show( "É necessário iniciar o video antes de definir uma região.",
                "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information );
        }

        private void toolsToolStripMenuItem_DropDownOpening( object sender, EventArgs e )
        {
            localVideoCaptureSettingsToolStripMenuItem.Enabled =
                ( ( videoSource != null ) && ( videoSource is VideoCaptureDevice ) );
        }

        private void localVideoCaptureSettingsToolStripMenuItem_Click( object sender, EventArgs e )
        {
            if ( ( videoSource != null ) && ( videoSource is VideoCaptureDevice ) )
            {
                try
                {
                    ( (VideoCaptureDevice) videoSource ).DisplayPropertyPage( this.Handle );
                }
                catch ( NotSupportedException ex )
                {
                    MessageBox.Show( ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error );
                }
            }
        }

        // Temporizador usado para colorir a borda se movimento foi detetado
        private void alarmTimer_Tick( object sender, EventArgs e )
        {
            if ( flash != 0 )
            {
                videoSourcePlayer.BorderColor = ( flash % 2 == 1 ) ? Color.Black : Color.Red;
                flash--;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            VideoCaptureDeviceForm form = new VideoCaptureDeviceForm();

            if (form.ShowDialog(this) == DialogResult.OK)
            {
                // create video source
                VideoCaptureDevice videoSource = new VideoCaptureDevice(form.VideoDevice);

                // open it
                OpenVideoSource(videoSource);
            }
        }

        private void motionDetectionAlgorithmToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.