通用物体识别使用攻略

作者:让天涯

一、需求描述

大家在出去旅游的时候,往往会对景点里的特色事物感兴趣,而一般情况下,如果没有导游的介绍,我们不太清楚这个景区里的特色景点是什么,有时候即使看到了一个事物,都不认识它,只能等着导游来介绍,这样的话,旅游的可玩性、自由度都大大降低了。

而如果能够使用百度的【通用物体与场景识别】技术,只需要简单的拍照上传,就能知道这个物品是什么,这个景点叫什么名字,它的由来它的故事等等,那么基本上可以脱离导游,自己一行人按照自己的喜好去游玩,不仅自由,还能增长见识,这样的旅游才有意思,否则的话,只能跟着导游走。

二、应用价值

利用百度【通用物体与场景识别】技术,识别自己旅游/生活中遇到的不认识的物体、场景,了解其背景,增长见识。

三、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。
(1)、登陆 百度智能云-管理中心 创建 “图像识别”应用,获取 “API Key ”和 “Secret Key” :https://console.bce.baidu.com/ai/?_=1561555561720&fromai=1#/ai/imagerecognition/overview/index
(2)、根据 API Key 和 Secret Key 获取 AccessToken。

    ///


    /// 获取百度access_token
    ///
    /// API Key
    /// Secret Key
    ///
    public static string GetAccessToken(string clientId, string clientSecret)
    {
        string authHost = "https://aip.baidubce.com/oauth/2.0/token";
        HttpClient client = new HttpClient();
        List> paraList = new List>();
        paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
        paraList.Add(new KeyValuePair("client_id", clientId));
        paraList.Add(new KeyValuePair("client_secret", clientSecret));


        HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
        string result = response.Content.ReadAsStringAsync().Result;
        JObject jo = (JObject)JsonConvert.DeserializeObject(result);
        string token = jo["access_token"].ToString();
        return token;
    }

(3)、调用API接口获取识别结果

1、在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法中开启虚拟目录映射功能:

        string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录

        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(webRootPath, "Uploads", "BaiduAIs")),
            RequestPath = "/BaiduAIs"
        });

2、 建立Index.cshtml文件

2.1 前台代码:
由于html代码无法原生显示,只能简单说明一下:

主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;

form表单里面有两个控件:

一个Input:type="file",asp-for="FileUpload" ,上传图片用;

一个Input:type="submit",asp-page-handler="Advanced" ,提交并返回识别结果。

一个img:src="@Model.curPath",显示识别的图片。

最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。

2.2 后台代码:

    [BindProperty]
    public IFormFile FileUpload { get; set; }
    private readonly IHostingEnvironment HostingEnvironment;
    public List msg = new List();
    public string curPath { get; set; }


    public BodySearchModel(IHostingEnvironment hostingEnvironment)
    {
        HostingEnvironment = hostingEnvironment;
    }

    public async Task OnPostAdvancedAsync()
    {
        if (FileUpload is null)
        {
            ModelState.AddModelError(string.Empty, "本地图片!");
        }
        if (!ModelState.IsValid)
        {
            return Page();
        }
        msg = new List();

        string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
        string fileDir = Path.Combine(webRootPath, "Uploads//BaiduAIs//");
        string imgName = await UploadFile(FileUpload, fileDir);

        string fileName = Path.Combine(fileDir, imgName);
        string imgBase64 = GetFileBase64(fileName);
        curPath = Path.Combine("/BaiduAIs/", imgName);//需在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env)方法中开启虚拟目录映射功能

        string result = GetImageJson(imgBase64, “你的API KEY”, “你的SECRET KEY”);
        JObject jo =(JObject)JsonConvert.DeserializeObject(result);
        try
        {
            List msgList = jo["result"].ToList();
            int number = int.Parse(jo["result_num"].ToString());
            int curNumber = 1;
            msg.Add("返回结果:" + number + "");
            foreach (JToken ms in msgList)
            {
                if (number > 1)
                {                       
                    msg.Add("第 " + (curNumber++).ToString() + " 条:");
                }
                msg.Add("置信度:" + ms["score"].ToString());
                msg.Add("标签:" + ms["root"].ToString());
                msg.Add("名称:" + ms["keyword"].ToString());
                if (ms["baike_info"] != null)
                {
                    msg.Add("百科词条:");
                    if (ms["baike_info"]["baike_url"] != null)
                    {
                        msg.Add("页面链接");
                    }
                    if (ms["baike_info"]["description"] != null)
                    {
                        msg.Add("内容描述:" + ms["baike_info"]["description"].ToString());
                    }
                    if (ms["baike_info"]["image_url"] != null)
                    {
                        msg.Add("");
                    }
                }
            }
        }
        catch(Exception e1)
        {
            msg.Add(result);
        }
        return Page();
    }

    ///


    /// 上传文件,返回文件名
    ///
    /// 文件上传控件
    /// 文件绝对路径
    ///
    public static async Task UploadFile(IFormFile formFile, string fileDir)
    {
        if (!Directory.Exists(fileDir))
        {
            Directory.CreateDirectory(fileDir);
        }
        string extension = Path.GetExtension(formFile.FileName);
        string imgName = Guid.NewGuid().ToString("N") + extension;
        var filePath = Path.Combine(fileDir, imgName);


        using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            await formFile.CopyToAsync(fileStream);
        }

        return imgName;
    }


    ///


    /// 返回图片的base64编码
    ///
    /// 文件绝对路径名称
    ///
    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;
    }


    ///


    /// 图像识别Json字符串
    ///
    /// 图片base64编码
    /// API Key
    /// Secret Key
    ///
    public static string GetImageJson(string strbaser64, string clientId, string clientSecret)
    {
        string token = GetAccessToken(clientId, clientSecret);
        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;
        string str = "image=" + HttpUtility.UrlEncode(strbaser64)+”&baike_num=5“;
        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();
        return result;
    }

四、效果测试
1、页面:
在这里插入图片描述
2、识别结果:

2.1
在这里插入图片描述
完整识别结果:
返回结果:5

第 1 条:

置信度:0.797064

标签:

名称:诸城恐龙博物馆

百科词条:

页面链接

内容描述:诸城恐龙博物馆位于山东省诸城市,成立于2001年5月9日,是中国第一个县(市)级恐龙博物馆,展出了目前世界上最高大的巨型鸭嘴龙化石骨架和100多件恐龙化石。巨龙馆(诸城恐龙博物馆)。国家4A级旅游景区,建筑面积5400平方米,馆内陈列着世界上最高大的鸭嘴恐龙化石骨架——“巨大诸城龙”(高9.1米,长16.6米),被中外专家誉为“世界第一龙”。展示有世界上最大的“巨型诸城暴龙”和最原始的“诸城中国角龙”等化石骨架以及恐龙骨骼化石、蛋化石等极具代表性的恐龙化石。珍藏于神妙龙骨厅的巨大恐龙股骨化石被誉为“华夏第一奇骨”。先后接待了30多位国家领导人、众多的社会知名人士和数以百万的中外游客。
在这里插入图片描述
根据识别结果可以看出,通用物体的识别结果还是比较准确的,再加上可以显示百度百科信息,这样的话,就能够得到更多更详细的知识了。
当然,对于动物、植物、花卉、地标等百度有专门的识别接口,可以得到更加准确的信息,不过一般情况下,可以调用【通用物体与场景识别】接口来识别,如果识别结果不太满意的话,再调用专门接口进行详细的识别。

发布了10 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45449540/article/details/103297085