百度ai人脸识别项目C#

news2025/2/8 18:07:08

一、项目描述

本项目通过集成百度AI人脸识别API,实现了人脸检测和识别功能。用户可以上传图片,系统将自动识别人脸并返回识别结果。

二、开发环境

  • Visual Studio 2019或更高版本
  • .NET Framework 4.7.2或更高版本
  • AForge.NET库
  • 百度AI平台人脸识别API

三、具体实现

1.界面设计

1.1所用的库

  1. AForge.Controls
    • VideoSourcePlayer
  2. AForge.Video
    • VideoCaptureDevice
  3. AForge.Video.DirectShow
    • FilterInfoCollection
    • FilterInfo
  4. Baidu.Aip.Face
    • Face
  5. BaiduAI.Common
    • ClassLoger
    • JsonHelper
  6. Newtonsoft.Json.Linq
    • JArray
    • JObject
  7. System
    • 各种基本的系统功能和类型(如 Exception, EventArgs, 等等)
  8. System.Collections.Generic
    • Dictionary
  9. System.ComponentModel
    • BackgroundWorker 和其他组件模型支持
  10. System.Data
    • 数据处理
  11. System.Drawing
    • Image, Bitmap, Graphics, Pen, Point
  12. System.Drawing.Imaging
    • ImageFormat
  13. System.IO
    • 文件操作,如 File, FileStream, MemoryStream, Path, 等等
  14. System.Linq
    • LINQ 查询
  15. System.Security.Policy
    • 安全策略
  16. System.Text
    • StringBuilder
  17. System.Threading
    • Thread, ThreadPool, WaitCallback
  18. System.Windows.Forms
    • 各种 WinForms 控件(如 Form, Button, TextBox, OpenFileDialog, MessageBox, ComboBox, 等等)
  19. System.Windows.Interop
    • Imaging
  20. System.Windows.Media.Imaging
    • BitmapSource, BitmapFrame, BitmapSizeOptions, JpegBitmapEncoder, PngBitmapEncoder

1.2所用到的控件

  1. Form1
    • WinForms 窗体类
  2. Button
    • button1, button2, button3, button4, button5, button6, button7, button8, button9
  3. TextBox
    • textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7
  4. ComboBox
    • comboBox1
  5. OpenFileDialog
    • 文件打开对话框
  6. MessageBox
    • 信息框
  7. VideoSourcePlayer
    • 来自 AForge.Controls,用于视频显示
  8. WindowsMediaPlayer
    • axWindowsMediaPlayer1,用于播放音频(使用 AxWindowsMediaPlayer 控件)

1.3最终设计界面显示如下:

2.代码实现

2.0初始化

首先要在百度AI官网注册账号然后再人脸识别项目中申请创建应用,就可以获得自己的APP_ID,API_KEY,SECRET_KEY。

using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Baidu.Aip.Face;
using BaiduAI.Common;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BaiduAI
{
    public partial class Form1 : Form
    {
        
        private readonly string APP_ID = "8xxx0583";
        private readonly string API_KEY = "Chxxxx3evL5rPW3skOL";
        private readonly string SECRET_KEY = "VT2FxxxxqEH1ZYcJSw";
        private Face client = null;
        private bool IsStart = false;
        private FaceLocation location = null;
        private FilterInfoCollection videoDevices = null;
        private VideoCaptureDevice videoSource;

        public Form1()
        {
            InitializeComponent();
            axWindowsMediaPlayer1.uiMode = "Invisible";
            client = new Face(API_KEY, SECRET_KEY);
        }
    }
}

2.1人脸检测

1.下面的自己的图片文件路径替换进去的话,使用应用的时候点击按钮就会先进入这个文件夹里面找图片,如果不更改的话,系统找不到文件路径,可能会按默认的进去。

