C#调用百度ai之图像识别

效果图:
C#调用百度ai之图像识别_第1张图片
基本代码以前在前一篇中展示了,
主要是这边转码有点坑,第一种 不要urlencode,图片格式尽量要为jpg吧

//定义一个全局变量
private static int Result_num = 1;
var picclient = new Baidu.Aip.ImageClassify.ImageClassify("NpBGfUR6qBGtFo5bIFbiPCO9", "S0L7LXAewfW7BBKmbXd0EQ8iRzEYRGqc")
                    {
     
                        Timeout = 60000  // 修改超时时间
                    };
                    Image img = this.picbPreview.Image;
                    MemoryStream ms = new MemoryStream();
                    byte[] imagedata = null;
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    imagedata = ms.GetBuffer();

                    var picoptions = new Dictionary<string, object> {
      {
      "baike_num",Result_num } };

                    var results = picclient.AdvancedGeneral(imagedata, picoptions);
                    if (results != null && results.ToString() != null && results.ToString().Length > 0)
                    {
     

                        var json = JsonConvert.SerializeObject(results);
                        ImageRecognitionModel model = DeserializeJsonToObject<ImageRecognitionModel>(json) ?? new ImageRecognitionModel();
                        ImageRecognitionBind(model);
                    }

第二种直接打开一个文件,进行图片转码

 OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string _path = ofd.FileName;
            var picclient = new Baidu.Aip.ImageClassify.ImageClassify("NpBGfUR6qBGtFo5bIFbiPCO9", "S0L7LXAewfW7BBKmbXd0EQ8iRzEYRGqc")
            {
     
                Timeout = 60000 // 修改超时时间
            };
            var image = File.ReadAllBytes(_path);
            var picoptions = new Dictionary<string, object> {
      };
            var results = picclient.AdvancedGeneral(image, picoptions);
            if (results != null && results.ToString() != null && results.ToString().Length > 0)
            {
     

                var json = JsonConvert.SerializeObject(results);
                ImageRecognitionModel model = DeserializeJsonToObject<ImageRecognitionModel>(json) ?? new ImageRecognitionModel();
                ImageRecognitionBind(model);
            }

结束

 /// 
        /// 图像识别绑定信息
        /// 
        /// 
        public void ImageRecognitionBind(ImageRecognitionModel model)
        {
     
            //清空文本框
            TestTextBoxAdd(textBox2, "", "", true);
            if (model != null && model.Log_id != 0)
            {
     
                if (model.Result_num > 0 && model.Result != null && model.Result.Count > 0)
                {
     
                    int count = 0;
                    foreach (var item in model.Result)
                    {
     
                        count++;
                        TestTextBoxAdd(textBox2, $"{item.Root}-{item.Keyword}-置信度{item.Score * 100}%",count+"" );
                        if (item.Baike_info != null)
                        {
     
                            TestTextBoxAdd(textBox2, $"{item.Baike_info.Baike_url}", "百科页面链接:");
                            TestTextBoxAdd(textBox2, $"{item.Baike_info.Image_url}", "百科图片链接:");
                            TestTextBoxAdd(textBox2, $"{item.Baike_info.Description}", "百科内容描述:");
                        }
                    }
                }
            }
        }
        /// 
        /// 多行文本框
        /// 
        /// 
        /// 
        /// 
        /// 
        private void TestTextBoxAdd(TextBox textBox, object result, string title,bool IsClearText=false)
        {
     
            // InvokeRequired需要比较调用线程ID和创建线程ID
            // 如果它们不相同则返回true
            if (textBox.InvokeRequired)
            {
     
                SetTextCallback d = new SetTextCallback(TestTextBoxAdd);
                textBox.Invoke(d, new object[] {
      textBox, result, title, IsClearText });
            }
            else
            {
     
                if (IsClearText)
                    textBox.Text = "";
                else
                    textBox.Text += $"{title}{result}{Environment.NewLine}{Environment.NewLine}";
            }
        }

创建一个ImageRecognitionModel类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceRecognitionSystem
{
     
    public class ImageRecognitionModel
    {
     
        /// 
        /// 唯一的log id,用于问题定位
        /// 
        public UInt64 Log_id {
      get; set; }
        /// 
        ///返回结果数目,及result数组中的元素个数
        /// 
        public UInt32 Result_num {
      get; set; }
        /// 
        /// 标签结果数组
        /// 
        public List<ResultItem> Result {
      get; set; }
    }
    public class Baike_info
    {
     
        /// 
        /// 对应识别结果百度百科页面链接
        /// 
        public string Baike_url {
      get; set; }
        /// 
        /// 对应识别结果百科图片链接
        /// 
        public string Image_url {
      get; set; }
        /// 
        /// 对应识别结果百科内容描述
        /// 
        public string Description {
      get; set; }
    }

    public class ResultItem
    {
     
        /// 
        /// 置信度,0-1
        /// 
        public double Score {
      get; set; }
        /// 
        /// 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签
        /// 
        public string Root {
      get; set; }
        /// 
        /// 对应识别结果的百科词条名称
        /// 
        public Baike_info Baike_info {
      get; set; }
        /// 
        /// 图片中的物体或场景名称
        /// 
        public string Keyword {
      get; set; }
    }
}

源码连接:https://github.com/sanpu77001/BaiDuAi.git

你可能感兴趣的:(C#)