C# USB視頻人臉檢測

此程序基於 虹軟人臉識別進行的開發 SDK下載地址:https://ai.arcsoft.com.cn/ucenter/user/reg?utm_source=csdn1&utm_medium=referralweb

前提條件 從虹軟官網下載獲取ArcFace引擎應用開發包,及其對應的激活碼(App_id, SDK_key)數組

將獲取到的開發包導入到您的應用中數據結構

App_id與SDK_key是在初始化的時候須要使用 基本類型app

全部基本類型在平臺庫中有定義。 定義規則是在ANSIC 中的基本類型ide

前加上字母「M」同時將類型的第一個字母改爲大寫。例如「long」 被定義成「MLong 」數據結構與枚舉ui

AFR_FSDK_FACEINPUT 描述: 臉部信息 定義this

typedef struct{
MRECT		rcFace;
AFR_FSDK_OrientCode  lOrient;
} AFR_FSDK_FACEINPUT, *LPAFR_FSDK_FACEINPUT;

成員描述spa

rcFace臉部矩形框信息
lOrient臉部旋轉角度

AFR_FSDK_FACEMODEL 描述: 臉部特徵信息.net

定義
typedef struct{
MByte		*pbFeature;
MInt32		lFeatureSize;
} AFR_FSDK_FACEMODEL, *LPAFR_FSDK_FACEMODEL;

成員描述線程

pbFeature提取到的臉部特徵

lFeatureSize特徵信息長度

AFR_FSDK_VERSION

描述: 引擎版本信息

定義
typedef struct{
MInt32			lCodebase;
MInt32			lMajor;
MInt32			lMinor;
MInt32			lBuild;
MInt32 		lFeatureLevel;
MPChar			Version;
MPChar			BuildDate;
MPChar  		CopyRight;
} AFR_FSDK_VERSION, *LPAFR_FSDK_VERSION;
成員描述
lCodebase代碼庫版本號
lMajor主版本號
lMinor次版本號
lBuild編譯版本號,遞增
lFeatureLevel特徵庫版本號
Version字符串形式的版本號
BuildDate編譯時間
CopyRight版權

枚舉 AFR_FSDK_ORIENTCODE 描述: 基於逆時針的臉部方向枚舉值

定義
enum AFR_FSDK_ORIENTCODE{
AFR_FSDK_FOC_0		= 0x1,
AFR_FSDK_FOC_90		= 0x2,
AFR_FSDK_FOC_270		= 0x3,
AFR_FSDK_FOC_180 = 0x4,
AFR_FSDK_FOC_30		= 0x5,
AFR_FSDK_FOC_60		= 0x6,
AFR_FSDK_FOC_120		= 0x7,
AFR_FSDK_FOC_150		= 0x8,
AFR_FSDK_FOC_210		= 0x9,
AFR_FSDK_FOC_240		= 0xa,
AFR_FSDK_FOC_300		= 0xb,
AFR_FSDK_FOC_330		= 0xc
};
成員描述
AFR_FSDK_FOC_00 度
AFR_FSDK_FOC_9090度
AFR_FSDK_FOC_270270度
AFR_FSDK_FOC_180180度
AFR_FSDK_FOC_3030度
AFR_FSDK_FOC_6060度
AFR_FSDK_FOC_120120度
AFR_FSDK_FOC_150150度
AFR_FSDK_FOC_210210度
AFR_FSDK_FOC_240240度
AFR_FSDK_FOC_300300度
AFR_FSDK_FOC_330330度

支持的顏色格式 描述: 顏色格式及其對齊規則 定義 ASVL_PAF_I420 8-bit Y層,以後是8-bit的2x2 採樣的U層和V層 ASVL_PAF_YUYV Y0, U0, Y1, V0 ASVL_PAF_RGB24_B8G8R8 BGR24, B8G8R8

API ReferenceAFR_FSDK_InitialEngine 描述: 初始化引擎參數

原型
MRESULT AFR_FSDK_InitialEngine(
MPChar		AppId,
MPChar		SDKKey,
Mbyte		*pMem,
MInt32		lMemSize,
MHandle	        *phEngine
);

參數

