1. 程式人生 > >使用C#實現百度API【人臉檢測】V3版

使用C#實現百度API【人臉檢測】V3版

第一次使用百度API  C#程式(測試用)

最近實現

首先閱讀文件

第一步:註冊百度賬號獲取Access TOKEN

新增應用

得到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<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;
		}
	}
}

第二步:呼叫介面,獲取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\"}";

使用BASE64型別的話要將圖片轉換成BASE64形式,然後呼叫介面。

第二步:JSON資料的解析

呼叫介面返回的是JSON資料,需要對JSON資料進行轉換。

下載開源的類庫Newtonsoft.Json(下載地址 http://json.codeplex.com/ )。

(或者直接在VS裡面下載)

定義類定義JSON資料,可以使用工具http://json2csharp.chahuo.com/

使用方法:將要處理的json字串複製到文字框即可以得到C#類,如圖所示:

解析JSON資料的程式碼如下:

private void button_change_Click(object sender, EventArgs e)
        {
            //解析JSON資料
            RootObject people = JsonConvert.DeserializeObject<RootObject>(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";
        }
    }