C#winforms实现windows窗体人脸识别(人脸登录、人脸认证)

举报
穆雄雄 发表于 2022/12/17 11:00:29 2022/12/17
【摘要】 六、人脸认证1.新建一个窗体,名称为faceIdentify,其运行结果是:这些控件的名称我也不多说,基本都能知道,下面我们来介绍一下代码:2.窗体加载刷新摄像头列表: //窗体加载 private void faceIdentify_Load(object sender, EventArgs e) { //显示为正在检测 ...

六、人脸认证

1.新建一个窗体,名称为faceIdentify,其运行结果是:
人脸认证
人脸认证
人脸认证
这些控件的名称我也不多说,基本都能知道,下面我们来介绍一下代码:
2.窗体加载刷新摄像头列表:

 //窗体加载
        private void faceIdentify_Load(object sender, EventArgs e)
        {
           //显示为正在检测
            this.label1.Text = this.label2.Text = this.label6.Text = this.label9.Text = "正在识别";
          
            // 刷新可用相机的列表
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            comboBoxCameras.Items.Clear();

            for (int i = 0; i < videoDevices.Count; i++)
            {
                comboBoxCameras.Items.Add(videoDevices[i].Name.ToString());
            }


            if (comboBoxCameras.Items.Count > 0)
                comboBoxCameras.SelectedIndex = 0;
            picsize.SelectedIndex = 0;

            //打开摄像头
            openCamera();
        }

3.打开摄像头:

