货币秒识别

(17) 2023-10-08 19:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说货币秒识别,希望能够帮助你!!!。

一、需求描述

随着国家日益强大,我们普通老百姓接触到外国货币的机会越来越多,但是外国货币这么多,这是哪国货币,价值是多少呢?一般人真的分不清楚,不过通过百度的【货币识别】技术,让我们足不出户,分分钟识别货币类型。

二、使用攻略

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

(1)平台接入

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

(2)接口文档

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

接口描述:识别图像中的货币类型,以纸币为主,正反面均可准确识别,接口返回货币的名称、代码、面值、年份信息;可识别各类近代常见货币,如美元、欧元、英镑、法郎、澳大利亚元、俄罗斯卢布、日元、韩元、泰铢、印尼卢比等。

请求说明

请求示例

HTTP 方法:POST

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

URL参数:

货币秒识别_https://bianchenghao6.com/blog__第1张

Header如下:

货币秒识别_https://bianchenghao6.com/blog__第2张

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

请求参数

货币秒识别_https://bianchenghao6.com/blog__第3张

返回说明

返回参数

货币秒识别_https://bianchenghao6.com/blog__第4张

返回示例

{

"log_id": 4247844653395235754,

"result": {

"currencyName": "美元",

"hasdetail": 1,

"currencyCode": "USD",

"year": "2001年",

"currencyDenomination": "50美元"

}

}

(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="Currency" ,提交并返回识别结果。

一个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 OnPostCurrencyAsync()
 {
 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
 {
 msg.Add("货币名称:" + jo["result"]["currencyName"].ToString());
 if (jo["result"]["hasdetail"].ToString().Equals("1"))
 {
 msg.Add("货币代码:" + jo["result"]["currencyCode"].ToString());
 msg.Add("货币面值:" + jo["result"]["currencyDenomination"].ToString());
 msg.Add("货币年份:" + jo["result"]["year"].ToString());
 }
 }
 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/v1/currency?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、页面:

货币秒识别_https://bianchenghao6.com/blog__第5张

2、识别结果:

2.1

货币秒识别_https://bianchenghao6.com/blog__第6张

2.2

货币秒识别_https://bianchenghao6.com/blog__第7张

2.3

货币秒识别_https://bianchenghao6.com/blog__第8张

2.4

货币秒识别_https://bianchenghao6.com/blog__第9张

2.5

货币秒识别_https://bianchenghao6.com/blog__第10张

四、产品建议

1、增加【货币兑换】功能:如果能输入一个目的的货币类型,然后识别货币价值后,能够显示当前兑换成目的货币的价值,功能就更加完善了。

2、增加【货币真假小技巧】功能:对于识别的货币类型,如果能够提供准确判断该货币真假的方法,让普通人也能识别出手中的货币的真假,如若能够拍照自动识别出该货币类型是不是真的就更加玩美了。

3、希望后期能够提供【硬币】识别功能。

原文链接:https://ai.baidu.com/forum/topic/show/953076

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复