AppId[in] 用戶申請SDK時獲取的App Id
SDKKey[in] 用戶申請SDK時獲取的SDK Key
pMem[in] 分配給引擎使用的內存地址
lMemSize[in] 分配給引擎使用的內存大小
phEngine[out] 引擎handle

返回值: 成功返回MOK,不然返回失敗code。失敗codes以下所列: MERR_INVALID_PARAM 參數輸入非法 MERR_NO_MEMORY 內存不足 AFR_FSDK_ExtractFRFeature 描述: 獲取臉部特徵參數

原型
MRESULT AFR_FSDK_ExtractFRFeature (
    MHandle			hEngine,
    LPASVLOFFSCREEN		pInputImage,
    LPAFR_FSDK_FACEINPUT	pFaceRes,
    LPAFR_FSDK_FACEMODEL	pFaceModels
);

參數

hEngine[in] 引擎handle
pInputImage[in] 輸入的圖像數據
pFaceRes[in] 已檢測到的臉部信息
pFaceModels[out] 提取的臉部特徵信息

返回值: 成功返回MOK,不然返回失敗code。失敗codes以下所列: MERR_INVALID_PARAM 參數輸入非法 MERR_NO_MEMORY 內存不足 AFR_FSDK_FacePairMatching 描述: 臉部特徵比較

原型

MRESULT AFR_FSDK_FacePairMatching(
	MHandle			hEngine,
	AFR_FSDK_FACEMODEL		*reffeature,
	AFR_FSDK_FACEMODEL		*probefeature,
	MFloat     			*pfSimilScore
);

參數

hEngine[in] 引擎handle
reffeature[in] 已有臉部特徵信息
probefeature[in] 被比較的臉部特徵信息
pfSimilScore[out] 臉部特徵類似程度數值

返回值: 成功返回MOK,不然返回失敗code。失敗codes以下所列: MERR_INVALID_PARAM 參數輸入非法 MERR_NO_MEMORY 內存不足 AFR_FSDK_UninitialEngine 描述: 銷燬引擎,釋放相應資源

原型
MRESULT AFR_FSDK_UninitialEngine(
	MHandle          hEngine
);

參數 hEngine[in] 引擎handle 返回值: 成功返回MOK,不然返回失敗code。失敗codes以下所列: MERR_INVALID_PARAM 參數輸入非法 AFR_FSDK_GetVersion

原型
const AFR_FSDK_VERSION *  AFR_FSDK_GetVersion(
     MHandle          hEngine
     );

