使用Emgu.CV侦测脸部从网络摄像头(C#)

问题描述:

我建立在C#中测试应用程序从一个摄像头检测脸部,并使用Emgu.CV侦测脸部从网络摄像头(C#)

我已经建立了它作为一个带有计时器的Windows窗体(timer1) ,一个用于显示网络摄像头输出的图片框(pictureBox1)和一个用于显示脸部数量的文本框(textBox2)。我已经通过NuGet(v3.1.0.1)安装了EmguCV并设置了一切。 EmguCV的大多数教程都是针对早期版本的,并且必要的HaarCascade类已折旧。但是,this Stack Overflow question为我提供了对我的代码的必要更新。

我现在已经设置了一切工作。网络摄像机在pictureBox1中显示更新图像。检测器假定在每次timer1滴答结束时在网络摄像机帧上工作,并且Faces[]阵列中的矩形数作为字符串输出到textBox2。然而,似乎没有任何工作。我无法识别任何东西。该程序正在运行,但检测到的人脸数量始终为0.如果我最初将NumberOfFaces变量设置为5之类的值,则Emgu代码会将其更改为0。所以,事情正在发生。我正在使用EmguCV提供的haar xml,但无济于事。有谁能够帮助我?

代码如下转储:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using Emgu.CV; 
using Emgu.CV.Structure; 
using Emgu.Util; 
using Emgu.CV.CvEnum; 

namespace FaceDetectTest 
{ 
    public partial class Form1 : Form 
    { 
     public Capture cap; 
     public CascadeClassifier haar; 
     public int NumberOfFaces; 
     public Rectangle[] Faces; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      cap = new Emgu.CV.Capture(0); 
      haar = new CascadeClassifier(@"C:\Users\Rob\AppData\Roaming\masterbeast\haarcascade_frontalface_alt_tree.xml"); 
      NumberOfFaces = 0; 
     } 

     private void timer1_Tick_1(object sender, EventArgs e) 
     { 
      using (Image<Bgr, byte> nextFrame = cap.QueryFrame().ToImage<Bgr, Byte>()) 
      { 
       if (nextFrame != null) 
       { 
       Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>(); 
       Faces = haar.DetectMultiScale(grayframe, 1.1, 1, new Size(100, 100), new Size(1000, 1000)); 
       NumberOfFaces = Faces.Length; 

      } 

      pictureBox1.Image = nextFrame.ToBitmap(); 
       textBox2.Text = NumberOfFaces.ToString(); 
      } 
     } 
    } 
} 

正如经常出现堆栈溢出,我发现了一个(部分)解决了这个几秒钟张贴的问题后。

什么似乎是造成该问题的条件声明if (nextFrame != null)。我不知道这是否与我的摄像头的刷新率或timer1计时器有关。现在删除它可以检测到人脸,但是我需要充分利用DetectMultiScale方法的参数,因为只有在完全正面和非常接近的情况下才能检测到它们。

如果有人能进一步阐明这一点,请成为我的客人;然而,它是有效的,这对我来说很重要。如果您来这里是为了使用Emgu.CV 3.1进行人脸检测的示例,请尝试使用上面的代码,而不使用该条件语句。