基本信息
源码名称:百度人脸识别SDK demo 可运行
源码大小:775.39M
文件格式:.rar
开发语言:C#
更新时间:2021-03-25
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 8 元 
   源码介绍


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace testface
{
    public partial class MainForm : Form
    {
        Thread thread;
        public static bool bExit = false;
        public static MainForm mainForm;
        private float kx, ky;
        int videoWidth, videoHeight, ifaceCount;
        Dictionary<uint, FaceAttrClass> faceAttrs;
        // 设置APPID/AK/SK
        string APP_ID = "XXX";
        string API_KEY = "XXXX";
        string SECRET_KEY = "XXX";
        public static Baidu.Aip.Face.Face client;
       
        Bitmap outBitmap;
        long sdk_begin;
        System.Timers.Timer timer;
        string[] strsMorning = {"","","" };
        Image loadingImage;

        public MainForm()
        {
            mainForm = this;
            InitializeComponent();
            videoWidth = 640;
            videoHeight = 480;
            kx = (float)pictureBox1.Width / videoWidth;
            ky = (float)pictureBox1.Height / videoHeight;
            faceAttrs = new Dictionary<uint, FaceAttrClass>();
            outBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            timer = new System.Timers.Timer(2000);
            loadingImage = Image.FromFile(Application.StartupPath   "\\assets\\loading.gif");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超时时间
            thread = new Thread(new ThreadStart(Face.FaceMain));
            thread.Start();
            //Face.test_face_track();
         
            ImageAnimator.Animate(loadingImage, new EventHandler((object o, EventArgs ea) =>
            {
                lock (this)
                {
                    ImageAnimator.UpdateFrames(o as Image);
                }
            }));
        }

      

        public void UpdateImg(byte[] buf, string res)
        {
            long t_begin = TimeUtil.get_time_stamp();
            long sdk_end = t_begin;
            float fontSize;
            Bitmap image = Image.FromStream(new MemoryStream(buf)) as Bitmap;
            //Bitmap bitmap = new Bitmap(image);
            Graphics g = Graphics.FromImage(outBitmap);
            g.DrawImage(image, 0,0, pictureBox1.Width, pictureBox1.Height);
            //textBox1.Text = res;
            dynamic obj = JsonConvert.DeserializeObject<dynamic>(res);
            if (obj.errno == 0 && obj.data.count > 0)
            {
                ifaceCount = obj.data.count;
                foreach (dynamic item in obj.data.list)
                {
                    bool bError = false;
                    int center_x = item.center_x;
                    int center_y = item.center_y;
                    float score = item.score;
                    uint faceId = item.face_id;
                    int width = item.width;
                    if (score < 0.8)
                        continue;

                    int faceX = (int)((center_x - 2 * width / 3));
                    if (faceX < 0)
                        faceX = 0;
                    else if (faceX > videoWidth)
                        faceX = videoWidth;

                    int faceY = (int)((center_y - width * 1.2));
                    if (faceY < 0)
                        faceY = 0;
                    else if (faceY > videoHeight)
                        faceX = videoHeight;

                    int faceWidth = (int)(width * 1.3);
                    if (faceX   faceWidth > videoWidth)
                        faceWidth = videoWidth - faceX;

                    int faceHeight = (int)(width * 1.8);
                    if (faceY   faceHeight > videoHeight)
                        faceHeight = videoHeight - faceY;
                    fontSize = (faceWidth * kx) / 12;
                    Rectangle rectangle = new Rectangle(faceX, faceY, faceWidth, faceHeight);
                    Rectangle drawRectangle = new Rectangle((int)(faceX * kx), (int)(faceY * ky), (int)(faceWidth * kx), (int)(faceHeight * ky));
                    FaceAttrClass temp;
                    string strBeauty = "未知";
                    string strAge = "未知";

                    if (!faceAttrs.TryGetValue(faceId, out temp))
                    {
                        if (faceAttrs.Count >= 20)
                            faceAttrs.Remove(faceAttrs.Keys.Min());
                        faceAttrs.Add(faceId, new FaceAttrClass()
                        {
                            frame = 0,
                            gifImage = Image.FromFile(Application.StartupPath   "\\assets\\loading.gif")
                        });
                        ImageAnimator.Animate(faceAttrs[faceId].gifImage, new EventHandler((object o, EventArgs e) =>
                        {
                            lock (this)
                            {
                                ImageAnimator.UpdateFrames(o as Image);
                            }
                        }));
                    }
                    else if (temp.frame == 8)
                    {
                        try
                        {

                            MemoryStream memoryStream = new MemoryStream();
                            Bitmap bmpCrop = image.Clone(rectangle, System.Drawing.Imaging.PixelFormat.Undefined);
                            bmpCrop.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                            FaceAttrThread faceAttrThread = new FaceAttrThread(memoryStream, faceAttrs, faceId);
                            new Thread(new ThreadStart(faceAttrThread.Run)).Start();


                        }
                        catch (Exception)
                        {
                            bError = true;
                        }
                    }
                    faceAttrs[faceId].frame  ;

                    float fillY = drawRectangle.Y - (3 * fontSize) - (fontSize * 0.1f);
                    g.FillRectangle(new SolidBrush(Color.FromArgb(151, 191, 41, 41)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);

                    if (faceAttrs[faceId].frame == 20)
                        ImageAnimator.StopAnimate(faceAttrs[faceId].gifImage, null);

                    if (faceAttrs[faceId].frame > 20)
                    {
                        strBeauty = faceAttrs[faceId].beauty > 0 ? faceAttrs[faceId].beauty.ToString() : "未知";
                        strAge = faceAttrs[faceId].age > 0 ? faceAttrs[faceId].age.ToString() : "未知";
                        label1.Invoke(new EventHandler(delegate
                        {
                            label1.Text = "年龄:"  strAge;

                        }));
                        label1.Invoke(new EventHandler(delegate
                        {
                            label2.Text = "颜值:"   strBeauty;
                        }));
                    }
                    else
                    {
                        lock (this)
                        {
                            g.DrawImage(faceAttrs[faceId].gifImage, drawRectangle.X   fontSize, fillY, 3 * fontSize, 3 * fontSize);
                        }
                        g.DrawString("特征分析中", new Font("宋体", fontSize, GraphicsUnit.Pixel), Brushes.White, drawRectangle.X   4.5f * fontSize, fillY   fontSize);
                    }
                }
            }
            else
                ifaceCount = 0;

            pictureBox1.CreateGraphics().DrawImage(outBitmap, 0, 0);
        }

        public void UpdateImgExt(System.Drawing.Bitmap image, TrackFaceInfo[] track_info, int faceCount)
        {
            long t_begin = TimeUtil.get_time_stamp();
            long sdk_end = t_begin;
            float fontSize;
            uint highestBeauty = uint.MaxValue;
            int iBeauty = 0, analysisFaceCount = 0;

            videoWidth = image.Width;
            videoHeight = image.Height;
            kx = (float)pictureBox1.Width / videoWidth;
            ky = (float)pictureBox1.Height / videoHeight;

            Graphics g = Graphics.FromImage(outBitmap);
            g.DrawImage(image, 0, 0, pictureBox1.Width, pictureBox1.Height);

            foreach (var item in faceAttrs)
            {
                faceAttrs[item.Key].valid = false;
            }

            if (faceCount > 0)
            {
                this.ifaceCount = faceCount;
                foreach (TrackFaceInfo item in track_info)
                {
                    float score = item.score;
                    if (score < 0.8)
                        continue;

                    bool bError = false;
                    int center_x = (int)item.box.mCenter_x;
                    int center_y = (int)item.box.mCenter_y;
                    
                    uint faceId = item.face_id;
                    int width = (int)item.box.mWidth;
                    FaceAttrClass temp;

                    if (!faceAttrs.TryGetValue(faceId, out temp))
                    {
                        if (faceAttrs.Count >= 20)
                            faceAttrs.Remove(faceAttrs.Keys.Min());

                        faceAttrs.Add(faceId, new FaceAttrClass()
                        {
                            frame = 0,
                            gifImage = loadingImage
                        });
                    }

                    faceAttrs[faceId].faceX = (int)((center_x - 2 * width / 3));
                    if (faceAttrs[faceId].faceX < 0)
                        faceAttrs[faceId].faceX = 0;
                    else if (faceAttrs[faceId].faceX > videoWidth)
                        faceAttrs[faceId].faceX = videoWidth;

                    faceAttrs[faceId].faceY = (int)((center_y - width * 1.2));
                    if (faceAttrs[faceId].faceY < 0)
                        faceAttrs[faceId].faceY = 0;
                    else if (faceAttrs[faceId].faceY > videoHeight)
                        faceAttrs[faceId].faceY = videoHeight;

                    faceAttrs[faceId].faceWidth = (int)(width * 1.35);
                    if (faceAttrs[faceId].faceX   faceAttrs[faceId].faceWidth > videoWidth)
                        faceAttrs[faceId].faceWidth = videoWidth - faceAttrs[faceId].faceX;

                    faceAttrs[faceId].faceHeight = (int)(width * 1.8);
                    if (faceAttrs[faceId].faceY   faceAttrs[faceId].faceHeight > videoHeight)
                        faceAttrs[faceId].faceHeight = videoHeight - faceAttrs[faceId].faceY;

                    if (faceAttrs[faceId].frame > 20)
                    {
                        if (faceAttrs[faceId].beauty > iBeauty)
                        {
                            highestBeauty = faceId;
                            iBeauty = faceAttrs[faceId].beauty;
                        }
                        analysisFaceCount  ;
                    }
                    faceAttrs[faceId].valid = true;
                }

                foreach (var item in faceAttrs)
                {
                    if (!item.Value.valid)
                        continue;
                    bool bError = false;
                    uint faceId = item.Key;

                    int faceX = faceAttrs[faceId].faceX;
                    int faceY = faceAttrs[faceId].faceY;
                    int faceWidth = faceAttrs[faceId].faceWidth;
                    int faceHeight = faceAttrs[faceId].faceHeight;

                    fontSize = (faceWidth * kx) / 12;
                    Rectangle rectangle = new Rectangle(faceX, faceY, faceWidth, faceHeight);
                    Rectangle drawRectangle = new Rectangle((int)(faceX * kx), (int)(faceY * ky), (int)(faceWidth * kx), (int)(faceHeight * ky));
                    
                    string strBeauty = "未知";
                    string strAge = "未知";

                    
                    if (faceAttrs[faceId].frame == 8)
                    {
                        try
                        {

                            MemoryStream memoryStream = new MemoryStream();
                            Bitmap bmpCrop = image.Clone(rectangle, System.Drawing.Imaging.PixelFormat.Undefined);
                            bmpCrop.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                            FaceAttrThread faceAttrThread = new FaceAttrThread(memoryStream, faceAttrs, faceId);
                            new Thread(new ThreadStart(faceAttrThread.Run)).Start();
                        }
                        catch (Exception)
                        {
                            bError = true;
                        }
                    }
                    faceAttrs[faceId].frame  ;;                   

                    //g.DrawRectangle(new Pen(Color.Gold, 2), drawRectangle);
        
                    float fillY = drawRectangle.Y - (3 * fontSize) - (fontSize * 0.1f);
                    if(analysisFaceCount >= 2 && faceId == highestBeauty)
                        g.FillRectangle(new SolidBrush(Color.FromArgb(151, 0xdb, 0x67, 0x34)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);
                    else
                        g.FillRectangle(new SolidBrush(Color.FromArgb(151, 0xbc, 0x6f, 0x6f)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);

                    if (faceAttrs[faceId].frame > 20)
                    {
                        strBeauty = faceAttrs[faceId].beauty > 0 ? faceAttrs[faceId].beauty.ToString() : "未知";
                        strAge = faceAttrs[faceId].age > 0 ? faceAttrs[faceId].age.ToString() : "未知";
                  
                        label1.Invoke(new EventHandler(delegate
                        {
                            label1.Text = "年龄:"   strAge;

                        }));
                        label1.Invoke(new EventHandler(delegate
                        {
                            label2.Text = "颜值:"   strBeauty;
                        }));
                       
                    }
                    else
                    {
                        lock (this)
                        {
                            g.DrawImage(faceAttrs[faceId].gifImage, drawRectangle.X   fontSize, fillY, 3 * fontSize, 3 * fontSize);
                        }
                        g.DrawString("特征分析中", new Font("宋体", fontSize, GraphicsUnit.Pixel), Brushes.White, drawRectangle.X   4.5f * fontSize, fillY   fontSize);
                    }
                }
            }
            else
            {
                ifaceCount = 0;
                faceAttrs.Clear();
            }

            pictureBox1.CreateGraphics().DrawImage(outBitmap, 0, 0);
        }
    }


    public class FaceAttrThread
    {
        MemoryStream _memoryStream;
        uint _faceId;
        Dictionary<uint, FaceAttrClass> _faceAttrs;

        public FaceAttrThread(MemoryStream memoryStream, Dictionary<uint, FaceAttrClass> faceAttrs, uint faceId)
        {
            _memoryStream = memoryStream;
            _faceAttrs = faceAttrs;
            _faceId = faceId;
        }

        public void Run()
        {
            FaceAttrClass temp;

            try
            {
                string image = Convert.ToBase64String(_memoryStream.GetBuffer());
                // 如果有可选参数
                var options = new Dictionary<string, object>{
                    {"face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype"},
                    {"max_face_num", 1},
                    {"face_type", "LIVE"}
                };
                // 带参数调用人脸检测
                dynamic result = MainForm.client.Detect(image, "BASE64", options);

                if (result.error_code == 0 && result.result.face_num > 0 && result.result.face_list[0].face_probability > 0.9 && _faceAttrs.TryGetValue(_faceId, out temp))
                {
                    _faceAttrs[_faceId].beauty = (int)(80   0.2 * float.Parse(result.result.face_list[0].beauty.ToString()));
                    _faceAttrs[_faceId].age = (int)float.Parse(result.result.face_list[0].age.ToString());
                    _faceAttrs[_faceId].expression = result.result.face_list[0].expression.type.ToString() == "none" ? 0 : 1;
                    if (result.result.face_list[0].gender.type.ToString() == "male")
                        _faceAttrs[_faceId].gender = 1;
                    else if (result.result.face_list[0].gender.type.ToString() == "female")
                        _faceAttrs[_faceId].gender = 2;
                    else
                        _faceAttrs[_faceId].gender = 0;
                    _faceAttrs[_faceId].glass = result.result.face_list[0].glasses.type.ToString() == "none" ? 0 : 1;
                }
            }
            catch (Exception)
            {

            }
            
        }
    }
}