首先去百度下载中心根据语言下载相关的SDK,地址:点击打开链接
下载完成后根据开发环境引入相关的dll如下图:
因为人脸识别用到了摄像头因此还需要 WPFMediaKit.dll
有关WPFMediaKit.dll的操作可参考我以前写过的《C#调用摄像头拍照》
人脸对比百度文档中心地址:点击打开链接
创建一个WPF应用
编码:
1.窗口设置
效果图:
需要用到的常量:
private static string oldImg = "d:/oldImg.jpg";
private static string newImg = "d:/newImg.jpg";
//APIKEY,SecretKey去百度申请 地址:https://console.bce.baidu.com/ai/#/ai/speech/app/list
private static string APIKEY= "moKpXShsda"; //去百度申请后替换
private static string SecretKey= "q8vEN4QxEHfs";//去百度申请后替换
按钮点击事件:
a.打开摄像头:
string[] ss = MultimediaUtil.VideoInputNames;
foreach (string s in ss)
{
vce.VideoCaptureSource = s;
}
b.信息录入
RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth,(int)vce.ActualHeight,96, 96, PixelFormats.Default);
bmp.Render(vce);
BitmapEncoder encoder = new JpegBitmapEncoder();//默认使用JPG格式保存,可以切换成其他格式,因为JPG格式的文件更小,所以这里推荐使用
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
byte[] data = ms.ToArray();
//保存图片
File.WriteAllBytes(oldImg, data);
}
vce.Pause();
MessageBox.Show("信息录入成功");
vce.VideoCaptureSource = "";
c.人脸识别
private void Button_Click_1(object sender, RoutedEventArgs e)
{
RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth,(int)vce.ActualHeight,96, 96, PixelFormats.Default);
bmp.Render(vce);
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
byte[] data = ms.ToArray();
File.WriteAllBytes(newImg, data);
}
var client = new Baidu.Aip.Face.Face(APIKEY, SecretKey);//这的KEY可以到百度申请
var faces = new JArray{
new JObject
{
{"image", ReadImg(oldImg)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
},
new JObject
{
{"image", ReadImg(newImg)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
}
};
rtb.Text = client.Match(faces).ToString();
if(rtb.Text.Contains("score"))
{
var result = client.Match(faces)["result"]["score"].ToString();//发送并解析返回的数据,获取两个数据的相似度
MessageBox.Show("相似度:" + result + "%,大于90%");
}
else
{
MessageBox.Show("相似度0");
}
vce.VideoCaptureSource = "";
}
public string ReadImg(string img)
{
return Convert.ToBase64String(File.ReadAllBytes(img));
}
源码下载地址:点击打开链接
效果图: