使用C#实现百度API【人脸检测】V3版

第一次使用百度API  C#程序(测试用)

使用C#实现百度API【人脸检测】V3版_第1张图片

最近实现

详细查看完整代码Github:https://github.com/122537067/PeopleDetect

使用C#实现百度API【人脸检测】V3版_第2张图片

首先阅读文档

http://ai.baidu.com/docs#/Face-Detect-V3/top

第一步:注册百度账号获取Access TOKEN

添加应用

使用C#实现百度API【人脸检测】V3版_第3张图片

得到Secret Key 和API Key

API Key 对应文档中的 clientId

SecretKey 对应文档中的 clientSecret

百度云文档C#源码如下

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> paraList = new List>();
			paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
			paraList.Add(new KeyValuePair("client_id", clientId));
			paraList.Add(new KeyValuePair("client_secret", clientSecret));

			HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
			String result = response.Content.ReadAsStringAsync().Result;
			Console.WriteLine(result);
			return result;
		}
	}
}

到这步可以测试一下Access Token是否已经获取成功(获取失败代码参见文档http://ai.baidu.com/docs#/Auth/9d0f74c9)

 

第二步:调用接口,获取JSON数据

// 人脸检测与属性分析
        public static string detect(String PictureBase64)
        {
            string token = AccessToken.getAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            String str = "{\"image\":\"" + PictureBase64 + "\",\"image_type\":\"BASE64\",\"face_field\":\"age,type\"}";
            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;
        }

str是接口处理的数据,我image_type使用的是BASE64,face_field只返回了age和type的属性,其他属性参见文档自己添加

文档的str是这样写,根据自己需求可以替换添加

String str = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"face_field\":\"faceshape,facetype\"}";

例如我想直接饮用网上的图片路径(URL),则这样写

String str = "{\"image\":\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533237885029&di=71c13d1cb749956107720a0c94f40876&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F9a504fc2d56285358e6bf5d59aef76c6a6ef63be.jpg\",\"image_type\":\"URL\",\"face_field\":\"faceshape,facetype\"}";

使用C#实现百度API【人脸检测】V3版_第4张图片

使用BASE64类型的话要将图片转换成BASE64形式,然后调用接口。

 

第二步:JSON数据的解析

调用接口返回的是JSON数据,需要对JSON数据进行转换。

下载开源的类库Newtonsoft.Json(下载地址 http://json.codeplex.com/ )。

(或者直接在VS里面下载)

使用C#实现百度API【人脸检测】V3版_第5张图片

使用C#实现百度API【人脸检测】V3版_第6张图片

定义类定义JSON数据,可以使用工具http://json2csharp.chahuo.com/

使用方法:将要处理的json字符串复制到文本框即可以得到C#类,如图所示:

使用C#实现百度API【人脸检测】V3版_第7张图片

 

解析JSON数据的代码如下:

private void button_change_Click(object sender, EventArgs e)
        {
            //解析JSON数据
            RootObject people = JsonConvert.DeserializeObject(textBox_token.Text);

            //获取值
            textBox_token.Text = "转换结果:";
            textBox_token.Text += people.error_msg + "\r\n" + "\r\n";

            textBox_token.Text += "这是一张人脸的概率:";
            textBox_token.Text += people.result.face_list[0].face_probability + "\r\n" + "\r\n";

            textBox_token.Text += "年龄:";
            textBox_token.Text += people.result.face_list[0].age + "\r\n" + "\r\n";

            textBox_token.Text += "颜值:";
            textBox_token.Text += people.result.face_list[0].beauty + "\r\n" + "\r\n";

            textBox_token.Text += "表情:";
            textBox_token.Text += people.result.face_list[0].expression.probability + "概率是";
            string expression_type = people.result.face_list[0].expression.type;
            if(expression_type == "none") { expression_type = "冷漠脸"; }
            else if(expression_type == "smile") { expression_type = "微笑"; }
            else if (expression_type == "laugh") { expression_type = "大笑"; }
            else { expression_type = "都不知道你什么表情"; }
            textBox_token.Text += expression_type + "\r\n" + "\r\n";

            //square: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形
            textBox_token.Text += "脸型:";
            textBox_token.Text += people.result.face_list[0].face_shape.probability + "概率是";
            string faceShape = people.result.face_list[0].face_shape.type;
            if (faceShape == "square") { faceShape = "正方形"; }
            else if (faceShape == "triangle") { faceShape = "三角形"; }
            else if (faceShape == "oval") { faceShape = "椭圆"; }
            else if (faceShape == "heart") { faceShape = "心形"; }
            else if (faceShape == "round") { faceShape = "圆形"; }
            else { faceShape = "都不知道你什么头"; }
            textBox_token.Text += faceShape + "\r\n" + "\r\n";

            //male:男性 female:女性
            textBox_token.Text += "性别:";
            textBox_token.Text += people.result.face_list[0].gender.probability + "概率是";
            string sex = people.result.face_list[0].gender.type;
            if (sex == "male") { sex = "男性"; }
            else if (sex == "female") { sex = "女性"; }
            else { sex = "都不知道你什么性别"; }
            textBox_token.Text += sex + "\r\n" + "\r\n";

            //none:无眼镜,common:普通眼镜,sun:墨镜
            textBox_token.Text += "眼镜类型:";
            textBox_token.Text += people.result.face_list[0].glasses.probability + "概率是";
            string glasse = people.result.face_list[0].glasses.type;
            if (glasse == "none") { glasse = "无眼镜"; }
            else if (glasse == "common") { glasse = "普通眼镜"; }
            else if (glasse == "sun") { glasse = "墨镜"; }
            else { faceShape = "眼呢?"; }
            textBox_token.Text += glasse + "\r\n" + "\r\n";

            //yellow: 黄种人 white: 白种人 black:黑种人 arabs: 阿拉伯人
            textBox_token.Text += "种族:";
            textBox_token.Text += people.result.face_list[0].race.probability + "概率是";
            string race = people.result.face_list[0].race.type;
            if (race == "yellow") { race = "黄种人"; }
            else if (race == "white") { race = "白种人"; }
            else if (race == "black") { race = "黑种人"; }
            else if (race == "arabs") { race = "阿拉伯人"; }
            else { race = "人呢?"; }
            textBox_token.Text += race + "\r\n" + "\r\n";
        }
    }

详细查看完整代码Github:https://github.com/122537067/PeopleDetect

你可能感兴趣的:(使用C#实现百度API【人脸检测】V3版)