C# - 检测面部和裁剪图像

Eri*_*lli 6 c# image-processing face-detection

我正在写一个HttpHandlerC#,它提供了大小调整的图像,等等等等......没有麻烦,我们有数百万个处理程序可供参考.

问题是我用"传统"尺寸拍摄的用户照片为4:3和16:9.但是这个处理程序需要以照片ID大小(4cm×3cm)提供照片,显然需要在用户脸部周围进行裁剪.面部位置变化很大(并不总是在图片中心).

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

Muh*_*han 9

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

Notes为了运行这个例子:

  • 创建Windows窗体应用程序
  • 添加PictureBox和Timer(并启用它) - 在x86系统上运行它
  • 确保您在执行代码的文件夹中具有OpenCV相关dll(包含在Emgu CV下载中).
  • 调整路径以找到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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我写的样本http://www.overroot.com/blog/wp-content/uploads/2011/03/FaceRecognition.zip