2014-08-28 1 views
-1
//---------------------------------------------------------------------------- 
// Copyright (C) 2004-2013 by EMGU. All rights reserved.  
//---------------------------------------------------------------------------- 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using Emgu.CV; 
using Emgu.CV.Structure; 
using Emgu.CV.VideoSurveillance; 
using Emgu.Util; 

namespace MotionDetection 
{ 
    public partial class Form1 : Form 
    { 
     private Capture _capture; 
     private MotionHistory _motionHistory; 
     private IBGFGDetector<Bgr> _forgroundDetector; 

     public Form1() 
     { 
     InitializeComponent(); 

     //try to create the capture 
     if (_capture == null) 
     { 
      try 
      { 
       _capture = new Capture(); 
      } 
      catch (NullReferenceException excpt) 
      { //show errors if there is any 
       MessageBox.Show(excpt.Message); 
      } 
     } 

     if (_capture != null) //if camera capture has been successfully created 
     { 
      _motionHistory = new MotionHistory(
       1.0, //in second, the duration of motion history you wants to keep 
       0.05, //in second, maxDelta for cvCalcMotionGradient 
       0.5); //in second, minDelta for cvCalcMotionGradient 

      _capture.ImageGrabbed += ProcessFrame; 
      _capture.Start(); 
     } 
     } 

     private void ProcessFrame(object sender, EventArgs e) 
     { 
     using (Image<Bgr, Byte> image = _capture.RetrieveBgrFrame()) 
     using (MemStorage storage = new MemStorage()) //create storage for motion components 
     { 
      if (_forgroundDetector == null) 
      { 
       //_forgroundDetector = new BGCodeBookModel<Bgr>(); 
       _forgroundDetector = new FGDetector<Bgr>(Emgu.CV.CvEnum.FORGROUND_DETECTOR_TYPE.FGD); 
       //_forgroundDetector = new BGStatModel<Bgr>(image, Emgu.CV.CvEnum.BG_STAT_TYPE.FGD_STAT_MODEL); 
      } 

      _forgroundDetector.Update(image); 

      capturedImageBox.Image = image; 

      //update the motion history 
      _motionHistory.Update(_forgroundDetector.ForegroundMask); 

      forgroundImageBox.Image = _forgroundDetector.ForegroundMask; 

      #region get a copy of the motion mask and enhance its color 
      double[] minValues, maxValues; 
      Point[] minLoc, maxLoc; 
      _motionHistory.Mask.MinMax(out minValues, out maxValues, out minLoc, out maxLoc); 
      Image<Gray, Byte> motionMask = _motionHistory.Mask.Mul(255.0/maxValues[0]); 
      #endregion 

      //create the motion image 
      Image<Bgr, Byte> motionImage = new Image<Bgr, byte>(motionMask.Size); 
      //display the motion pixels in blue (first channel) 
      motionImage[0] = motionMask; 

      //Threshold to define a motion area, reduce the value to detect smaller motion 
      double minArea = 100; 

      storage.Clear(); //clear the storage 
      Seq<MCvConnectedComp> motionComponents = _motionHistory.GetMotionComponents(storage); 

      //iterate through each of the motion component 
      foreach (MCvConnectedComp comp in motionComponents) 
      { 
       //reject the components that have small area; 
       if (comp.area < minArea) continue; 

       // find the angle and motion pixel count of the specific area 
       double angle, motionPixelCount; 
       _motionHistory.MotionInfo(comp.rect, out angle, out motionPixelCount); 

       //reject the area that contains too few motion 
       if (motionPixelCount < comp.area * 0.05) continue; 

       //Draw each individual motion in red 
       DrawMotion(motionImage, comp.rect, angle, new Bgr(Color.Red)); 
      } 

      // find and draw the overall motion angle 
      double overallAngle, overallMotionPixelCount; 
      _motionHistory.MotionInfo(motionMask.ROI, out overallAngle, out overallMotionPixelCount); 
      DrawMotion(motionImage, motionMask.ROI, overallAngle, new Bgr(Color.Green)); 

      //Display the amount of motions found on the current image 
      UpdateText(String.Format("Total Motions found: {0}; Motion Pixel count: {1}", motionComponents.Total, overallMotionPixelCount)); 

      //Display the image of the motion 
      motionImageBox.Image = motionImage; 
     } 
     } 