2.设置参数这里,可以去官网的人脸识别技术文档里面查看具体有哪些token可以设置,也有一些参数有默认值。

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.InitialDirectory = "C:\\";//自己的图片文件路径
    dialog.Filter = "所有文件|*.*";
    dialog.RestoreDirectory = true;
    dialog.FilterIndex = 1;

    if (dialog.ShowDialog() == DialogResult.OK)
    {
        string filename = dialog.FileName;
        try
        {
            Image im = Image.FromFile(filename);
            var image = ConvertImageToBase64(im);
            string imageType = "BASE64";

            var options = new Dictionary<string, object>{
                {"max_face_num", 2},
                {"face_field", "age,beauty"},
                {"face_fields", "age,qualities,beauty"}
            };

            var result = client.Detect(image, imageType, options);
            textBox1.Text = result.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

public string ConvertImageToBase64(Image file)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        file.Save(memoryStream, file.RawFormat);
        byte[] imageBytes = memoryStream.ToArray();
        return Convert.ToBase64String(imageBytes);
    }
}

2.2人脸对比

通过选择两张图片,调用百度AI的人脸比对接口,比较两张图片中的人脸。

private void button2_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))
    {
        MessageBox.Show("请选择要对比的人脸图片");
        return;
    }
    try
    {
        string path1 = textBox2.Text;
        string path2 = textBox3.Text;

        var faces = new JArray
        {
            new JObject
            {
                {"image", ReadImg(path1)},
                {"image_type", "BASE64"},
                {"face_type", "LIVE"},
                {"quality_control", "LOW"},
                {"liveness_control", "NONE"},
            },
            new JObject
            {
                {"image", ReadImg(path2)},
                {"image_type", "BASE64"},
                {"face_type", "LIVE"},
                {"quality_control", "LOW"},
                {"liveness_control", "NONE"},
            }
         };

        var result = client.Match(faces);
        textBox1.Text = result.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public string ReadImg(string img)
{
    return Convert.ToBase64String(File.ReadAllBytes(img));
}

2.3获取系统摄像头

通过AForge库获取摄像头设备,并显示实时视频。

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;
    }

    videoSourcePlayer1.NewFrame += VideoSourcePlayer1_NewFrame;
    ThreadPool.QueueUserWorkItem(new WaitCallback(p =>
    {
        while (true)
        {
            IsStart = true;
            Thread.Sleep(500);
        }
    }));
}

private void VideoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
    if (IsStart)
    {
        IsStart = false;
        ThreadPool.QueueUserWorkItem(new WaitCallback(this.Detect), image.Clone());
    }
    if (location != null)
    {
        try
        {
            Graphics g = Graphics.FromImage(image);
            g.DrawLine(new Pen(Color.Black), new Point(location.left, location.top), new Point(location.left + location.width, location.top));
            g.DrawLine(new Pen(Color.Black), new Point(location.left, location.top), new Point(location.left, location.top + location.height));
            g.DrawLine(new Pen(Color.Black), new Point(location.left, location.top + location.height), new Point(location.left + location.width, location.top + location.height));
            g.DrawLine(new Pen(Color.Black), new Point(location.left + location.width, location.top), new Point(location.left + location.width, location.top + location.height));
            g.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show("绘制方框出错:" + ex.Message);
        }
    }
}

2.4摄像头拍照

实现拍照功能,并保存图像到本地。

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);
            }
            //拍照完成后刷新界面,不关闭窗体
            if (videoSourcePlayer1 != null && videoSourcePlayer1.IsRunning)
            {
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
            }

            MessageBox.Show("拍照成功,请进行人脸注册!");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("摄像头异常:" + ex.Message);
    }
}

三、结果

人脸检测:

人脸对比:

四、结语

通过以上步骤,我们成功实现了一个使用百度AI进行人脸识别的项目。该项目包括人脸检测、人脸比对、摄像头拍照、人脸注册和人脸登录等功能,展示了如何结合百度AI平台和AForge库实现实用的人脸识别应用。希望本博客能对你有所帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1850680.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

09--keepalived高可用集群

前言&#xff1a;高可用集群配置是大型网站的一个基础&#xff0c;网站可用性的基础保障之一&#xff0c;这里将对应的概念知识和实操步骤进行整理与收集。 1、基础概念详解 1.1、高可用集群 高可用集群&#xff08;High Availability Cluster&#xff0c;简称HA Cluster&am…

