欢迎来到 安卓源码空间!
安卓源码空间

                                C# winform 百度AI的图像多主体识别



效果如图:

第一步:

选择本地图片

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

第二步:获取百度AI AccessToken

private static String clientId = "应用ID";
    private static String clientSecret = "应用密钥"; 
    public string access_token = "";
    public 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;
            token tm = new token();
            JavaScriptSerializer js = new JavaScriptSerializer();
            tm = js.Deserialize<token>(result);
            access_token = tm.access_token;
            return result;
        }
    public class token
        {
            public string refresh_token { get; set; }
            public string expires_in { get; set; }
            public string session_key { get; set; }
            public string access_token { get; set; }
            public string scope { get; set; }
            public string session_secret { get; set; }
        }

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

public List<imgObjectDetect> multiObjectDetect(string fileName)
        {
            try
            {
                string token = access_token;
                string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/multi_object_detect?access_token=" + token;
                Encoding encoding = Encoding.Default;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                // 图片的base64编码
                string base64 = getFileBase64(fileName);
                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.Default);
                string result = reader.ReadToEnd().Replace('?', '\"');

                Byte[] timeoutStrTemp = Encoding.Default.GetBytes(result);
                result = Encoding.UTF8.GetString(timeoutStrTemp);

                muliObject objects = JsonConvert.DeserializeObject<muliObject>(result);

                return objects.result;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

       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;
        }
    public class Location
        {
            //宽度
            public int width { get; set; }
            //到图像顶部的距离
            public int top { get; set; }
            //到图像左边的距离
            public int left { get; set; }
            //高度
            public int height { get; set; }

            public override string ToString()
            {
                return "top:" + top + ";left:" + left + ";width:" + width + ";height:" + height + ";";
            }
        }

        public class imgObjectDetect
        {
            public double score { get; set; }
            //名称
            public string name { get; set; }
            //位置
            public Location location { get; set; }
        }

        public class muliObject
        {
            public string log_id { get; set; }
            public List<imgObjectDetect> result { get; set; }
        }

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

Bitmap bitmap = new Bitmap(filename);
            foreach (baiduAI.imgObjectDetect item in imgObjectDetects)
            {
                int top = item.location.top;
                int left = item.location.left;
                int width = item.location.width;
                int height = item.location.height;
                for (int i = top; i < top + height; i++)
                {
                    bitmap.SetPixel(left, i, Color.Red);
                    bitmap.SetPixel(width + left, i, Color.Red);
                }
                for (int i = left; i < left + width; i++)
                {
                    bitmap.SetPixel(i, top, Color.Red);
                    bitmap.SetPixel(i, height + top, Color.Red);
                }
            }
            pictureBox1.Image = Image.FromHbitmap(bitmap.GetHbitmap());



————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
                           原文链接:https://blog.csdn.net/qq_40907356/article/details/120066670

copyright@ 2020-2028  安卓源码空间网版权所有   

备案号:豫ICP备2023034476号-1号