【征稿计划第二期】红酒识别
让天涯 发布于2019-07 浏览:3144 回复:0
0
收藏

【使用攻略】【图像技术】红酒识别

一、需求描述

“来一瓶82年的拉菲”,相信大家一定听过这个梗(对于红酒的认识,我也就只知道这个梗了,惭愧。。。),在红酒消费越来越趋平民化的今天,了解一些红酒知识还是有好处的。但是如果作为一个普通人,想要根据掌握的红酒知识,直接说出眼前的红酒的名称国家、产区、特点等信息,还是具有一定的困难的。

因此,如果能够使用百度AI的“红酒识别”技术,只需要简单拍张照,直接反馈给你眼前的红酒信息,相信还是会受到不少喜欢品酒的人的喜欢的。

二、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。
(1)平台接入

登陆 百度智能云-管理中心 创建 “图像识别”应用,获取 “API Key ”和 “Secret Key” :https://console.bce.baidu.com/ai/?_=1563948654041&fromai=1#/ai/imagerecognition/overview/index
(2)接口文档

文档地址:https://ai.baidu.com/docs#/ImageClassify-API/71e05fb6

接口描述:该服务用于识别红酒标签,即对于输入的一张图片(可正常解码,长宽比适宜,且酒标清晰可见),输出图片中的红酒名称、国家、产区、酒庄、类型、糖分、葡萄品种、酒品描述等信息。可识别数十万中外常见红酒。
请求说明
请求示例

HTTP 方法:POST

请求URL: https://aip.baidubce.com/rest/2.0/image-classify/v1/redwine

URL参数:

参数	        值
access_token	通过API Key和Secret Key获取的access_token,参考“Access Token获取”

Header如下:

参数	        值
Content-Type	application/x-www-form-urlencoded

Body中放置请求参数,参数详情如下:

参数	是否必选	  类型	可选值范围	说明
image	是	string	-	Base64编码字符串,以图片文件形式请求时必填。(支持图片格式:jpg,bmp,png),图片大小不超过4M。最短边至少15px,最长边最大4096px。 注意:图片的base64编码是不包含图片头的,如(data:image/jpg;base64,)

返回说明
返回参数

字段	是否必选	类型	说明
log_id	是	uint64	请求标识码,随机数,唯一
result	是	dict	识别结果
+hasdetail	是	unit	判断是否返回详细信息(除红酒中文名之外的其他字段),含有返回1,不含有返回0
+wineNameCn	是	string	红酒中文名,无法识别返回空,示例:波斯塔瓦经典赤霞珠品丽珠半甜红葡萄酒
+wineNameEn	否	string	红酒英文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:Bostavan Classic Cabernet
+countryCn	否	string	国家中文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:摩尔多瓦
+countryEn	否	string	国家英文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:Moldova
+regionCn	否	string	产区中文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:波尔多
+regionEn	否	string	产区英文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:Bordeaux
+subRegionCn	否	string	子产区中文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:梅多克
+subRegionEn	否	string	子产区英文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:Medoc
+wineryCn	否	string	酒庄中文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:波斯塔瓦酒庄
+wineryEn	否	string	酒庄英文名,hasdetail = 0时,表示无法识别,该字段不返回,示例:Vinaria Bostavan
+classifyByColor	否	string	酒类型,hasdetail = 0时,表示无法识别,该字段不返回,示例:红葡萄酒
+classifyBySugar	否	string	糖分类型,hasdetail = 0时,表示无法识别,该字段不返回,示例:半甜型
+color	否	string	色泽,hasdetail = 0时,表示无法识别,该字段不返回,示例:宝石红色
+grapeCn	否	string	葡萄品种,可能有多种葡萄,hasdetail = 0时,表示无法识别,该字段不返回,示例:品丽珠;赤霞珠
+grapeEn	否	string	葡萄品种英文名,可能有多种葡萄,hasdetail = 0时,表示无法识别,该字段不返回,示例:Cabernet Franc;Cabernet Sauvignon
+tasteTemperature	否	string	品尝温度,hasdetail = 0时,表示无法识别,该字段不返回,示例:6-11℃
+description	否	string	酒品描述,hasdetail = 0时,表示无法识别,该字段不返回,示例:葡萄酒呈深宝石红色,具有香料、香草和新鲜水果的果香,酒体分明,口感畅顺,果香横溢,单宁软化程度高,让你回味无穷

返回示例

仅识别出红酒名称,hasdetail = 0:

{
    "log_id": 3450013152046070669,
    "result":
    {
        "wineNameCn": "银色高地阙歌干红",
        "hasdetail":0
    }
}

识别出详细信息,hasdetail = 1:

{
    "log_id": 2495538539661269738,
    "result": {
        "classifyByColor": "红葡萄酒/Red Wine",
        "subRegionCn": "梅多克",
        "wineNameCn": "拉图嘉利庄园红葡萄酒(正牌)",
        "subRegionEn": "Medoc",
        "regionEn": "Bordeaux",
        "color": "深紫红色/Dark Violet",
        "wineNameEn": "Chateau La Tour Carnet",
        "hasdetail": 1,
        "wineryCn": "拉图嘉利庄园",
        "classifyBySugar": "干型/Dry",
        "tasteTemperature": "16-18℃",
        "regionCn": "波尔多",
        "wineryEn": "Chateau La Tour-Carnet",
        "grapeCn": "",
        "grapeEn": "",
        "countryCn": "法国",
        "countryEn": "France",
        "description": "此酒充满红果和黑果味道,并带有矿物质和花香(紫罗兰,玫瑰),混合些许香草气息,单宁柔软,余香悠长。在口中留下清新的味道,香料和香草味道萦绕口中。"
    }
}

(3)源码共享

3.1-根据 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.2-调用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="Redwine" ,提交并返回识别结果。

    一个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 OnPostRedwineAsync()
        {
           
            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)JsonStringToObj(result);

            try
            {
                msg.Add("红酒中文名:" + jo["result"]["wineNameCn"].ToString());
                if (jo["result"]["hasdetail"].ToString().Equals("1"))
                {
                    msg.Add("红酒英文名:" + jo["result"]["wineNameEn"].ToString());
                    msg.Add("国家:" + jo["result"]["countryCn"].ToString());
                    msg.Add("产区:" + jo["result"]["regionCn"].ToString());
                    msg.Add("子产区:" + jo["result"]["subRegionCn"].ToString());
                    msg.Add("酒庄:" + jo["result"]["wineryCn"].ToString());
                    msg.Add("酒类型:" + jo["result"]["classifyByColor"].ToString());
                    msg.Add("糖分类型:" + jo["result"]["classifyBySugar"].ToString());
                    msg.Add("色泽:" + jo["result"]["color"].ToString());
                    msg.Add("葡萄品种:" + jo["result"]["grapeCn"].ToString());
                    msg.Add("品尝温度:" + jo["result"]["tasteTemperature"].ToString());
                    msg.Add("酒品描述:" + jo["result"]["description"].ToString());
                }
            }
            catch (Exception e)
            {
                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/v1/redwine?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);
            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

2.2

2.3

四、产品建议

1、希望能结合百度百科信息,提供更多的识别的红酒知识。

2、如果能提供如何辨别当前红酒真假的技巧信息就更好了。

3、此外,红酒数据库内容还不够丰富,有些红酒不能识别,或不能提供更加详细的内容。

收藏
点赞
0
个赞
TOP
切换版块