已解决java.security.acl.AclNotFoundException异常的正确解决方法,亲测有效!!!

已解决java.security.acl.AclNotFoundException异常的正确解决方法&#xff0c;亲测有效&#xff01;&#xff01;&#xff01; 目录 问题分析 出现问题的场景 报错原因 解决思路 解决方法 分析错误日志 检查ACL文件路径和名称 确认系统权限 修改代码逻辑 确保ACL文…

什么是微分和导数?

文章目录 设立问题微分特性指数特性线性特性常数特性 多项式微分导数 在机器学习领域&#xff0c;有多种解决最优化问题的方法&#xff0c;其中之一就是使用微分。 通过微分&#xff0c;可以得知函数在某个点的斜率&#xff0c;也可以了解函数在瞬间的变化。 设立问题 请想象一…

C++/Qt 小知识记录7

工作中遇到的一些小问题&#xff0c;总结的小知识记录&#xff1a;C/Qt 小知识7 编译FFMPEG遇到的问题CMakeLists.txt配置FFMPEG的依赖方式&#xff1a; x264在Windows下编译生成*.libVS编译Qt工程时&#xff0c;遇到提示Change Qt Version的情况在QtOsg的窗口上嵌入子窗口&…

Map集合之HashMap细说

最近在看面试题&#xff0c;看到了hashmap相关的知识&#xff0c;面试中问的也挺多的&#xff0c;然后我这里记录下来&#xff0c;供大家学习。 Hashmap为什么线程不安全 jdk 1.7中&#xff0c;在扩容的时候因为使用头插法导致链表需要倒转&#xff0c;从而可能出现循环链表问…

图像分割(四)---(图像显示、灰度直方图和三维灰度图综合分析选取最佳分割方法)

一、引言 对彩色图像进行分割的一种常用方法&#xff0c;是先把彩色图像转灰度图像&#xff0c;然后再选择合适的阈值进行二值分割。但有时彩色图像转灰度图像后不具有典型的双峰特性&#xff0c;二值分割效果不好。本文章提出一种确定彩色图像分割方法的新思路。首先读入一幅彩…

2024山东大学软件学院创新项目实训(9)使用OpenCompass进行模型评估

下载好OpenCompassData-core-20231110.zip 之后&#xff0c;解压压缩包 unzip OpenCompassData-core-20231110.zip 运行代码&#xff1a; python run.py --datasets ceval_gen --hf-path /hy-tmp/7B21/merged --tokenizer-path /hy-tmp/7B21/merged --tokenizer-kwargs p…

【数据结构】线性表之《栈》超详细实现

栈 一.栈的概念及结构二.顺序栈与链栈1.顺序栈2.链栈1.单链表栈2.双链表栈 三.顺序栈的实现1.栈的初始化2.检查栈的容量3.入栈4.出栈5.获取栈顶元素6.栈的大小7.栈的判空8.栈的清空9.栈的销毁 四.模块化源代码1.Stack.h2.Stack.c3.test.c 一.栈的概念及结构 栈&#xff1a;一种…

WDG开门狗

WDG开门狗简介 独立看门狗&#xff0c;它的特点就是独立运行&#xff0c;对时间精度要求较低。独立运行就是独立看门狗的时钟是专用的&#xff0c;LSI内部低速时钟&#xff0c;即使主时钟出现问题了&#xff0c;看门狗也能正常工作&#xff0c;这也是独立看门狗独立的得名原因&…

【34W字CISSP备考笔记】域1:安全与风险管理

1.1 理解、坚持和弘扬职业道德 1.1.1.(ISC)职业道德规范 1、行为得体、诚实、公正、负责、守法。 2、为委托人提供尽职、合格的服务。 3、促进和保护职业。 4、保护社会、公益、必需的公信和自信&#xff0c;保护基础设施。 1.1.2.组织道德规范 1、RFC 1087 &#xff0…

