unity接入实现人脸识别应用-基于虹软人脸识别算法4.0

一、准备工作

1、下载虹软人脸识别增值版SDK 4.0

1)注册并登录开发者中心

2)下载虹软人脸识别SDK

2、安装Unity3D及Visual Studio 2019开发环境

1)安装Unity Hub

2)安装Unity 2020.3.1f1c1

二、创建DEMO工程

1、创建Unity工程

2、引入虹软人脸识别SDK

3、项目工程目录说明

三、运行调试程序

1、虹软人脸识别SDK在线激活

2、可以进行人脸识别

四、核心代码说明

1、关于System.Drawing.dll缺失的问题说明

2、关于Unity中使用选择.NET版本的说明

3、人脸识别核心代码分析

五、DEMO源码下载 ————————————————

一、准备工作

1、下载虹软人脸识别增值版SDK 4.0

1)注册并登录开发者中心

访问https://www.arcsoft.com.cn/登录后创建新应用并添加SDK 在这里插入图片描述

2)下载虹软人脸识别SDK

点击上图中V4.0版本的下载箭头可以下载SDK

2、安装Unity3D及Visual Studio 2019开发环境

1)安装Unity Hub

访问https://unity.cn/并下载安装Unity Hub

2)安装Unity 2020.3.1f1c1

Unity Hub安装完成后打开,依据下图内容安装Unity 2020.3.1f1c1,注意:勾选Visual Studio可以下载VS开发环境! 在这里插入图片描述

二、创建DEMO工程

1、创建Unity工程

Unity Hub-》项目-》新建-》创建即可完成unity工程的创建 在这里插入图片描述

2、引入虹软人脸识别SDK

下载完成虹软人脸识别SDK后解压-》lib-》X64即可看到libarcsoft_face.dll和libarcsoft_face_engine.dll两个动态库文件 在这里插入图片描述 注意:在unity工程的下图中红色箭头标注,32位和64位的Arcface SDK需要分别勾选x86和x64,libarcsoft_face.dll和libarcsoft_face_engine.dll两个文件都需要此操作! 在这里插入图片描述

3、项目工程目录说明

下图中1、2部分取自官网的VS窗体Demo,3部分取自虹软人脸识别SDK,4部分是在VS窗体Demo的基础上进行修改的类。 在这里插入图片描述

三、运行调试程序

1、虹软人脸识别SDK在线激活

在这里插入图片描述

2、可以进行人脸识别

四、核心代码说明

1、关于System.Drawing.dll缺失的问题说明

注意:如果代码中只引入libarcsoft_face.dll和libarcsoft_face_engine.dll会报错System.Drawing.dll文件丢失

可以在unity的安装目录~\2020.3.1f1c1\Editor\Data\MonoBleedingEdge\lib\mono\4.7.1-api\下找到该文件并复制进入工程内

2、关于Unity中使用选择.NET版本的说明

在unity工程的player设置中选择Scripting Backend位Mono,Api Compatibility Level*为.NET 4.x

在这里插入图片描述

3、人脸识别核心代码分析

1)摄像头初始化 WebCamTexture.devices

    public RawImage rawimage;
    WebCamTexture webCamTexture;
 
    public Text webCamDisplayText;
 
    void Start()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }
 
        GoWebCam01();
 
        InitEngines();
 
        btnStartVideo_Click(new object(), new EventArgs());
    }
 
    //CAMERA 01 SELECT
    public void GoWebCam01()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }
 
        webCamTexture = new WebCamTexture(cam_devices[0].name, 1280, 720, 30);
        rawimage.texture = webCamTexture;
        if (webCamTexture != null)
        {
            //webCamTexture.Play();
            Debug.Log("Web Cam Connected : " + webCamTexture.deviceName + "\n");
        }
        webCamDisplayText.text = "Camera Type: " + cam_devices[0].name.ToString();
    }

2)图片格式转换 Texture2D to Image

    public static Image Texture2Image(Texture2D texture)
    {
        if (texture == null)
        {
            return null;
        }
        //Save the texture to the stream.
        byte[] bytes = texture.EncodeToPNG();
 
        //Memory stream to store the bitmap data.
        MemoryStream ms = new MemoryStream(bytes);
 
        //Seek the beginning of the stream.
        ms.Seek(0, SeekOrigin.Begin);
 
        //Create an image from a stream.
        Image bmp2 = Bitmap.FromStream(ms);
 
        //Close the stream, we nolonger need it.
        ms.Close();
        ms = null;
 
        return bmp2;
    }

3)初始化人脸识别库 注意:此代码片段中appId sdkKey64 sdkKey32 activeKey64 activeKey32的值需要根据虹软开发者中心的实际数值进行填写

    private void InitEngines()
    {
        try
        {
            webCamDisplayText.text += "测试";
 
            //读取配置文件
            //AppSettingsReader reader = new AppSettingsReader();
            //rgbCameraIndex = (int)reader.GetValue("RGB_CAMERA_INDEX", typeof(int));
            //irCameraIndex = (int)reader.GetValue("IR_CAMERA_INDEX", typeof(int));
            //frMatchTime = (int)reader.GetValue("FR_MATCH_TIME", typeof(int));
            //liveMatchTime = (int)reader.GetValue("LIVENESS_MATCH_TIME", typeof(int));
 
            AppSettingsReader reader = new AppSettingsReader();
            rgbCameraIndex = 0;
            irCameraIndex = 1;
            frMatchTime = 20;
            liveMatchTime = 20;
 
            int retCode = 0;
            bool isOnlineActive = true;//true(在线激活) or false(离线激活)
            try
            {
                if (isOnlineActive)
                {
                    #region 读取在线激活配置信息
                    //string appId = (string)reader.GetValue("APPID", typeof(string));
                    //string sdkKey64 = (string)reader.GetValue("SDKKEY64", typeof(string));
                    //string sdkKey32 = (string)reader.GetValue("SDKKEY32", typeof(string));
                    //string activeKey64 = (string)reader.GetValue("ACTIVEKEY64", typeof(string));
                    //string activeKey32 = (string)reader.GetValue("ACTIVEKEY32", typeof(string));
 
                    string appId = "";
                    string sdkKey64 = "";
                    string sdkKey32 = "";
                    string activeKey64 = "";
                    string activeKey32 = "";
 
                    webCamDisplayText.text += "111111";
 
                    //判断CPU位数
                    var is64CPU = Environment.Is64BitProcess;
                    if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(is64CPU ? sdkKey64 : sdkKey32) || string.IsNullOrWhiteSpace(is64CPU ? activeKey64 : activeKey32))
                    {
                        Debug.LogError(string.Format("请在App.config配置文件中先配置APP_ID和SDKKEY{0}、ACTIVEKEY{0}!", is64CPU ? "64" : "32"));
                        //MessageBox.Show(string.Format("请在App.config配置文件中先配置APP_ID和SDKKEY{0}、ACTIVEKEY{0}!", is64CPU ? "64" : "32"));
 
                        //System.Environment.Exit(0);
                        Quit();
                    }
                    #endregion
 
                    webCamDisplayText.text += "准备激活";
 
                    //在线激活引擎    如出现错误,1.请先确认从官网下载的sdk库已放到对应的bin中,2.当前选择的CPU为x86或者x64
                    retCode = imageEngine.ASFOnlineActivation(appId, is64CPU ? sdkKey64 : sdkKey32, is64CPU ? activeKey64 : activeKey32);
 
                    webCamDisplayText.text += "激活完成";
                }
                else
                {
                    #region 读取离线激活配置信息
                    string offlineActiveFilePath = (string)reader.GetValue("OfflineActiveFilePath", typeof(string));
                    if (string.IsNullOrWhiteSpace(offlineActiveFilePath) || !File.Exists(offlineActiveFilePath))
                    {
                        string deviceInfo;
                        retCode = imageEngine.ASFGetActiveDeviceInfo(out deviceInfo);
                        if (retCode != 0)
                        {
                            Debug.LogError("获取设备信息失败,错误码:" + retCode);
                            //MessageBox.Show("获取设备信息失败,错误码:" + retCode);
                        }
                        else
                        {
                            File.WriteAllText("ActiveDeviceInfo.txt", deviceInfo);
                            Debug.LogError("获取设备信息成功,已保存到运行根目录ActiveDeviceInfo.txt文件,请在官网执行离线激活操作,将生成的离线授权文件路径在App.config里配置后再重新运行");
                            //MessageBox.Show("获取设备信息成功,已保存到运行根目录ActiveDeviceInfo.txt文件,请在官网执行离线激活操作,将生成的离线授权文件路径在App.config里配置后再重新运行");
                        }
                        //System.Environment.Exit(0);
                        Quit();
                    }
                    #endregion
                    //离线激活
                    retCode = imageEngine.ASFOfflineActivation(offlineActiveFilePath);
                }
                if (retCode != 0 && retCode != 90114)
                {
                    Debug.LogError("激活SDK失败,错误码:" + retCode);
                    //MessageBox.Show("激活SDK失败,错误码:" + retCode);
                    //System.Environment.Exit(0);
                    Quit();
                }
 
                webCamDisplayText.text += retCode.ToString();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("无法加载 DLL"))
                {
                    Debug.LogError("请将SDK相关DLL放入bin对应的x86或x64下的文件夹中!");
                    //MessageBox.Show("请将SDK相关DLL放入bin对应的x86或x64下的文件夹中!");
                }
                else
                {
                    Debug.LogError("激活SDK失败,请先检查依赖环境及SDK的平台、版本是否正确!");
                    //MessageBox.Show("激活SDK失败,请先检查依赖环境及SDK的平台、版本是否正确!");
                }
                //System.Environment.Exit(0);
                Quit();
            }
 
            //初始化引擎
            DetectionMode detectMode = DetectionMode.ASF_DETECT_MODE_IMAGE;
            //Video模式下检测脸部的角度优先值
            ASF_OrientPriority videoDetectFaceOrientPriority = ASF_OrientPriority.ASF_OP_ALL_OUT;
            //Image模式下检测脸部的角度优先值
            ASF_OrientPriority imageDetectFaceOrientPriority = ASF_OrientPriority.ASF_OP_ALL_OUT;
            //最大需要检测的人脸个数
            int detectFaceMaxNum = 6;
            //引擎初始化时需要初始化的检测功能组合
            int combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_AGE | FaceEngineMask.ASF_GENDER | FaceEngineMask.ASF_FACE3DANGLE | FaceEngineMask.ASF_IMAGEQUALITY | FaceEngineMask.ASF_MASKDETECT;
            //初始化引擎,正常值为0,其他返回值请参考http://ai.arcsoft.com.cn/bbs/forum.php?mod=viewthread&tid=19&_dsign=dbad527e
            retCode = imageEngine.ASFInitEngine(detectMode, imageDetectFaceOrientPriority, detectFaceMaxNum, combinedMask);
            Console.WriteLine("InitEngine Result:" + retCode);
            AppendText((retCode == 0) ? "图片引擎初始化成功!" : string.Format("图片引擎初始化失败!错误码为:{0}", retCode));
            if (retCode != 0)
            {
                //禁用相关功能按钮
                //ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn);
            }
 
            //初始化视频模式下人脸检测引擎
            DetectionMode detectModeVideo = DetectionMode.ASF_DETECT_MODE_VIDEO;
            int combinedMaskVideo = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_FACELANDMARK;
            retCode = videoEngine.ASFInitEngine(detectModeVideo, videoDetectFaceOrientPriority, detectFaceMaxNum, combinedMaskVideo);
            AppendText((retCode == 0) ? "视频引擎初始化成功!" : string.Format("视频引擎初始化失败!错误码为:{0}", retCode));
            if (retCode != 0)
            {
                //禁用相关功能按钮
                //ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn);
            }
 
            //RGB视频专用FR引擎
            combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_LIVENESS | FaceEngineMask.ASF_MASKDETECT;
            retCode = videoRGBImageEngine.ASFInitEngine(detectMode, videoDetectFaceOrientPriority, detectFaceMaxNum, combinedMask);
            AppendText((retCode == 0) ? "RGB处理引擎初始化成功!" : string.Format("RGB处理引擎初始化失败!错误码为:{0}", retCode));
            if (retCode != 0)
            {
                //禁用相关功能按钮
                //ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn);
            }
            //设置活体阈值
            videoRGBImageEngine.ASFSetLivenessParam(thresholdRgb);
 
            //IR视频专用FR引擎
            combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_IR_LIVENESS;
            retCode = videoIRImageEngine.ASFInitEngine(detectModeVideo, videoDetectFaceOrientPriority, detectFaceMaxNum, combinedMask);
            AppendText((retCode == 0) ? "IR处理引擎初始化成功!\r\n" : string.Format("IR处理引擎初始化失败!错误码为:{0}\r\n", retCode));
            if (retCode != 0)
            {
                //禁用相关功能按钮
                //ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn);
            }
            //设置活体阈值
            videoIRImageEngine.ASFSetLivenessParam(thresholdRgb, thresholdIr);
 
            initVideo();
        }
        catch (Exception ex)
        {
            LogUtil.LogInfo(GetType(), ex);
            Debug.LogError("程序初始化异常,请在App.config中修改日志配置,根据日志查找原因!");
            //MessageBox.Show("程序初始化异常,请在App.config中修改日志配置,根据日志查找原因!");
 
            Quit();
            //System.Environment.Exit(0);
        }
    }

五、DEMO源码下载 链接:https://pan.baidu.com/s/1FXs94jbAEseoERpVDzysFA 提取码:iabc 复制这段内容后打开百度网盘手机App,操作更方便哦

注意:DEMO工程只是实现了摄像头初始化、采集图片格式转换、虹软人脸在线注册和人脸特征值实时提取等功能,在使用图片进行人脸注册功能时会报错,未解决!

提供思路:可以将人脸注册的功能单独提取并将特征值存入数据库,然后从unity中读取特征值进行人脸数据的比对。

了解更多人脸识别产品相关内容请到虹软视觉开放平台

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章