C#窗体程序 调用接口 实现人脸识别(附完整项目工程文件)
·
基本功能
1.实现人脸检测功能,显示常用属性
2.实现人脸比对功能,显示比对结果
具体如图:

先安装Baidu.AI
Form1.cs:
using Baidu.Aip.Kg;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;
namespace PiggyFaceRecognition
{
public partial class Form1 : Form
{
float a, b, r, w, h;
float l, t, r0, w0, h0;
string filePath1 = "0";
string filePath2 = "0";
//设置自己的AK SK
String API_KEY = "*******";
String SECRET_KEY = "*******";
Baidu.Aip.Face.Face client;
public Form1()
{
InitializeComponent();
try
{
client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
catch
{
MessageBox.Show("初始化百度接口出错", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
public string ImageToBase64(Image img)
{
try
{
Bitmap bmp = new Bitmap(img);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return null;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// 获取PictureBox和图片的大小
PictureBox pictureBox1 = (PictureBox)sender;
Image image = pictureBox1.Image;
//缩放尺寸
float scale;
//坐标补偿
float additionX = -2;
float additionY = -2;
if (image == null)
return;
if (a == 0|| b == 0 || w == 0 || h == 0 )
return;
// 计算缩放比例
if (image.Width > image.Height)
{
scale = (float)pictureBox1.Width / (float)image.Width;
additionY = ((pictureBox1.Height - image.Height * scale) / 2);
}
else
{
scale = (float)pictureBox1.Height / (float)image.Height;
additionX = ((pictureBox1.Width - image.Width * scale) / 2);
}
float ratationX = a*scale+additionX;
float ratationY = b*scale+additionY;
e.Graphics.TranslateTransform(ratationX, ratationY);
e.Graphics.RotateTransform(r);
// 计算正方形边长并缩放
int squareLength = (int)(Math.Min(w,h) * scale);
// 计算正方形位置
float squareX = a*scale-ratationX+additionX;
float squareY = b* scale - ratationY+additionY;
// 绘制正方形
e.Graphics.DrawRectangle(Pens.Red, squareX, squareY, squareLength, squareLength);
e.Graphics.ResetTransform();
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
// 获取PictureBox和图片的大小
PictureBox pictureBox2 = (PictureBox)sender;
Image image = pictureBox2.Image;
//缩放尺寸
float scale;
//坐标补偿
float additionX = -2;
float additionY = -2;
if (image == null)
return;
if (l == 0 || t == 0 || w0 == 0 || h0 == 0)
return;
// 计算缩放比例
if (image.Width > image.Height)
{
scale = (float)pictureBox2.Width / (float)image.Width;
additionY = ((pictureBox2.Height - image.Height * scale) / 2);
}
else
{
scale = (float)pictureBox2.Height / (float)image.Height;
additionX = ((pictureBox2.Width - image.Width * scale) / 2);
}
float ratationX = l * scale + additionX;
float ratationY = t * scale + additionY;
e.Graphics.TranslateTransform(ratationX, ratationY);
e.Graphics.RotateTransform(r0);
// 计算正方形边长并缩放
int squareLength = (int)(Math.Min(w0, h0) * scale);
// 计算正方形位置
float squareX = l * scale - ratationX + additionX;
float squareY = t * scale - ratationY + additionY;
// 绘制正方形
e.Graphics.DrawRectangle(Pens.Red, squareX, squareY, squareLength, squareLength);
e.Graphics.ResetTransform();
}
//载入图像按钮
private void button1_Click(object sender, EventArgs e)
{
// string filePath = "0";
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "选择文件";
fdlg.FilterIndex = 2;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filePath1 = System.IO.Path.GetFullPath(fdlg.FileName);
}
if (filePath1 == "0") { return; }
pictureBox1.LoadAsync(filePath1);//显示在框
//调用接口
textBox1.Clear();
Image oriImg1 = Image.FromFile(filePath1);//打开图片
var image = ImageToBase64(oriImg1);//转成base64
var imageType = "BASE64";
// 如果有可选参数
var options = new Dictionary<string, object>{
{"face_field", "age,,beauty,expression,face_shape,gender,race,face_type"},
{"max_face_num", 1},
{"face_type", "LIVE"},
};
//表情
var exp = new Dictionary<string, object>
{
{"smile","微笑" },
{"none","不笑" },
{"laugh","大笑" },
};
//脸型
var fs = new Dictionary<string, object>
{
{"triangle","三角形" },
{"square","国字脸" },
{"oval","鸭蛋脸" },
{"heart"," 锥子脸" },
{ "round","圆形脸"}
};
//性别
var gd = new Dictionary<string, object>
{ {"male","男"},
{"female","女" },
};
//
var ra = new Dictionary<string, object>
{{"yellow","黄种人"},
{"black","黑人"},
{"white","白人"},
};
// 带参数调用人脸检测
var result = client.Detect(image, imageType, options);
var items = result["result"]["face_list"];
//获取位置信息
var items1 = result["result"]["face_list"][0]["location"];
a = (float)items1["left"];
b = (float)items1["top"];
r = (float)items1["rotation"];
w =(float)items1["width"];
h =(float)items1["height"];
//
textBox1.Text += "估算年龄: " + items[0]["age"] + "\r\n";
textBox1.Text += "样貌评分: " + items[0]["beauty"] + "\r\n";
textBox1.Text += "表情: " + exp[(String)items[0]["expression"]["type"]] + ", 置信度:" + (String)items[0]["expression"]["probability"] + "\r\n";
textBox1.Text += "脸型: " + fs[(String)items[0]["face_shape"]["type"]] + ", 置信度:" + (String)items[0]["face_shape"]["probability"] + "\r\n";
textBox1.Text += "性别: " + gd[(String)items[0]["gender"]["type"]] + ", 置信度:" + (String)items[0]["gender"]["probability"] + "\r\n";
textBox1.Text += "人种: " + ra[(String)items[0]["race"]["type"]] + ", 置信度:" + (String)items[0]["race"]["probability"] + "\r\n";
}
//载入图像按钮
private void button2_Click(object sender, EventArgs e)
{
// string filePath = "0";
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "选择文件";
fdlg.FilterIndex = 2;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filePath2 = System.IO.Path.GetFullPath(fdlg.FileName);
}
if (filePath2 == "0") { return; }
pictureBox2.LoadAsync(filePath2);
textBox2.Clear();
Image oriImg = Image.FromFile(filePath2);//打开图片
var image = ImageToBase64(oriImg);//转成base64
var imageType = "BASE64";
// 如果有可选参数
var options = new Dictionary<string, object>{
{"face_field", "age,,beauty,expression,face_shape,gender,race,face_type"},
{"max_face_num", 1},
{"face_type", "LIVE"},
};
//表情
var exp = new Dictionary<string, object>
{
{"smile","微笑" },
{"none","不笑" },
{"laugh","大笑" },
};
//脸型
var fs = new Dictionary<string, object>
{
{"triangle","三角形" },
{"square","国字脸" },
{"oval","鸭蛋脸" },
{"heart"," 锥子脸" },
{ "round","圆形脸"}
};
//性别
var gd = new Dictionary<string, object>
{ {"male","男"},
{"female","女" },
};
//
var ra = new Dictionary<string, object>
{{"yellow","黄种人"},
{"black","黑人"},
{"white","白人"},
};
// 带参数调用人脸检测
var result = client.Detect(image, imageType, options);
var items = result["result"]["face_list"];
//获取位置信息
var items1 = result["result"]["face_list"][0]["location"];
l = (float)items1["left"];
t = (float)items1["top"];
r0 = (float)items1["rotation"];
w0 = (float)items1["width"];
h0 = (float)items1["height"];
textBox2.Text += "估算年龄: " + items[0]["age"] + "\r\n";
textBox2.Text += "样貌评分: " + items[0]["beauty"] + "\r\n";
// textBox2.Text += "样貌评分: " + "99.07" + "\r\n";
textBox2.Text += "表情: " + exp[(String)items[0]["expression"]["type"]] + ", 置信度:" + (String)items[0]["expression"]["probability"] + "\r\n";
textBox2.Text += "脸型: " + fs[(String)items[0]["face_shape"]["type"]] + ", 置信度:" + (String)items[0]["face_shape"]["probability"] + "\r\n";
textBox2.Text += "性别: " + gd[(String)items[0]["gender"]["type"]] + ", 置信度:" + (String)items[0]["gender"]["probability"] + "\r\n";
textBox2.Text += "人种: " + ra[(String)items[0]["race"]["type"]] + ", 置信度:" + (String)items[0]["race"]["probability"] + "\r\n";
}
//人脸对比按钮
private void button3_Click(object sender, EventArgs e)
{
textBox3.Clear();
if (filePath1 == "0"|| filePath2 == "0") {
textBox3.Text = "请放入两张对比的图片。";
return;
}
Image oriImg1 = Image.FromFile(filePath1);//打开图片
var image1 = ImageToBase64(oriImg1);//转成base64
Image oriImg2 = Image.FromFile(filePath2);//打开图片
var image2 = ImageToBase64(oriImg2);//转成base64
var faces = new JArray {
new JObject {
{"image",image1},
{"image_type", "BASE64"}},
new JObject {
{"image", image2},
{"image_type", "BASE64"}}};
var result = client.Match(faces);
if ((int)result["result"]["score"] == 100)
{
textBox3.Text = "同一个人" + "\r\n" + "得分:" + (int)result["result"]["score"];
}
else if ((int)result["result"]["score"] >= 80)
{
textBox3.Text = "很像" + "\r\n" + "得分:" + (int)result["result"]["score"];
}
else if ((int)result["result"]["score"] < 80 && (int)result["result"]["score"] >= 30)
{
textBox3.Text = "有些像" + "\r\n" + "得分:" + (int)result["result"]["score"];
}
else if ((int)result["result"]["score"] < 30)
{
textBox3.Text = "不像" + "\r\n" + "得分:" + (int)result["result"]["score"];
}
}
}
}
窗体控件自行修改
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐




所有评论(0)