本科生大厂算法岗实习经验复盘:从投递到面试的底层思维!

目录 投递渠道boss直聘官网邮箱内推 面试准备leetcode八股深挖项目自我介绍mock面试技巧答不出来怎么办coding反问 复盘技术交流群用通俗易懂方式讲解系列 节前&#xff0c;我们星球组织了一场算法岗技术&面试讨论会&#xff0c;邀请了一些互联网大厂朋友、参加社招和校招面…

实战电商大数据项目搭建||电商大数据采集||电商API接口

我会提供给你大概1亿条真实的互联网用户上网数据&#xff0c;至于来源&#xff0c;我先不告诉你&#xff0c;绝对是你在网络上无法找到的宝贵数据源。 此外&#xff0c;还会给你提供一个基于当前数据特点而设计的大数据处理方案。 当然&#xff0c;为了防止用户的隐私部分被泄露…

【已解决】SpringBoot图片更新需重启服务器才能显示

问题描述 1、更新头像&#xff0c;并跳转回列表页&#xff0c;发现显示不出来 2、但是前端获取用户头像的信息是在加载页面就会被调用的&#xff0c;同时前端也不存在所谓的缓存问题&#xff0c;因为没有动这部分代码。 但查看响应是能获得正确的信息&#xff08;前端打印图片…

GitHub Copilot 登录账号激活,已经在IntellJ IDEA使用

GitHub Copilot 想必大家都是熟悉的&#xff0c;一款AI代码辅助神器&#xff0c;相信对编程界的诸位并不陌生。 今日特此分享一项便捷的工具&#xff0c;助您轻松激活GitHub Copilot&#xff0c;尽享智能编码之便利&#xff01; GitHub Copilot 是由 GitHub 和 OpenAI 共同开…

2024年安全员-A证证考试题库及安全员-A证试题解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2024年安全员-A证证考试题库及安全员-A证试题解析是安全生产模拟考试一点通结合&#xff08;安监局&#xff09;特种作业人员操作证考试大纲和&#xff08;质检局&#xff09;特种设备作业人员上岗证考试大纲随机出的…

合并有序链表

合并有序链表 图解代码如下 图解 虽然很复杂&#xff0c;但能够很好的理解怎么使用链表&#xff0c;以及对链表的指针类理解 代码如下 Node* merge_list_two_pointer(List& list1, List& list2) {Node* new_head1 list1.head;Node* new_head2 list2.head;Node* s…

FFmpeg编译4(1)

ffmpeg.cffmpeg.h 修改ffmpeg文件 修改刚刚拷贝的ffmpeg.c文件&#xff0c;找到int main(int argc, char **argv)函数&#xff0c;将其替换为int run(int argc, char **argv)在修改后的run(int argc, char **argv) 末尾&#xff08;retrun 之前&#xff09;加上如上如下代码&…

跟TED演讲学英文:How language shapes the way we think by Lera Boroditsky

How language shapes the way we think Link: https://www.ted.com/talks/lera_boroditsky_how_language_shapes_the_way_we_think? Speaker: Lera Boroditsky Date: November 2017 文章目录 How language shapes the way we thinkIntroductionVocabularySummaryTranscriptA…

【完全复现】基于改进粒子群算法的微电网多目标优化调度(含matlab代码)

目录 主要内容 部分代码 结果一览 下载链接 主要内容 程序完全复现文献模型《基于改进粒子群算法的微电网多目标优化调度》&#xff0c;以微电网系统运行成本和环境保护成本为目标函数&#xff0c;建立了并网方式下的微网多目标优化调度模型&#xff0c;通过改进…

数组和链表的区别是什么?

引言&#xff1a;本文旨在深入探讨数组和链表之间的区别&#xff0c;分析它们在不同情境下的优缺点&#xff0c;并探讨如何根据应用需求选择合适的数据结构。通过深入理解数组和链表的内部工作原理和应用场景&#xff0c;读者将能够更好地应用这些知识解决实际问题&#xff0c;…