2011-09-10 45 views
5

我在C#中编写HttpHandler,它提供调整大小的图像和等等等等......没有麻烦,我们有数百万处理程序用作参考。C# - 检测脸部和裁剪图像

问题是我的用户以“传统”尺寸拍摄的照片为4:3和16:9。但是这个处理器需要以照片ID大小(4厘米×3厘米)提供照片,并且显然需要在用户脸部周围裁剪。脸部位置差异很大(并不总是在图片中心)。

那么,我可以用什么样的算法来检测面部中心,然后在这个点上裁剪图像?

回答

8

您可以使用HaarCascade类EmguCV(OpenCV中的DOTNET的端口)http://www.emgu.com/wiki/index.php/Face_detection

注意事项,以运行这个例子:

  • 创建一个Windows窗体应用程序
  • 添加一个PictureBox和一个定时器(并启用它) - 在x86系统上运行它
  • 请确保您的代码执行文件所在的文件夹中包含OpenCV相关DLL(包含在Emgu CV下载中) ES。
  • 调整的路径来寻找Haarcascade XML(代码的最后一行)
using System; 
using System.Windows.Forms; 
using System.Drawing; 
using Emgu.CV; 
using Emgu.Util; 
using Emgu.CV.Structure; 
using Emgu.CV.CvEnum; 

namespace opencvtut 
{ 
    public partial class Form1 : Form 
    { 
       private Capture cap; 
       private HaarCascade haar; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
       using (Image<Bgr, byte> nextFrame = cap.QueryFrame()) 
       { 
         if (nextFrame != null) 
         { 
           // there's only one channel (greyscale), hence the zero index 
           //var faces = nextFrame.DetectHaarCascade(haar)[0]; 
           Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>(); 
           var faces = 
             grayframe.DetectHaarCascade(
               haar, 1.4, 4, 
               HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, 
               new Size(nextFrame.Width/8, nextFrame.Height/8) 
               )[0]; 

           foreach (var face in faces) 
           { 
             nextFrame.Draw(face.rect, new Bgr(0,double.MaxValue,0), 3); 
           } 
           pictureBox1.Image = nextFrame.ToBitmap(); 
         } 
       } 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      // passing 0 gets zeroth webcam 
         cap = new Capture(0); 
      // adjust path to find your xml 
         haar = new HaarCascade(
       "..\\..\\..\\..\\lib\\haarcascade_frontalface_alt2.xml"); 
     } 
    } 
} 

这里是我写的http://www.overroot.com/blog/wp-content/uploads/2011/03/FaceRecognition.zip

1

有一个example on CodeProject,看起来这将是一个非常好的开始。

+0

本文不再CodeProject上,因为它是另一种工作的直接复制在线(查看链接)。 –

1

如果您正在寻找剪裁图片的方法,可以使用名为Face API的Microsoft Cognitive Service,它可以分隔照片上所有人的脸部,它会返回一个JSON,其中包含返回给您的Rectangle结构的元素,那么你可以裁剪和调整图像的大小,只要你想。

在这里你可以看到更多的资料a一下:FaceAPI