赞
踩
本项目代码已经开源,可通过文章末尾的链接进行查看。注意的是,本项目的代码涉及到隐私内容(如AK、SK)均作脱敏处理,部分代码因个人原因不做展示,请读者自行脑补。
这里跳过在百度ai开放平台进行登录、领取免费额度(或购买额度)的操作。
我们在这里百度智能云 - 管理中心创建应用(记得勾选需要的功能)后,就可以在如图所示的界面中找到自己的API Key、Secret Key,记住这两个key
都很重要,不要泄露出去,以避免不必要的损失。
这里我们直接根据技术文档中的示例代码进行AccessToken
获取,AccessToken
的获取示例代码如下:
using System; using System.Collections.Generic; using System.Net.Http; namespace com.baidu.ai { public static class AccessToken { // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存 // 返回token示例 public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567"; // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务 private static String clientId = "百度云应用的AK"; // 百度云中开通对应服务应用的 Secret Key private static String clientSecret = "百度云应用的SK"; public static String getAccessToken() { String authHost = "https://aip.baidubce.com/oauth/2.0/token"; HttpClient client = new HttpClient(); List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>(); paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials")); paraList.Add(new KeyValuePair<string, string>("client_id", clientId)); paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret)); HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result; String result = response.Content.ReadAsStringAsync().Result; Console.WriteLine(result); return result; } } }
在这里直接把API Key、Secret Key修改为自己的key就行了。需要注意的是,这里返回的result
值是一个json,里面包含了不止AccessToken的信息,需要我们自行写一个函数进行AccessToken值提取。
在可视化人脸库这里,我们可以很轻松地创建自己的人脸库,并且可以在这个人脸库中手动添加照片。但是这样做太麻烦了,我们会在后面的内容中直接调用函数来进行人脸注册。
这里直接套用百度的示例代码即可:
using System; using System.IO; using System.Net; using System.Text; using System.Web; namespace com.baidu.ai { public class FaceSearch { // 人脸搜索 public static string faceSearch() { string token = "[调用鉴权接口获取的token]"; string host = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + token; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post"; request.KeepAlive = true; String str = "{"image":"027d8308a2ec665acb1bdf63e513bcb9","image_type":"FACE_TOKEN","group_id_list":"group_repeat,group_233","quality_control":"LOW","liveness_control":"NORMAL"}"; byte[] buffer = encoding.GetBytes(str); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string result = reader.ReadToEnd(); Console.WriteLine("人脸搜索:"); Console.WriteLine(result); return result; } } }
在这里我们需要修改的是string token = "[调用鉴权接口获取的token]";
,将token换成我们前文提到的函数;String str = "{"image":"……","image_type":"……","group_id_list":"……","quality_control":"……","liveness_control":"……"}";
这里面的值修改成你想要的属性,具体有哪些属性可以在技术文档中看到。
在这里先把我的成品ui图放出来:
这里我们将按照该ui界面展示的功能进行逐一功能描述。
private void search_device()
{
vedioDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (vedioDevices != null && vedioDevices.Count > 0)
{
comboBox1.Items.Clear();
foreach (FilterInfo device in vedioDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0;
}
}
这里我们选用FilterCategory来收集设备上可用视频设备。
private void CameraConn()
{
if (comboBox1.Items.Count<=0)
{
return;
}
videoSource = new VideoCaptureDevice(vedioDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.VideoResolution = videoSource.VideoCapabilities[0];
videoSource.DesiredFrameRate = 1;
videoSourcePlayer1.VideoSource = videoSource;
videoSourcePlayer1.Start();
}
这里我们通过设置组件videoSource来进行摄像头的调用。
private void button9_Click(object sender, EventArgs e) { if (!videoSourcePlayer1.IsRunning) { 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); selectedImage1Path = picName; MessageBox.Show("照片保存成功,保存在:\n"+ picName); } pictureBox2.SizeMode = PictureBoxSizeMode.Zoom; pictureBox2.Load(picName); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
这段代码实现了通过摄像头捕获当前视频帧,并将其保存为图像文件。通过使用videoSourcePlayer1控件获取视频帧,并使用PngBitmapEncoder进行编码和保存,实现了将摄像头捕获的图像保存到指定路径并显示在pictureBox2控件上的功能。
string selectedImage1Path = ""; string selectedImage2Path = ""; private void pictureBox2_Click(object sender, EventArgs e) { try { openFileDialog1.Filter = "选择图片|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { selectedImage1Path = openFileDialog1.FileName; } pictureBox2.SizeMode = PictureBoxSizeMode.Zoom; pictureBox2.Load(selectedImage1Path); } catch (Exception ex) { MessageBox.Show("错误:" + ex.Message); } }
这段代码实现了通过点击图片框来选择并显示图片文件的功能。通过使用openFileDialog1对话框来选择文件,并将选择的图片文件路径存储在变量中,然后使用pictureBox2.Load方法加载该图片文件并在图片框上显示。这样,用户就可以通过点击图片框来选择要显示的图片文件。
private void button1_Click(object sender, EventArgs e)
{
string token = getAccessToken();
if (!string.IsNullOrEmpty(token))
{
MessageBox.Show($"获取AccessToken成功,access_Token为:\n{token}");
}
return;
}
参考百度人脸识别技术文档
// 转换base64编码 public static string ConvertJpgToBase64(string imagePath) { try { using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) { byte[] imageBytes = new byte[fileStream.Length]; fileStream.Read(imageBytes, 0, (int)fileStream.Length); return Convert.ToBase64String(imageBytes); } } catch (Exception ex) { // 处理异常,例如文件不存在或无法读取 Console.WriteLine($"转换错误: {ex.Message}"); return null; } }
这个方法的作用是将指定的JPEG图像文件转换为Base64编码的字符串表示形式。使用FileStream读取图像文件的内容,并将其转换为字节数组。然后,使用Convert.ToBase64String方法将字节数组转换为Base64编码的字符串。这对于在需要将图像数据以文本形式传输或存储的场景非常有用。
照片均来源于网络,侵删。
本项目展示了如何使用百度智能云的人脸识别功能,涉及API Key和Secret Key的获取与调用。项目通过示例代码详细介绍了AccessToken的获取过程,并演示了人脸库的创建与应用。代码实现了摄像头的连接、拍照功能、图片加载等操作,结合百度智能云的API实现了人脸检测、人脸对比和人脸登录等功能。本文提供的代码示例和技术文档链接将有助于读者更好地理解和应用人脸识别技术。具体实现细节和完整代码请参考本文提供的链接。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。