//打开摄像头
        public void openCamera()
        {
            selectedPICIndex = picsize.SelectedIndex;

            selectedDeviceIndex = comboBoxCameras.SelectedIndex;
            //连接摄像头。
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            // 枚举所有摄像头支持的像素,设置拍照为1920*1080
            foreach (VideoCapabilities capab in videoSource.VideoCapabilities)
            {
                if (selectedPICIndex == 0)
                {
                    if (capab.FrameSize.Width == 1920 && capab.FrameSize.Height == 1080)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
                else
                {
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
            }
            videoSourcePlayer1.VideoSource = videoSource;

            // set NewFrame event handler
            videoSourcePlayer1.Start();
        }

4.签到的按钮:

/// <summary>
        /// 签到的按钮
        /// 先保存图片,然后进行比较,获取的id,查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void qiandao_Click(object sender, EventArgs e)
        {
            Users users = FaceIdentifys(SavePicture());
            this.label1.Text = users.age.ToString();
            this.label2.Text = users.name;
            this.label6.Text = users.phone;
            this.label9.Text = users.address;
            if (users.picture != null)
            {
                this.pictureBox1.Image = Image.FromFile(users.picture, false);
            }
            
        }

5.人脸识别:

/// <summary>
        /// 人脸识别
        /// </summary>
        /// <param name="filename"></param>
        public static Users FaceIdentifys(string filename)
        {
            long id = 0;
            string ids = "";
            double scores_num = 0;
            Users user = new Users();
            var client = new Baidu.Aip.Face.Face(Api_Key, Secret_Key);
            var image1 = File.ReadAllBytes(filename);
            var result = client.User.Identify(image1, new[] { "gr_test" }, 1, 1);
            //先判断脸是不是在上面,在继续看有匹配的没,否则提示放上脸
            //得到根节点
            JObject jo_result = (JObject)JsonConvert.DeserializeObject(result.ToString());
            if ((string)jo_result["error_msg"] != null)
            {
                MessageBox.Show("对不起,请把脸放上!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                //检测到脸
                //得到result节点
                JArray jo_age = (JArray)JsonConvert.DeserializeObject(jo_result["result"].ToString());
                foreach (var val in jo_age)
                {
                    id = long.Parse(((JObject)val)["uid"].ToString());  //获取uid
                    string scores = ((JObject)val)["scores"].ToString();//获取scores
                    int num1 = scores.IndexOf("\n") + 2;
                    int num2 = scores.LastIndexOf("]")-8;
                    ids = scores.Substring(num1, num2);
                    scores_num =double.Parse(ids);
                }
                if (scores_num > 80)
                {
                    user = QueryUsersById(id);
                    if (user.id != 0)
                    {
                        MessageBox.Show("签到成功,已检测到您的信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("对不起,系统根据您的脸未检测到信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }
                else {
                    MessageBox.Show("对不起,系统根据您的脸未检测到信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

            }
            return user;

        }

6.保存图片:

 /// <summary>
        /// 保存图片
        /// </summary>
        public string SavePicture()
        {
            if (videoSource == null)
            {
                return null;
            }

            Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
            //图片名称,年月日时分秒毫秒.jpg
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";

            //获取项目的根目录
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string picture = path + "\\picture\\" + fileName;
            //将图片保存在服务器里面
            bitmap.Save(picture, ImageFormat.Jpeg);
            bitmap.Dispose();
            return picture;
        }

7.根据编号查询用户信息:

/// <summary>
        /// 根据编号查询用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Users QueryUsersById(long id)
        {

            Users user = new Users();
            string sql = "select * from users where id = @id";
            using (SqlDataReader reader = SqlHelper.ExcuteReader(sql, CommandType.Text, new SqlParameter("@id", id)))
            {
                if (reader.Read())
                {
                    user.id = long.Parse(reader[0].ToString());
                    user.name = reader[1].ToString();
                    user.age = Convert.ToInt32(reader[2]);
                    user.phone = reader[3].ToString();
                    user.password = reader[4].ToString();
                    user.address = reader[5].ToString();
                    user.picture = reader[6].ToString();
                }
            }
            return user;
        }

源码请在这里面看:
人脸认证源码faceIdentify

七、人脸登陆

1.新建一个窗体,参考如下:
人脸登陆
人脸登陆
2.窗体加载刷新摄像头列表:

//窗体加载
        private void faceIdentify_Load(object sender, EventArgs e)
        {
           //显示为正在检测
            this.label1.Text = this.label2.Text = this.label6.Text = this.label9.Text = "正在识别";
          
            // 刷新可用相机的列表
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            comboBoxCameras.Items.Clear();

            for (int i = 0; i < videoDevices.Count; i++)
            {
                comboBoxCameras.Items.Add(videoDevices[i].Name.ToString());
            }


            if (comboBoxCameras.Items.Count > 0)
                comboBoxCameras.SelectedIndex = 0;
            picsize.SelectedIndex = 0;

            //打开摄像头
            openCamera();
        }

3.打开摄像头:

//打开摄像头
        public void openCamera()
        {
            selectedPICIndex = picsize.SelectedIndex;

            selectedDeviceIndex = comboBoxCameras.SelectedIndex;
            //连接摄像头。
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            // 枚举所有摄像头支持的像素,设置拍照为1920*1080
            foreach (VideoCapabilities capab in videoSource.VideoCapabilities)
            {
                if (selectedPICIndex == 0)
                {
                    if (capab.FrameSize.Width == 1920 && capab.FrameSize.Height == 1080)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
                else
                {
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
            }
            videoSourcePlayer1.VideoSource = videoSource;

            // set NewFrame event handler
            videoSourcePlayer1.Start();
        }

4.点击确定的按钮,(人脸登陆):

/// <summary>
        /// 点击确定的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //先获取用户名
            //然后在提取图片
            //先查询用户名,看看有没有该用户名
            //有该用户名的话继续判断人脸对应不,没有的话提示没有该用户
            string name = this.textBox1.Text;
            Users user = QueryUsersByName(name);
            if (((string)(user.name))!="")
            {
                //有该用户,判断摄入的人脸和人脸库中的对比
                FaceVerify(SavePicture(),user);
            }
            else { 
               
                //说明没有该用户,提示用户重新输入用户名
                MessageBox.Show("对不起,检测到没有该用户,请重新输入", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            

        }

5.人脸认证【登陆】:

/// <summary>
        /// 人脸认证【登陆】
        /// </summary>
        public  void FaceVerify(string filename,Users users)
        {
            var client = new Baidu.Aip.Face.Face(Api_Key ,Secret_Key);
            var image1 = File.ReadAllBytes(filename);

            var result = client.User.Verify(image1,(users.id).ToString(), new[] { "gr_test" }, 1);


            //先判断脸是不是在上面,在继续看有匹配的没,否则提示放上脸
            //得到根节点
            JObject jo_result = (JObject)JsonConvert.DeserializeObject(result.ToString());
            if ((string)jo_result["error_msg"] != null)
            {
                MessageBox.Show("对不起,请把脸放上!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                //检测到脸
                //得到result节点
                JArray jo_age = (JArray)JsonConvert.DeserializeObject(jo_result["result"].ToString());
                string resu = jo_age.ToString();
                int num1 = resu.IndexOf("\n") + 2;
                int num2 = resu.LastIndexOf("]") - 8;
                string ids = resu.Substring(num1, num2);
                if (ids != null || !ids.Equals(""))
                {

                    double scores_num = double.Parse(ids);
                    if (scores_num > 80)
                    {
                        MessageBox.Show("登陆成功,已检测到您的信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("对不起,脸与账户不对应,请换张脸试试", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }
            }
        }

6.根据编号查询用户信息:

/// <summary>
        /// 根据编号查询用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Users QueryUsersByName(string name)
        {
            Users user = new Users();
            string sql = "select * from users where name = @name";
            using (SqlDataReader reader = SqlHelper.ExcuteReader(sql, CommandType.Text, new SqlParameter("@name", name)))
            {
                if (reader.Read())
                {
                    user.id = long.Parse(reader[0].ToString());
                    user.name = reader[1].ToString();
                    user.age = Convert.ToInt32(reader[2]);
                    user.phone = reader[3].ToString();
                    user.password = reader[4].ToString();
                    user.address = reader[5].ToString();
                    user.picture = reader[6].ToString();
                }
            }
            return user;
        }

7.保存图片:

  /// <summary>
        /// 保存图片
        /// </summary>
        public string SavePicture()
        {
            if (videoSource == null)
            {
                return null;
            }

            Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
            //图片名称,年月日时分秒毫秒.jpg
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";

            //获取项目的根目录
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string picture = path + "\\picture\\" + fileName;
            //将图片保存在服务器里面
            bitmap.Save(picture, ImageFormat.Jpeg);
            bitmap.Dispose();
            return picture;
        }

源码请在这里看:
人脸登陆facelogin

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。