人工智能时代,关于人脸检测、识别等功能大家已经屡见不鲜。

本篇用C#来写一下人脸检测功能,简单点说,是借助百度SDK来实现,在前面写到的文字识别文章中已经使用过了此方式,我们只要换下调用方法即可(感觉可以写一个C#调用百度AI平台的专栏了。。)

去 百度AI开放平台 查找关于人脸功能的模块,获取到api_key和secret_key即可

C# 人脸检测_百度

实现功能:

    • 检测图片中是否存在人脸并显示年龄、颜值等数据

开发环境:

开发工具:Visual Studio 2013

.NET Framework版本:4.5

实现代码:


//从官网下载AipSdk.dll引用到自己项目


//填写自己账号的api_key和secret_key
string api_key = "", secret_key = "";


//人脸检测
private void btnDetector_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
MessageBox.Show("请先复制图片到图片框");
return;
}


//设置鼠标等待
this.Cursor = Cursors.WaitCursor;
//开始识别
Baidu.Aip.Face.Face client = new Baidu.Aip.Face.Face(api_key, secret_key);
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("max_face_num", 1);//最大识别人脸数
dic.Add("face_fields", "result_num,age,beauty");//返回人脸数,年龄,颜值
JObject result = client.Detect(ImageToByte((Bitmap)pictureBox1.Image), dic);
if ((int)result["result_num"] == 0)
{
textBox1.Text = "未检测到人脸";
}
else
{
Image img = pictureBox1.Image.Clone() as Image;
Graphics g = Graphics.FromImage(img);
string text = "识别到" + result["result_num"] + "张人脸\r\n";
foreach (var face in result["result"])
{
text += "年龄:" + face["age"] + ";颜值分值:" + face["beauty"] + "\r\n";
//画人脸位置
Rectangle rect = new Rectangle((int)face["location"]["left"], (int)face["location"]["top"], (int)face["location"]["width"], (int)face["location"]["height"]);
g.DrawRectangle(new Pen(Color.Red), rect);
}
pictureBox1.Image = img;
textBox1.Text = text;
}
//设置鼠标还原
this.Cursor = Cursors.Default;


}


//图片转byte[]
public byte[] ImageToByte(Bitmap inImg)
{
MemoryStream mstream = new MemoryStream();
inImg.Save(mstream, ImageFormat.Bmp);
byte[] bytes = new Byte[mstream.Length];
mstream.Position = 0;
mstream.Read(bytes, 0, bytes.Length);
mstream.Close();
return bytes;
}


//需要解决方案源码的话,可执行以下代码
string text = "E5BEAEE4BFA1E6909CE7B4A2E585ACE4BC97E58FB7EFBC9A43736861727020E5B08FE8AEB0";
int k = 0;
byte[] bytes = new byte[text.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = byte.Parse(text.Substring(k, 2), System.Globalization.NumberStyles.HexNumber);
k += 2;
}
Console.WriteLine(Encoding.UTF8.GetString(bytes));


实现效果:

C# 人脸检测_解决方案_02

其实这个功能比较简单,可以不借助百度SDK,用OpenCV实现本地检测,嗯,后面会写。。。

若需要整个解决方案源码,请私信 人脸检测 获取;

由简入繁,拿来即用

后续精彩,持续关注

欢迎关注公众号: dotnet编程大全