当前位置:   article > 正文

C# winform 百度AI的图像多主体识别——写来玩玩_c# 调用百度云api 图像分类

c# 调用百度云api 图像分类

效果如图:

 第一步:

选择本地图片

  1. OpenFileDialog openFileDialog = new OpenFileDialog();
  2. openFileDialog.InitialDirectory = @"C:\";
  3. openFileDialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif";
  4. openFileDialog.RestoreDirectory = true;
  5. openFileDialog.FilterIndex = 1;
  6. if (openFileDialog.ShowDialog() == DialogResult.OK)
  7. {
  8. filename = openFileDialog.FileName;
  9. FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
  10. Image image = System.Drawing.Image.FromStream(fs);
  11. pictureBox1.Image = image;
  12. fs.Close();
  13. }

第二步:获取百度AI AccessToken

  1. private static String clientId = "应用ID";
  2. private static String clientSecret = "应用密钥";
  3. public string access_token = "";
  4. public string getAccessToken()
  5. {
  6. String authHost = "https://aip.baidubce.com/oauth/2.0/token";
  7. HttpClient client = new HttpClient();
  8. List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
  9. paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
  10. paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
  11. paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
  12. HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
  13. String result = response.Content.ReadAsStringAsync().Result;
  14. token tm = new token();
  15. JavaScriptSerializer js = new JavaScriptSerializer();
  16. tm = js.Deserialize<token>(result);
  17. access_token = tm.access_token;
  18. return result;
  19. }
  20. public class token
  21. {
  22. public string refresh_token { get; set; }
  23. public string expires_in { get; set; }
  24. public string session_key { get; set; }
  25. public string access_token { get; set; }
  26. public string scope { get; set; }
  27. public string session_secret { get; set; }
  28. }

第三步:调用百度AI的图像多主体解析API端口,返回值具体说明见代码中实体类。

  1. public List<imgObjectDetect> multiObjectDetect(string fileName)
  2. {
  3. try
  4. {
  5. string token = access_token;
  6. string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/multi_object_detect?access_token=" + token;
  7. Encoding encoding = Encoding.Default;
  8. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
  9. request.Method = "post";
  10. request.KeepAlive = true;
  11. // 图片的base64编码
  12. string base64 = getFileBase64(fileName);
  13. String str = "image=" + HttpUtility.UrlEncode(base64);
  14. byte[] buffer = encoding.GetBytes(str);
  15. request.ContentLength = buffer.Length;
  16. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  17. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  18. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  19. string result = reader.ReadToEnd().Replace('?', '\"');
  20. Byte[] timeoutStrTemp = Encoding.Default.GetBytes(result);
  21. result = Encoding.UTF8.GetString(timeoutStrTemp);
  22. muliObject objects = JsonConvert.DeserializeObject<muliObject>(result);
  23. return objects.result;
  24. }
  25. catch (Exception ex)
  26. {
  27. return null;
  28. }
  29. }
  30. public static String getFileBase64(String fileName)
  31. {
  32. FileStream filestream = new FileStream(fileName, FileMode.Open);
  33. byte[] arr = new byte[filestream.Length];
  34. filestream.Read(arr, 0, (int)filestream.Length);
  35. string baser64 = Convert.ToBase64String(arr);
  36. filestream.Close();
  37. return baser64;
  38. }
  39. public class Location
  40. {
  41. //宽度
  42. public int width { get; set; }
  43. //到图像顶部的距离
  44. public int top { get; set; }
  45. //到图像左边的距离
  46. public int left { get; set; }
  47. //高度
  48. public int height { get; set; }
  49. public override string ToString()
  50. {
  51. return "top:" + top + ";left:" + left + ";width:" + width + ";height:" + height + ";";
  52. }
  53. }
  54. public class imgObjectDetect
  55. {
  56. public double score { get; set; }
  57. //名称
  58. public string name { get; set; }
  59. //位置
  60. public Location location { get; set; }
  61. }
  62. public class muliObject
  63. {
  64. public string log_id { get; set; }
  65. public List<imgObjectDetect> result { get; set; }
  66. }

第四步:全部应用到图像中,红框标注

  1. Bitmap bitmap = new Bitmap(filename);
  2. foreach (baiduAI.imgObjectDetect item in imgObjectDetects)
  3. {
  4. int top = item.location.top;
  5. int left = item.location.left;
  6. int width = item.location.width;
  7. int height = item.location.height;
  8. for (int i = top; i < top + height; i++)
  9. {
  10. bitmap.SetPixel(left, i, Color.Red);
  11. bitmap.SetPixel(width + left, i, Color.Red);
  12. }
  13. for (int i = left; i < left + width; i++)
  14. {
  15. bitmap.SetPixel(i, top, Color.Red);
  16. bitmap.SetPixel(i, height + top, Color.Red);
  17. }
  18. }
  19. pictureBox1.Image = Image.FromHbitmap(bitmap.GetHbitmap());
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/347128
推荐阅读
相关标签
  

闽ICP备14008679号