     private void UpdateText(String text) 
     { 
     if (InvokeRequired && !IsDisposed) 
     { 
      Invoke((Action<String>)UpdateText, text); 
     } 
     else 
     { 
      label3.Text = text; 
     } 
     } 

     private static void DrawMotion(Image<Bgr, Byte> image, Rectangle motionRegion, double angle, Bgr color) 
     { 
     float circleRadius = (motionRegion.Width + motionRegion.Height) >> 2; 
     Point center = new Point(motionRegion.X + motionRegion.Width >> 1, motionRegion.Y + motionRegion.Height >> 1); 

     CircleF circle = new CircleF(
      center, 
      circleRadius); 

     int xDirection = (int)(Math.Cos(angle * (Math.PI/180.0)) * circleRadius); 
     int yDirection = (int)(Math.Sin(angle * (Math.PI/180.0)) * circleRadius); 
     Point pointOnCircle = new Point(
      center.X + xDirection, 
      center.Y - yDirection); 
     LineSegment2D line = new LineSegment2D(center, pointOnCircle); 

     image.Draw(circle, color, 1); 
     image.Draw(line, color, 2); 
     } 

     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
     protected override void Dispose(bool disposing) 
     { 

     if (disposing && (components != null)) 
     { 
      components.Dispose(); 
     } 

     base.Dispose(disposing); 
     } 

     private void Form1_FormClosed(object sender, FormClosedEventArgs e) 
     { 
     _capture.Stop(); 
     } 
    } 
} 

나는 이력서 예를 emgu 컴파일왜 emgu cv 예제가 작동하지 않습니까?

그의 이름 MotionDetection

하지만 난 그 예를 컴파일 할 때, 결과는 오류이며 그 메시지를 나에게 대한

형식 이니셜을 제공합니다 'Emgu.CV.CvInvoke'는 예외를 던졌습니다.

은 내가 opencv_highgui290.dll, 내가 프로젝트에 대한 참조를 추가하고 난 복사 opencv_core290.dll이이 _capture = new Capture();

에 부착하고, opencv_imgproc290.dll는 여전히 didnt 한 일

을 폴더 프로젝트 만에 메시지는 여전히 동일합니다. 'Emgu.CV.CvInvoke'의 형식 초기화 프로그램에서 예외가 발생했습니다.

Visual Studio 2012 Ultimate 및 Win 8.1 을 사용하면 누구든지 도와 줄 수 있습니까?

감사합니다 :)

+0

질문에 게시 된 코드가 있다면 누군가가 대답 할 수 있다면 그것은 수치 스러울 것입니다. – Adam

답변

0

The type initializer for 'Emgu.CV.CvInvoke' threw an exception 당신이 클래스의 정적 생성자, 또는 해당 클래스의 정적 멤버의 초기화에 하나 볼 필요가 의미합니다. 그 위에 예외가 던져지는 곳의 InnerException 속성을 살펴 보겠습니다.

잘못되거나 불법적으로 사용되는 정적 방법이나 요소가있을 확률이 높습니다.

TypeInitializationException에 대해 여기에 수컷 거위를 타고 'Emgu.CV.CvInvoke'의 형식 이니셜이 파일을 EMGU.CV의 수단이 코드에 의해 dectecting되지 않은 예외가 발생했습니다 http://msdn.microsoft.com/en-us/library/system.typeinitializationexception(v=vs.110).aspx

+0

예를 들어 이고 컴파일 할 수 없습니다. 입니다. 튜토리얼은 단지 예제 프로젝트를 열고 그것을 컴파일한다. . 그것은 작동해야한다, 그러나 그것은 나를 위해 didnt한다. – user3094912

0

. 이는 시스템 종속성 때문입니다. 당신은 시각적 stdio에서 구성 관리자 창에 가서 필요한 플랫폼을 선택한 다음 각각의 dll 파일을 복사해야합니다 (x86 용 64 dll 파일과 x86 용 32 비트 dll은 emgu 웹 사이트에서 다운로드 할 수 있습니다). 그것을 복사하십시오 지금 emgu.cv.invoke와 같은 오류가 없습니다

관련 문제