OCRIboade

作者: 萧非子 | 来源:发表于2017-11-28 19:28 被阅读14次

    using System.Collections.Generic;
    using System.Collections;
    using UnityEngine;
    using UnityEngine.UI;
    using Baidu.Aip.Ocr;
    using System.IO;
    //using Newtonsoft.Json.Linq;//接收返回结果 JObject
    using LitJson;
    //百度图片文字识别接口调用——非子萧
    public class OCRIboade : MonoBehaviour
    {
    private string deviceName; //摄像头名称
    private WebCamTexture WebCamTexture;//摄像纹理,//必须是Raw Image;改名为CameraTexture
    public RawImage rawImage; //显示摄像的图片
    public Image img_Show; //显示拍出来的照片
    public Image img_Scan; //扫描框
    private string infoLog = ""; //日志信息
    private string strTempTime; //当前时间,拍照的照片名称
    private static WebCamDevice[] webCamArray = null;//硬件
    摄像头数组
    private int index = 0;

    public Text debugInfo;                            // 显示debug信息
    public Text tex_TW;                              // 显示图片文字识别的结果
                                                     // public Image image;
    private string sss="";
    private Ocr client;                              // 用来调用百度AI接口
    

    // private JObject result; // 接收返回的结果
    private string ApiKey = "G7h0xBIkf4xfR6NE1mfpZvF3";//此处填写自己申请的key
    private string SecretKey = "gKsyBaTKp8GDAeiqG6eNrHkxbbsT4MAN";//此处填写自己申请的key

    private void Awake()
    {
        //网页端身份安全验证失败,我们需要在程序运行时手动添加安全证书,在Awake方法中加入
        System.Net.ServicePointManager.ServerCertificateValidationCallback +=
            delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;           // always accept
            };
        // 此处填写自己申请的key("Api Key", "Secret Key");
        client = new Ocr(ApiKey, SecretKey);
    
        rawImage.enabled = false;
        img_Scan.enabled = false;
    }
    
    private void Update()
    {
        debugInfo.text = infoLog;
        tex_TW.text=sss;
    }
    //通用文字识别
    public void GeneralBasic()
    {
       // var path = Application.dataPath + "/Images/tw03.jpg";
        var path = Application.dataPath + "/Resources/xxocr.jpg";
    
        var image = File.ReadAllBytes(path);
    
        var result = client.GeneralBasic(image);
    
        JsonData jd0 = JsonMapper.ToObject(result.ToString());//json解析json数据
        JsonData jd1 = jd0["words_result"];
    
        foreach (JsonData jd2 in jd1)//json解析数组
        {
            string s31 = jd2["words"].ToString();
            // Debug.Log(s31);//ok
        }
    
        int s2 = (int)jd0["words_result_num"];
        for (int i = 0; i < s2; i++)
        {
            sss = "";
            sss += jd1[i]["words"].ToString();
        }
        debugInfo.text = result.ToString();
    
        Debug.Log("通用文字识别");
    }
    // 高精度图片文字识别..//每天限量50次,超过错误码17;
    public void Accurate()
    {
        var path = Application.dataPath + "/Images/tw22.jpg";//要识别的文字图片=路径+文件名
       // var path = Application.dataPath + "/Resources/tw01.jpg";//要识别的文字图片=路径+文件名
        var image = File.ReadAllBytes(path);//要识别的文字图片
    
        var result = client.Accurate(image);//百度文字识别
        JsonData jd0 = JsonMapper.ToObject(result.ToString());//json解析json数据
        JsonData jd1 = jd0["words_result"];
    
        foreach (JsonData jd2 in jd1)//json解析数组
        {
            string s31 = jd2["words"].ToString();
            // Debug.Log(s31);//ok
        }
    
        int s2 = (int)jd0["words_result_num"];
        for (int i = 0; i < s2; i++)
        {
           // tex_TW.text = "";
            sss += jd1[i]["words"].ToString();
        }
    
        //string s1 = jd0["log_id"].ToString();
        //string s3 = jd0["words_result"].ToString();
    
        //Debug.Log(s1);//ok
        //Debug.Log(s2);//ok
        //Debug.Log(s3);//ok
        Debug.Log(result.ToString());
    
        debugInfo.text = result.ToString();
        Debug.Log("高精度识别");
    }
    
    //通用文字带生僻字识别
    public void GeneralEnhanced()
    {
    var path = Application.dataPath + "/Images/tw23.jpg";
    var image = File.ReadAllBytes(path);
    
    var result = client.GeneralEnhanced(image);
    debugInfo.text = result.ToString();
    Debug.Log("带生僻字识别");
    }
    //高精度识别(带位置信息)
    public  void AccurateWithLocation()
        {
        var path = Application.dataPath + "/Images/tw13.jpg";
        var image = File.ReadAllBytes(path);
    
       var result = client.AccurateWithLocation(image);
        debugInfo.text = result.ToString();
        Debug.Log("高精度识别带位置");
    }
    // 检查获取摄像头设备
    public void GetMicrophoneDevice()
    {
        webCamArray = WebCamTexture.devices;
        if (webCamArray.Length == 0)
        {
            Debug.LogError("找不到摄像头硬件设备!");
            ShowInfoLog("找不到摄像头硬件设备!");
            return;
        }
        else
        {
            if (Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                Debug.Log("摄像头已经就绪,可以录像!");
                ShowInfoLog("摄像头已经就绪,可以开始拍照,录像了!!");
            }
            else
            {
                Debug.Log("摄像头权限被禁止,请获取摄像头权限!");
                ShowInfoLog("摄像头权限被禁止,请获取摄像头权限!");
            }
        }
    }
    //开启摄像头
    public void OpenWebCam()
    {
        GetMicrophoneDevice();//检查摄像头设备
        _WebCamTexture.Play();//开启摄像头
        rawImage.GetComponent<RawImage>().texture = _WebCamTexture;//摄像头纹理渲染在屏幕上
    
        Debug.Log("开启摄像头!");
        ShowInfoLog("开启摄像头!");
    }
    IEnumerator Start()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            webCamArray = WebCamTexture.devices;
            deviceName = webCamArray[index].name;
            //摄像机摄像的区域
            _WebCamTexture = new WebCamTexture(deviceName, 400, 300, -112);
            //_WebCamTexture.Play();
            // Debug.Log("录像头运行中!!");
            //ShowInfoLog("录像头运行中!");
        }
    }
    //暂停
    public void PauseWebCam()
    {
        _WebCamTexture.Pause();//摄像头暂停
    
        Debug.Log("暂停摄像头!");
        ShowInfoLog("暂停摄像头!");
    }
    //停止
    public void StopWebCam()
    {
        _WebCamTexture.Stop();//摄像头停止
        rawImage.GetComponent<RawImage>().texture = null;
    
        Debug.Log("停止摄像头!");
        ShowInfoLog("停止摄像头!");
    }
    //拍照,存贮照片在本地
    public void Photograph()
    {
        StartCoroutine("GetTexture2D");//协程——获取摄像头图像,并把图片保存在本地
        Debug.Log("拍照!");
        ShowInfoLog("拍照!");
    }
    //获取摄像头图像,并把图片保存在本地
    IEnumerator GetTexture2D()
    {
        print(GameObject.Find("CameraTexture").transform.localPosition);//摄像纹理,//必须是Raw Image;改名为CameraTexture,屏幕中摄像头纹理位置
        yield return new WaitForEndOfFrame();
        Texture2D t = new Texture2D(400, 300);//新,实例化一张空白长400,宽400的图片,//摄像头纹理大小
        t.ReadPixels(new Rect(200, 150, 400f, 300f), 0, 0, false);//新空白图片的像素为,这个区域中的像素(摄像头在屏幕中的区域的图像)、
        //参数1:200为摄像头纹理左下角距离屏幕左边的距离;参数2:150为摄像头纹理左下角距离屏幕底部的距离;参数3:400f为摄像头纹理宽度,参数4:300f为摄像头纹理高度,
        t.Apply();//把像素应用在图片
        //把图片数据转换为byte数组
        byte[] byt = t.EncodeToPNG();
        //然后保存为图片
        string strTempTime = System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);//当前时间,把图片命名为当前时间
    
        // System.IO.File.WriteAllBytes(Application.dataPath + "/Resources/" + strTempTime + ".jpg", byt);//把图片保存在本地,Resources文件夹中,名字为当前时间.jpg
        //System.IO.File.WriteAllBytes(Application.persistentDataPath+"/"+strTempTime + ".jpg", byt);//把图片保存在本地,文件夹中,名字为当前时间.jpg
        System.IO.File.WriteAllBytes(Application.dataPath + "/Resources/xxocr.jpg", byt);//把图片保存在本地,Resources文件夹中,名字为当前时间.jpg
    
    
        UnityEditor.AssetDatabase.Refresh();//刷新,使刚创建的图片立刻导入。接下来才可以被使用
    
        //image.material.mainTexture = Resources.Load(strTempTime, typeof(Texture2D)) as Texture2D;//把拍的照片显示出来;
        img_Show.material.mainTexture = Resources.Load("xxocr", typeof(Texture2D)) as Texture2D;//把拍的照片显示出来;//Resources加载不需要后缀
    
        Debug.Log("照片保存在本地!");
        ShowInfoLog("照片保存在本地!");
    }
    //显示日志提示信息
    void ShowInfoLog(string info)
    {
        debugInfo.text = "";
        infoLog += info;
        infoLog += "\r\n";
    }
    //显示扫描UI
    public void ShowUI()
    {
        img_Scan.enabled = true;//扫描框
        rawImage.enabled = true;//摄像机纹理
    }
    //隐藏扫描UI
    public void HideUI()
    {
        img_Scan.enabled = false;//扫描框
        rawImage.enabled = false;//摄像机纹理
    
    }
    //显示UI,开启摄像头,
    public void StartScan()
    {
        ShowUI();//显示UI
        OpenWebCam();//打开摄像头        
    }
    //拍照,识别
    public void  PhotoOCR()
    {
        Photograph();//拍照,并把照片保存在本地
        //Accurate();//百度文字识别//高精度识别,每天限制50次
        GeneralBasic();//百度文字识别;普通识别
       
    
       // HideUI();//隐藏UI
    }
    

    }

    相关文章

      网友评论

          本文标题:OCRIboade

          本文链接:https://www.haomeiwen.com/subject/ikgebxtx.html