相關事例代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ArcsoftFace
{


    public struct AFD_FSDK_FACERES
    {
        public int nFace;                     // number of faces detected


        public IntPtr rcFace;                        // The bounding box of face


        public IntPtr lfaceOrient;                   // the angle of each face
    }


}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ArcsoftFace
{
    public struct AFR_FSDK_FACEINPUT
    {
        public MRECT rcFace;	                   // The bounding box of face


        public int lfaceOrient;                 // The orientation of face
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ArcsoftFace
{
    public struct AFR_FSDK_FACEMODEL
    {
        public IntPtr pbFeature;	// The extracted features


        public int lFeatureSize;	// The size of pbFeature
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ArcsoftFace
{
    public struct AFR_FSDK_Version
    {
        public int lCodebase;
        public int lMajor;
        public int lMinor;
        public int lBuild;
        public int lFeatureLevel;
        public IntPtr Version;
        public IntPtr BuildDate;
        public IntPtr CopyRight;
    }
}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;


namespace ArcsoftFace
{


    public class AmFaceVerify
    {
        /**
        * 初始化人臉檢測引擎
        * @return 初始化人臉檢測引擎
        */
        [DllImport("libarcsoft_fsdk_face_detection.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AFD_FSDK_InitialFaceEngine(string appId, string sdkKey, IntPtr pMem, int lMemSize, ref IntPtr pEngine, int iOrientPriority, int nScale, int nMaxFaceNum);


        /**
        * 獲取人臉檢測 SDK 版本信息
        * @return 獲取人臉檢測SDK 版本信息
        */
        [DllImport("libarcsoft_fsdk_face_detection.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr AFD_FSDK_GetVersion(IntPtr pEngine);


        /**
        * 根據輸入的圖像檢測出人臉位置,通常用於靜態圖像檢測
        * @return 人臉位置
        */
        [DllImport("libarcsoft_fsdk_face_detection.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AFD_FSDK_StillImageFaceDetection(IntPtr pEngine, IntPtr offline, ref IntPtr faceRes);




        /**
        * 初始化人臉識別引擎
        * @return 初始化人臉識別引擎
        */
        [DllImport("libarcsoft_fsdk_face_recognition.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AFR_FSDK_InitialEngine(string appId, string sdkKey, IntPtr pMem, int lMemSize, ref IntPtr pEngine);


        /**
        * 獲取人臉識別SDK 版本信息
        * @return 獲取人臉識別SDK 版本信息
        */
        [DllImport("libarcsoft_fsdk_face_recognition.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr AFR_FSDK_GetVersion(IntPtr pEngine);


        /**
        * 提取人臉特徵
        * @return 提取人臉特徵
        */
        [DllImport("libarcsoft_fsdk_face_recognition.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AFR_FSDK_ExtractFRFeature(IntPtr pEngine, IntPtr offline, IntPtr faceResult, IntPtr localFaceModels);


        /**
        * 獲取類似度
        * @return 獲取類似度
        */
        [DllImport("libarcsoft_fsdk_face_recognition.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int AFR_FSDK_FacePairMatching(IntPtr pEngine, IntPtr faceModels1, IntPtr faceModels2, ref float fSimilScore);


        #region delete
        ///**
        // *  建立人臉檢測引擎
        // *  @param [in] model_path 模型文件夾路徑
        // *  @param [out] engine 建立的人臉檢測引擎
        // *  @return =0 表示成功,<0 表示錯誤碼。
        // */
        //[DllImport("AmFaceDet.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern int AmCreateFaceDetectEngine(string modelPath, ref IntPtr faceDetectEngine);


        ///**
        // *  建立人臉識別引擎
        // *  @param [in] model_path 模型文件夾路徑
        // *  @param [out] engine 建立的人臉識別引擎
        // *  @return =0 表示成功,<0 表示錯誤碼。
        // */
        //[DllImport("AmFaceRec.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern int AmCreateFaceRecogniseEngine(string modelPath, ref IntPtr facRecogniseeEngine);


        ///**
        // *  建立人臉比對別引擎
        // *  @param [in] model_path 模型文件夾路徑
        // *  @param [out] engine 建立的人臉比對引擎
        // *  @return =0 表示成功,<0 表示錯誤碼。
        // */
        //[DllImport("AmFaceCompare.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern int AmCreateFaceCompareEngine(ref IntPtr facCompareEngine);


        ///**
        // *  設置人臉引擎參數
        // *  @param [in] engine 人臉引擎
        // *  @param [in] param 人臉參數
        // */
        //[DllImport("AmFaceDet.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern void AmSetParam(IntPtr faceDetectEngine, [MarshalAs(UnmanagedType.LPArray)] [In] TFaceParams[] setFaceParams);


        ///**
        // * 人臉檢測
        // * @param [in] engine 人臉引擎
        // * @param [in] bgr 圖像數據,BGR格式
        // * @param [in] width 圖像寬度
        // * @param [in] height 圖像高度
        // * @param [in] pitch 圖像數據行字節數
        // * @param [in,out] faces 人臉結構體數組,元素個數應等於指望檢測人臉個數
        // * @param [in] face_count 指望檢測人臉個數
        // * @return >=0 表示實際檢測到的人臉數量,<0 表示錯誤碼。
        // */
        //[DllImport("AmFaceDet.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern int AmDetectFaces(IntPtr faceDetectEngine, [MarshalAs(UnmanagedType.LPArray)] [In] byte[] image, int width, int height, int pitch, [MarshalAs(UnmanagedType.LPArray)] [In][Out] TAmFace[] faces, int face_count);


        ///**
        // * 抽取人臉特徵
        // * @param [in] engine 人臉引擎
        // * @param [in] bgr 圖像數據,BGR格式
        // * @param [in] width 圖像寬度
        // * @param [in] height 圖像高度
        // * @param [in] pitch 圖像數據行字節數
        // * @param [in] face 人臉結構體
        // * @param [out] feature 人臉特徵
        // * @return =0 表示成功,<0 表示錯誤碼。
        // */
        //[DllImport("AmFaceRec.dll", CallingConvention = CallingConvention.Cdecl)]
        ////public static extern int AmExtractFeature(IntPtr faceEngine, [MarshalAs(UnmanagedType.LPArray)] [In] byte[] image, int width, int height, int pitch, [MarshalAs(UnmanagedType.LPArray)] [In] TAmFace[] faces, ref byte[] feature);
        //public static extern int AmExtractFeature(IntPtr facRecogniseeEngine, [MarshalAs(UnmanagedType.LPArray)] [In] byte[] image, int width, int height, int pitch, [MarshalAs(UnmanagedType.LPArray)] [In] TAmFace[] faces, [MarshalAs(UnmanagedType.LPArray)] [Out] byte[] feature);


        ///**
        // * 比對兩我的臉特徵類似度
        // * @param [in] engine 人臉引擎
        // * @param [in] feature1 人臉特徵1
        // * @param [in] feature2 人臉特徵2
        // * @return 人臉類似度
        // */
        //[DllImport("AmFaceCompare.dll", CallingConvention = CallingConvention.Cdecl)]
        //public static extern float AmCompare(IntPtr facCompareEngine, byte[] feature1, byte[] feature2);
        #endregion
    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;


namespace ArcsoftFace
{
    public struct ASVLOFFSCREEN
    {
        public int u32PixelArrayFormat;


        public int i32Width;


        public int i32Height;


        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public IntPtr[] ppu8Plane;


        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public int[] pi32Pitch;
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ArcsoftFace
{
    public struct MRECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Emgu.CV.CvEnum;
using Emgu.CV;//PS:調用的Emgu dll  
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.UI;
using Emgu.CV.OCR;
using System.Threading;
using ArcsoftFace;
using System.Timers;
using Emgu.CV.Util;
using System.Linq;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Text;
using System.Diagnostics;
using System.Drawing.Drawing2D;


namespace ArcsoftFace
{
    public partial class Form2 : Form
    {
       
        private Capture        capture = new Capture(0);
        private bool captureinprocess;//判斷攝像頭的狀態   


        byte[] firstFeature;


        byte[] secondFeature;


        //人臉檢測引擎
        IntPtr detectEngine = IntPtr.Zero;


        //人臉識別引擎
        IntPtr regcognizeEngine = IntPtr.Zero;


        //拖拽線程


        private string haarXmlPath = "haarcascade_frontalface_alt_tree.xml";
        double scale = 1.5;
        // web camera  
        private System.Timers.Timer capture_tick;
        private bool capture_flag = true;


        Image<Gray, Byte> gray = null;
        Image<Bgr, Byte> smallframe = null;
        Mat frame = new Mat();
        private int sb = 0;
        Rectangle f = new Rectangle();
        public Form2()
        {
            InitializeComponent();


            capture_tick = new System.Timers.Timer();
            capture_tick.Interval = 50;
            capture_tick.Enabled = Enabled;
            capture_tick.Stop();
            capture_tick.Elapsed += new ElapsedEventHandler(processfram);
        }


        private byte[] getBGR(Bitmap image, ref int width, ref int height, ref int pitch)
        {
            //Bitmap image = new Bitmap(imgPath);


            const PixelFormat PixelFormat = PixelFormat.Format24bppRgb;


            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat);


            IntPtr ptr = data.Scan0;


            int ptr_len = data.Height * Math.Abs(data.Stride);


            byte[] ptr_bgr = new byte[ptr_len];


            Marshal.Copy(ptr, ptr_bgr, 0, ptr_len);


            width = data.Width;


            height = data.Height;


            pitch = Math.Abs(data.Stride);


            int line = width * 3;


            int bgr_len = line * height;


            byte[] bgr = new byte[bgr_len];


            for (int i = 0; i < height; ++i)
            {
                Array.Copy(ptr_bgr, i * pitch, bgr, i * line, line);
            }


            pitch = line;


            image.UnlockBits(data);


            return bgr;
        }






        private void button1_Click(object sender, EventArgs e)
        {
            if (capture != null)//攝像頭不爲空   
            {


                if (captureinprocess)
                {
                    imageBox1.Enabled = false;
                    //  Application.Idle -= new EventHandler(processfram);
                    capture_tick.Stop();
                    button1.Text = "Stop";
                   
                }
                else
                {
                    //  Application.Idle += new EventHandler(processfram);
                    imageBox1.Enabled = true;
                    capture_tick.Start();
                    button1.Text = "Start";
                }
                captureinprocess = !captureinprocess;
            }
            else//攝像頭爲空則經過Capture()方法調用   
            {
                try
                {
                    capture = new Capture(0);
                }
                catch (NullReferenceException excpt)
                {
                    MessageBox.Show(excpt.Message);
                }
            }


        }




        private void processfram(object sender, EventArgs arg)
        {
            capture_tick.Enabled = false;
            try
            {
                if (frame != null)
                {
                    frame = capture.QueryFrame();
                    Emgu.CV.Image<Bgr, Byte> image = frame.ToImage<Bgr, Byte>();
                    Image<Bgr, Byte> currentFrame = image;






                    if (sb == 0)
                    {
                        sb += 1;
                        MRECT rect = detectAndExtractFeature(image.ToBitmap(), 1);


                        if (Math.Abs(rect.left - f.Left) > 30 || Math.Abs(rect.top - f.Top) > 30)
                        {
                            f = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
                        }




                    }
                    else if (sb >= 4)
                    {
                        sb = 0;
                    }
                    else
                    {
                        sb += 1;
                    }


                    // currentFrame.Draw(rect, new Bgr(Color.Red));
                    // image.Draw(detectAndExtractFeature(image.ToBitmap(),1),new Bgr(Color.Red),3);


                    currentFrame.Draw(f, new Bgr(Color.Red), 3);






                    imageBox1.Image = currentFrame.ToBitmap();
                    PointF pf = new PointF(50, 50);
                    using (Graphics g = imageBox1.CreateGraphics())
                    {
                        Font font = new Font("Arial", 12);
                        g.DrawString("left:" + f.Left + "  top:" + f.Top, font, Brushes.Green, pf);


                    }
                    currentFrame.Dispose();
                    image.Dispose(); ;
                }
                capture_tick.Enabled = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                capture_tick.Enabled = true;
            }
        }


        public static void BoundingBox(Image<Gray, byte> src, Image<Bgr, byte> draw)
        {
            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(src, contours, null, RetrType.External,
                                      ChainApproxMethod.ChainApproxSimple);


                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                    {
                        Rectangle BoundingBox = CvInvoke.BoundingRectangle(contour);
                        CvInvoke.Rectangle(draw, BoundingBox, new MCvScalar(255, 0, 255, 255), 3);
                    }
                }
            }
        }


        public void CaptureProcess(object sender, EventArgs arg)
        {
            Mat frame1 = new Mat();
            frame1 = capture.QueryFrame();




            if (frame1 != null)
            {


                //face detection   


                //frame = frame.Flip(Emgu.CV.CvEnum.FLIP.HORIZONTAL);  
                //  smallframe = frame.Resize(1 / scale, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);//縮放攝像頭拍到的大尺寸照片  
                gray = smallframe.Convert<Gray, Byte>(); //Convert it to Grayscale  
                gray._EqualizeHist();//均衡化  


                CascadeClassifier ccr = new CascadeClassifier(haarXmlPath);
                Rectangle[] rects = ccr.DetectMultiScale(gray, 1.3, 3, new Size(20, 20), Size.Empty);
                foreach (Rectangle r in rects)
                {
                    //This will focus in on the face from the haar results its not perfect but it will remove a majoriy  
                    //of the background noise  
                    Rectangle facesDetected = r;
                    facesDetected.X += (int)(facesDetected.Height * 0.6);
                    facesDetected.Y += (int)(facesDetected.Width * 0.8);
                    facesDetected.Height += (int)(facesDetected.Height * 0.1);
                    facesDetected.Width += (int)(facesDetected.Width * 0.2);


                    //   frame.Draw(facesDetected, new Bgr(Color.Red), 3);//繪製檢測框  
                }




                // imageBox_capture.Image = frame;
            }
        }




        private MRECT detectAndExtractFeature(Image imageParam, int firstSecondFlg)
        {


            byte[] feature = null;
            MRECT rect = new MRECT();
            Bitmap bitmap = new Bitmap(imageParam);
            byte[] imageData = null;
            IntPtr imageDataPtr = IntPtr.Zero;
            ASVLOFFSCREEN offInput = new ASVLOFFSCREEN();
            AFD_FSDK_FACERES faceRes = new AFD_FSDK_FACERES();


            IntPtr faceResPtr = IntPtr.Zero;
            try
            {


                int width = 0;


                int height = 0;


                int pitch = 0;




                imageData = getBGR(bitmap, ref width, ref height, ref pitch);


                //GCHandle hObject = GCHandle.Alloc(imageData, GCHandleType.Pinned);


                //IntPtr imageDataPtr = hObject.AddrOfPinnedObject();


                imageDataPtr = Marshal.AllocHGlobal(imageData.Length);


                Marshal.Copy(imageData, 0, imageDataPtr, imageData.Length);






                offInput.u32PixelArrayFormat = 513;


                offInput.ppu8Plane = new IntPtr[4];


                offInput.ppu8Plane[0] = imageDataPtr;


                offInput.i32Width = width;


                offInput.i32Height = height;


                offInput.pi32Pitch = new int[4];


                offInput.pi32Pitch[0] = pitch;




                IntPtr offInputPtr = Marshal.AllocHGlobal(Marshal.SizeOf(offInput));


                Marshal.StructureToPtr(offInput, offInputPtr, false);


                faceResPtr = Marshal.AllocHGlobal(Marshal.SizeOf(faceRes));


                //Marshal.StructureToPtr(faceRes, faceResPtr, false);






                //人臉檢測
                int detectResult = AmFaceVerify.AFD_FSDK_StillImageFaceDetection(detectEngine, offInputPtr, ref faceResPtr);






                object obj = Marshal.PtrToStructure(faceResPtr, typeof(AFD_FSDK_FACERES));


                faceRes = (AFD_FSDK_FACERES)obj;




                for (int i = 0; i < faceRes.nFace; i++)
                {
                    rect = (MRECT)Marshal.PtrToStructure(faceRes.rcFace + Marshal.SizeOf(typeof(MRECT)) * i, typeof(MRECT));
                    int orient = (int)Marshal.PtrToStructure(faceRes.lfaceOrient + Marshal.SizeOf(typeof(int)) * i, typeof(int));


                    if (i == 0)
                    {
                        Image image = CutFace(bitmap, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);


                        if (firstSecondFlg == 1)
                        {
                            this.pictureBox3.Image = image;
                        }
                        else if (firstSecondFlg == 2)
                        {
                            this.pictureBox4.Image = image;
                        }
                    }


                }




            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog("detect", e.Message + "\n" + e.StackTrace);
            }
            finally
            {
                bitmap.Dispose();


                imageData = null;


                Marshal.FreeHGlobal(imageDataPtr);




                offInput = new ASVLOFFSCREEN();


                faceRes = new AFD_FSDK_FACERES();


            }
            return rect;
        }


        private Image DrawRectangleInPicture(Image bmp, Point p0, Point p1, Color RectColor, int LineWidth, DashStyle ds)
        {


            if (bmp == null) return null;


            Graphics g = Graphics.FromImage(bmp);


            Brush brush = new SolidBrush(RectColor);


            Pen pen = new Pen(brush, LineWidth);


            pen.DashStyle = ds;


            g.DrawRectangle(pen, new Rectangle(p0.X, p0.Y, Math.Abs(p0.X - p1.X), Math.Abs(p0.Y - p1.Y)));


            g.Dispose();


            return bmp;


        }


        public static Bitmap CutFace(Bitmap srcImage, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (srcImage == null)
            {
                return null;
            }


            int w = srcImage.Width;


            int h = srcImage.Height;


            if (StartX >= w || StartY >= h)
            {
                return null;
            }
            if (StartX + iWidth > w)
            {
                iWidth = w - StartX;
            }
            if (StartY + iHeight > h)
            {
                iHeight = h - StartY;
            }
            try
            {
                Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);


                Graphics g = Graphics.FromImage(bmpOut);


                g.DrawImage(srcImage, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);


                g.Dispose();


                return bmpOut;
            }
            catch
            {
                return null;
            }
        }


        private void Form2_Load(object sender, System.EventArgs e)
        {
            #region 初始化人臉檢測引擎


            int detectSize = 40 * 1024 * 1024;


            IntPtr pMem = Marshal.AllocHGlobal(detectSize);


            //1-1
            //string appId = "4tnYSJ68e8wztSo4Cf7WvbyMZduHwpqtThAEM3obMWbE";


            //1-1
            //string sdkKey = "Cgbaq34izc8PA2Px26x8qqWTQn2P5vxijaWKdUrdCwYT";


            //1-n
            string appId = "8b4R2gvcoFQXKbC4wGtnYcqsa9Bd3FLiN3VWDFtJqcnB";


            //1-n
            string sdkKey = "A5Km3QjZKGuakWRmC2pSWTuNzbNbaSCnj5fFtjBBcdxm";


            //人臉檢測引擎初始化


            // IntPtr aaa= AFD_FSDKLibrary.AFD_FSDK_InitialFaceEngine(appId, sdkKey, pMem, detectSize, ref detectEngine, 5, 50, 1);
            int retCode = AmFaceVerify.AFD_FSDK_InitialFaceEngine(appId, sdkKey, pMem, detectSize, ref detectEngine, 5, 50, 1);
            //獲取人臉檢測引擎版本
            IntPtr versionPtr = AmFaceVerify.AFD_FSDK_GetVersion(detectEngine);


            AFR_FSDK_Version version = (AFR_FSDK_Version)Marshal.PtrToStructure(versionPtr, typeof(AFR_FSDK_Version));


            Console.WriteLine("lCodebase:{0} lMajor:{1} lMinor:{2} lBuild:{3} Version:{4} BuildDate:{5} CopyRight:{6}", version.lCodebase, version.lMajor, version.lMinor, version.lBuild, Marshal.PtrToStringAnsi(version.Version), Marshal.PtrToStringAnsi(version.BuildDate), Marshal.PtrToStringAnsi(version.CopyRight));


            //Marshal.FreeHGlobal(versionPtr);


            #endregion


            #region 初始化人臉識別引擎


            int recognizeSize = 40 * 1024 * 1024;


            IntPtr pMemDetect = Marshal.AllocHGlobal(recognizeSize);


            //1-1
            //string appIdDetect = "4tnYSJ68e8wztSo4Cf7WvbyMZduHwpqtThAEM3obMWbE";


            //1-1
            //string sdkKeyDetect = "Cgbaq34izc8PA2Px26x8qqWaaBHbPD7wWMcTU6xe8VRo";


            //1-n
            string appIdDetect = "8b4R2gvcoFQXKbC4wGtnYcqsa9Bd3FLiN3VWDFtJqcnB";


            //1-n
            string sdkKeyDetect = "A5Km3QjZKGuakWRmC2pSWTuW9zdndn5EkVDo4LceRxLU";


            //人臉識別引擎初始化
            retCode = AmFaceVerify.AFR_FSDK_InitialEngine(appIdDetect, sdkKeyDetect, pMemDetect, recognizeSize, ref regcognizeEngine);


            //獲取人臉識別引擎版本
            IntPtr versionPtrDetect = AmFaceVerify.AFR_FSDK_GetVersion(regcognizeEngine);


            AFR_FSDK_Version versionDetect = (AFR_FSDK_Version)Marshal.PtrToStructure(versionPtrDetect, typeof(AFR_FSDK_Version));


            Console.WriteLine("lCodebase:{0} lMajor:{1} lMinor:{2} lBuild:{3} lFeatureLevel:{4} Version:{5} BuildDate:{6} CopyRight:{7}", versionDetect.lCodebase, versionDetect.lMajor, versionDetect.lMinor, versionDetect.lBuild, versionDetect.lFeatureLevel, Marshal.PtrToStringAnsi(versionDetect.Version), Marshal.PtrToStringAnsi(versionDetect.BuildDate), Marshal.PtrToStringAnsi(versionDetect.CopyRight));


            #endregion
        }


  
    }
}


USB視頻   動態畫框   源碼下載地址 
https://download.csdn.net/download/zhang1244/10368237
運行效果地址
https://download.csdn.net/download/zhang1244/10368222
普通人臉照片進行關鍵點提取以及相關對比類似度

https://download.csdn.net/download/zhang1244/10368197

運行效果地址

https://download.csdn.net/download/zhang1244/10368181

相關技術交流,後期可能開發相關與身份證照片進行實名制對比。請繼續關注
相關文章
相關標籤/搜索