c#调用百度AI通用物体和场景识别
电脑版发表于:2020/2/14 10:29
public class AdvancedGeneral { // 通用物体和场景识别 public static AdvancedGeneralModel advancedGeneral(string token) { //string token = "[调用鉴权接口获取的token]"; //通用物体和场景识别接口 string host = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + token; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post";//请求方式 request.KeepAlive = true; // 图片的base64编码 string base64 = getFileBase64("c://cc.jpg"); String str = "image=" + HttpUtility.UrlEncode(base64); 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.UTF8); string result = reader.ReadToEnd(); //Console.WriteLine("通用物体和场景识别:"); //Console.WriteLine(result); AdvancedGeneralModel advancedGeneralModel = JsonConvert.DeserializeObject<AdvancedGeneralModel>(result); return advancedGeneralModel; } /// <summary> /// 把图片转化成base64格式 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static String getFileBase64(String fileName) { FileStream filestream = new FileStream(fileName, FileMode.Open); byte[] arr = new byte[filestream.Length]; filestream.Read(arr, 0, (int)filestream.Length); string baser64 = Convert.ToBase64String(arr); filestream.Close(); return baser64; } }
model:
public class AdvancedGeneralModel { public List<SubAdvancedGeneralModel> result { get; set; } } public class SubAdvancedGeneralModel { public string root { get; set; } public string keyword { get; set; } }