unity 使用百度API识别货币和车型

小模块,做个了简单的demo,和之前人脸识别差不多,直接上代码

using com.baidu.ai;
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Net.Http;
public class Test : MonoBehaviour
{
    // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
    // 返回token示例
    public static string TOKEN = "";

    // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务 
    // 填自己申请的key
    private static string clientId = "82vRAVriP1UX6FMgFnzYvvlY";
    // 百度云中开通对应服务应用的 Secret Key
    private static string clientSecret = "5StFKW0VOpcbxfWrP1wu1eH6glG7DuGl";
    /// <summary>
    /// 获取token
    /// </summary>
    public static 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;
        JObject jo = JsonConvert.DeserializeObject<JObject>(result);
        string token = jo["access_token"].ToString();
        TOKEN = token;
        return token;
    }

    void Start()
    {
        getAccessToken();
        StartCoroutine(IEGetStringBase64());
    }
    /// <summary>
    ///  获取图片
    /// </summary>
    IEnumerator IEGetStringBase64()
    {
        //获取到每一张图片的路径  
        // 这里图片要放在本地StreamingAssets文件夹下的FaceDetect或car文件夹(根据要检测的图片),
        // 放在一个文件夹也可以但是会同时检测车型和货币
        string[] picsPathArr = Directory.GetFiles(Application.streamingAssetsPath + "/car/");
        //循环获取每张图片的base64字符串  
        for (int i = 0; i < picsPathArr.Length; i++)
        {
            //unity会自动生成.meta文件,过滤掉  
            if (picsPathArr[i].Contains("meta")) continue;
            //读取  
            FileInfo file = new FileInfo(picsPathArr[i]);
            var stream = file.OpenRead();
            byte[] buffer = new byte[file.Length];
            //读取图片字节流  
            stream.Read(buffer, 0, Convert.ToInt32(file.Length));
            //base64字符串  
            string imageBase64 = Convert.ToBase64String(buffer);
            //开始注册  
            PictrueRecognition(imageBase64);
            yield return new WaitForSeconds(0.6f);
        }
    }
    /// <summary>
    /// 图像识别
    /// </summary>    
    public void PictrueRecognition(string image)
    {
    	// 货币识别
        StartCoroutine(Money.money(TOKEN, image));
        // 车型识别
        Car.car(TOKEN, image);
    }
}


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace com.baidu.ai
{
    public static class Money
    {
        /// <summary>
        /// 货币识别
        /// </summary>
        public static IEnumerator money(string TOKEN, string base64)
        {
            string url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/currency?access_token=" + TOKEN;

            WWWForm form = new WWWForm();
            form.AddField("access_token", TOKEN);
            UnityWebRequest www = UnityWebRequest.Post(url, form);
            www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            base64 = UnityWebRequest.EscapeURL(base64);
            string image = "image=" + base64;
            www.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(image));
            yield return www.SendWebRequest();
            if (www.isHttpError || www.isNetworkError)
                Debug.Log(www.error);
            else
                Debug.Log("货币识别结果" + www.downloadHandler.text);
        }
    }
}
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using UnityEngine;

namespace com.baidu.ai
{
    public class Car
    {
        /// <summary>
        /// 车型识别
        /// </summary>        
        public static string car(string token, string image)
        {
            string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token=" + token;

            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = image;
            string str = "image=" + HttpUtility.UrlEncode(base64) + "&top_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();
            UnityEngine.Debug.Log("车型识别结果" + result);
            return result;
        }
    }
}

直接就能用

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

猜你喜欢

转载自blog.csdn.net/Mediary/article/details/103434757
今日推荐