百度人臉識別


1.首先是去百度智能雲(http://ai.baidu.com/tech/face?track=cp:ainsem|pf:pc|pp:chanpin-renlianshibie|pu:renlianshibie-pinpai|ci:|kw:10002421)注冊一個賬號,填寫有些相關的信息。

2.在產品服務找到人臉識別

 

 3.創建應用,得到對應的AppID,API Key,Secret Key

3.新建組

4.新建用戶

 

 5.添加人臉

 

 6.新建一個控制台應用程序

8.先關代碼

using AForge.Video.DirectShow;
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private FilterInfoCollection videoDevices = null;
        /// <summary>
        /// 連接並且打開攝像頭
        /// </summary>
        private void CameraConn()
        {
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("請插入視頻設備");
                return;
            }
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            CameraConn();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            /// 獲取電腦已經安裝的視頻設備
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices != null && videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            /// 獲取電腦已經安裝的視頻設備
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices != null && videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("請插入視頻設備");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + ".jpg";
                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("攝像頭異常:" + ex.Message);
            }
        }

        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }
        /// <summary>
        /// 圖片轉換為Base64
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private string ImgToBase64String(string image)
        {
            try
            {
                Bitmap bmp = new Bitmap(image, true);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();

                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 注冊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            string sl = "";
            #region 拍照
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("請插入視頻設備");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + ".jpg";
                    sl = picName;
                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("攝像頭異常:" + ex.Message);
            }
            #endregion
            var image = ImgToBase64String(sl);
            var imageType = "BASE64";

            // 設置APPID/AK/SK
            var API_KEY = "***";                   //你的 Api Key
            var SECRET_KEY = "***";        //你的 Secret Key
            var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超時時間

            //取決於image_type參數,傳入BASE64字符串或URL字符串或FACE_TOKEN字符串
            //你共享的圖片路徑(點擊路徑可直接查看圖片)

            //注冊人臉
            var groupId = "group1";
            var userId = textBox6.Text;
            // 調用人臉注冊,可能會拋出網絡等異常,請使用try/catch捕獲
            var result = client.UserAdd(image, imageType, groupId, userId);

            JObject _jObject = result;
            bool sf = false;
            foreach (var item in _jObject)
            {
                if (item.Key == "error_code")
                {
                    if (item.Value.ToString() == "0")
                    {
                        sf = true;
                        MessageBox.Show("注冊成功!");
                        MessageBox.Show(result.ToString());
                    }
                    else
                    {
                        sf = false;
                        MessageBox.Show("注冊失敗!");
                        MessageBox.Show(result.ToString());
                    }
                }
            }
        }
        /// <summary>
        /// 人臉識別API參數初始化
        /// </summary>
        /// <returns></returns>
        private Baidu.Aip.Face.Face GetFacaClient()
        {
            // 設置APPID/AK/SK
            string APP_ID = "***";
            string API_KEY = "***";
            string SECRET_KEY = "**";

            Face client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超時時間

            return client;
        }
        /// <summary>
        /// 人臉搜索,從人臉庫中查詢是否有合適的人像
        /// </summary>
        /// <param name="ImageBase">圖片Base64值</param>
        /// <returns></returns>
        public Newtonsoft.Json.Linq.JObject SearchDemo(string ImageBase)
        {
            string image = ImageBase;
            string imageType = "BASE64";
            string groupIdList = "group1";//你的應用名字

            Face client = GetFacaClient();
            // 調用人臉搜索,可能會拋出網絡等異常,請使用try/catch捕獲
            var result = client.Search(image, imageType, groupIdList);

            return result;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string sl = "";
            #region 拍照
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("請插入視頻設備");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + ".jpg";
                    sl = picName;
                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("攝像頭異常:" + ex.Message);
            }
            #endregion
            string ImageBase = ImgToBase64String(sl);
            var msg = SearchDemo(ImageBase);

            bool sf = false;
            JObject _jObject = msg;
            StringBuilder str = new StringBuilder();
            foreach (var item in _jObject)
            {
                str.Append(item.Key + ":" + item.Value + ",");
                if (item.Key == "error_code")
                {
                    if (item.Value.ToString() == "0")
                    {
                        sf = true;
                    }
                    else
                    {
                        sf = false;
                    }
                }
            }

            if (sf)
            {
                group_id.Text = "所在組:" + msg["result"]["user_list"][0].Value<string>("group_id");
                user_id.Text = "用戶id:" + msg["result"]["user_list"][0].Value<string>("user_id");
                score.Text = "匹配度:" + msg["result"]["user_list"][0].Value<string>("score");
                if (Convert.ToDecimal(msg["result"]["user_list"][0].Value<string>("score")) > 80)
                {
                    MessageBox.Show("與用戶"+ msg["result"]["user_list"][0].Value<string>("user_id") + ",相似度:" + Convert.ToDouble(msg["result"]["user_list"][0].Value<string>("score")) + "匹配成功");
                }
                else
                {
                    MessageBox.Show("匹配人臉庫的照片的最大相似度:" + Convert.ToDouble(msg["result"]["user_list"][0].Value<string>("score")) + "匹配失敗");
                }
            }
            else
            {
                MessageBox.Show("找不到匹配的用戶!");
            }
        }
    }
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM