CSkin博客

标题: 【人脸识别EmguCV】动态人脸检测。中文名字识别 [打印本页]

作者: wtujoxk    时间: 2014-8-8 09:44
标题: 【人脸识别EmguCV】动态人脸检测。中文名字识别
人脸识别EmguCV
动态人脸检测。中文名字识别
识别后语音播报



人脸识别EmguCV.rar (568.14 KB, 下载次数: 1667)   
emgu支持库,装完后需配置下环境
http://sourceforge.net/projects/emgucv/

[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Threading;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using Emgu.CV.UI;

namespace MultiFaceRec
{
    public partial class FrmPrincipal : Form
    {
        //Declararation of all variables, vectors and haarcascades
        Image<Bgr, Byte> currentFrame;
        Capture grabber;
        HaarCascade face;
        HaarCascade eye;
        MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
        Image<Gray, byte> result, TrainedFace = null;
        Image<Gray, byte> gray = null;
        List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
        List<string> labels = new List<string>();
        List<string> NamePersons = new List<string>();
        int ContTrain, NumLabels, t;
        string name, namess = null, names = null;
        Dictionary<string, Rectangle> foundPeople = new Dictionary<string, Rectangle>();
        float xfactor;
        float yfactor;

        public FrmPrincipal()
        {
            InitializeComponent();

            try
            {
                //Initialize the capture device
                grabber = new Capture();
                grabber.QueryFrame();
                //Initialize the FrameGraber event
                Application.Idle += new EventHandler(FrameGrabber);
                if (grabber != null)
                    grabber.FlipHorizontal = !grabber.FlipHorizontal;
                button1.Enabled = false;
            }
            catch (Exception)
            {
                MessageBox.Show("没有摄像头!");
            }

            //Load haarcascades for face detection
            face = new HaarCascade("haarcascade_frontalface_default.xml");
            //eye = new HaarCascade("haarcascade_eye.xml");
            try
            {
                //Load of previus trainned faces and labels for each image
                string Labelsinfo = File.ReadAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt");
                string[] Labels = Labelsinfo.Split('%');
                NumLabels = Convert.ToInt16(Labels[0]);
                ContTrain = NumLabels;
                string LoadFaces;

                for (int tf = 1; tf < NumLabels + 1; tf++)
                {
                    LoadFaces = "face" + tf + ".bmp";
                    trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/TrainedFaces/" + LoadFaces));
                    labels.Add(Labels[tf]);
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
                MessageBox.Show("Nothing in binary database, please add at least a face", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Idle += new EventHandler(FrameGrabber);               
                button1.Enabled = false;
            }
            catch (Exception)
            {               
            }               
        }
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Idle -= new EventHandler(FrameGrabber);
                button1.Enabled = true;
            }
            catch (Exception)
            {
            }   
        }
        private void button2_Click(object sender, System.EventArgs e)
        {
            try
            {
                //Trained face counter
                ContTrain = ContTrain + 1;

                //Get a gray frame from capture device
                gray = grabber.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

                //Face Detector
                MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
                face,
                1.2,
                10,
                Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                new Size(20, 20));

                //Action for each element detected
                foreach (MCvAvgComp f in facesDetected[0])
                {
                    TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();
                    break;
                }

                //resize face detected image for force to compare the same size with the
                //test image with cubic interpolation type method
                TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
                trainingImages.Add(TrainedFace);
                labels.Add(textBox1.Text);

                //Show face added in gray scale
                imageBox1.Image = TrainedFace;

                //Write the number of triained faces in a file text for further load
                File.WriteAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", trainingImages.ToArray().Length.ToString() + "%");

                //Write the labels of triained faces in a file text for further load
                for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
                {
                    trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/TrainedFaces/face" + i + ".bmp");
                    File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", labels.ToArray()[i - 1] + "%");
                }

                MessageBox.Show(textBox1.Text + "´s face detected and added :)", "Training OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Enable the face detection first", "Training Fail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        /// <summary>
        /// 人脸识别与检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrameGrabber(object sender, EventArgs e)
        {
            label3.Text = "0";
            //label4.Text = "";
            NamePersons.Add("");


            //Get the current frame form capture device
            currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

            //Convert it to Grayscale
            gray = currentFrame.Convert<Gray, Byte>();

            //Face Detector
            MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
            face,
            1.2,
            10,
            Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
            new Size(20, 20));

            foundPeople.Clear();
            //Action for each element detected
            foreach (MCvAvgComp f in facesDetected[0])
            {
                t = t + 1;
                result = currentFrame.Copy(f.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
                //draw the face detected in the 0th (gray) channel with red color
                currentFrame.Draw(f.rect, new Bgr(Color.Red), 2);


                if (trainingImages.ToArray().Length != 0)
                {
                    //TermCriteria for face recognition with numbers of trained images like maxIteration
                    MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);

                    //Eigen face recognizer
                    EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
                       trainingImages.ToArray(),
                       labels.ToArray(),
                       5000,
                       ref termCrit);

                    name = recognizer.Recognize(result);
                    foundPeople[name] = f.rect;

                    //Draw the label for each face detected and recognized
                    //currentFrame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.LightGreen));                  

                }               

                NamePersons[t - 1] = name;
                NamePersons.Add("");


                //Set the number of faces detected on the scene
                label3.Text = facesDetected[0].Length.ToString();

            }
            t = 0;

            //Names concatenation of persons recognized
            for (int nnn = 0; nnn < facesDetected[0].Length; nnn++)
            {
                names = names + NamePersons[nnn] + ", ";
            }
            //Show the faces procesed and recognized
            imageBoxFrameGrabber.Image = currentFrame;
            label4.Text = names;
            namess = names;
            names = "";
            //Clear the list(vector) of names
            NamePersons.Clear();

        }
    }
}










作者: xiaobo    时间: 2014-8-8 09:56
这么高端的东西,没有摄像头怎么能行呢~可惜没法测试咯
作者: cjkall    时间: 2014-8-8 10:18
高大上..........
作者: xiaoben“爱小号    时间: 2014-8-9 09:39
这么高端的东西,没有摄像头怎么能行呢~可惜没法测试咯
作者: 王龙    时间: 2014-10-6 13:49
前排留名
作者: cjkall    时间: 2014-12-7 00:07
怎么配置啊?
作者: 辰晓晨    时间: 2014-12-11 21:55
这么高端的东西,没有摄像头怎么能行呢~可惜没法测试咯
作者: qq443061626    时间: 2014-12-12 11:50
没有摄像头~~~咋么个测试
作者: jidysontao    时间: 2015-3-29 14:21
测试了下,无法取得人脸信息.
作者: huangyouwei    时间: 2015-7-11 18:22
谢谢分享,楼主辛苦了
作者: huangyouwei    时间: 2015-7-11 18:27
楼主怎么运行出错“Emgu.CV.CvInvoke”的类型初始值设定项引发异常。弹出这个错误
作者: suncathay    时间: 2016-2-1 11:21
谢谢分享,楼主辛苦了
作者: Qyang    时间: 2016-3-19 03:19
有没有OpenCVC的,
作者: liqud    时间: 2016-3-19 21:35
下载来学习一下
作者: userlm    时间: 2016-3-20 10:31
非常感谢,正好需要
作者: userlm    时间: 2016-3-20 10:31
学习学习
作者: windy    时间: 2016-7-8 16:36
太牛逼啊!!!!!!!!!!!
作者: xftjywx    时间: 2017-3-8 16:05
谢谢分享,楼主辛苦了
作者: 752828765    时间: 2019-2-24 15:49
谢谢楼主!!!
作者: Mr黄鹤    时间: 2019-2-27 14:04
学习一下
作者: jacksonwong    时间: 2019-5-25 13:17
谢谢分享!
作者: tqx007    时间: 2019-7-9 11:46
为啥打不开
作者: caozw2002    时间: 2020-2-16 11:33
谢谢分享




欢迎光临 CSkin博客 (http://bbs.cskin.net/) Powered by Discuz! X3.2