百度HttpV3版本图片识别

Posted vr-1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度HttpV3版本图片识别相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections;
using System.IO;
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.UI;

public class WebCameraManager : MonoBehaviour
{

    public string DeviceName;
    public Vector2 CameraSize;
    public float CameraFPS;
    //显示出来得Plane
    public GameObject PlaneGameObject;
    //接收返回的图片数据  
    WebCamTexture _webCamera;
    //图片读取
    private string PathTex;
    private Texture2D originalTex;
    //百度得Key
    public static String clientId = "yTFoS5UpTmyPyYd94XO5Ht6l";
    // 百度云中开通对应服务应用的 Secret Key
    public static String clientSecret = "3rKvOLUgCEgYQ8eC5qVnEDMC08B8o5G7";
   //图片对比路劲
    private string Path1=" ";
    private string Path2=" ";
    //提示文本
    public Text ResulText;
    //记录第一次拍照
    private int Number=1;
        /// <summary>
        /// 手动添加安全证书
        /// </summary>
    private void 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
            };
    }

    void Start()
    {
        //本地已经存在得照片
        Path1 = Application.persistentDataPath + "My.jpg";
        StartCoroutine(InitCameraCor());
    }
    /// <summary>
    /// 点击保存按钮
    /// </summary>
    public void ButtonSave()
    {
        if (Number==1)
        {
            byte[] Pho = GetPhotoPixel(_webCamera);
            File.WriteAllBytes(Application.persistentDataPath + "First.jpg", Pho);
            Debug.Log(Pho);
            if (Pho != null)
            {
                //截取得照片
                PathTex = Application.persistentDataPath + "First.jpg";
                //获取路劲给Path2拿去与Path1对比
                Path1 = PathTex;
                FileLoadTexture();
                Number += 1;
                Debug.Log("点击次数"+Number);
            }
            
        }
        else
        {
            Debug.Log("非第一次");
            byte[] Pho = GetPhotoPixel(_webCamera);
            File.WriteAllBytes(Application.persistentDataPath + "Other.jpg", Pho);
            Debug.Log(Pho);
            if (Pho != null)
            {
                //截取得照片
                PathTex = Application.persistentDataPath + "Other.jpg";
                //获取路劲给Path2拿去与Path1对比
                Path2 = PathTex;
                FileLoadTexture();
            }
        }
  
        
    }

    /// <summary>  
    /// 初始化摄像头
    /// </summary>  
    public IEnumerator InitCameraCor()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            DeviceName = devices[1].name;
            _webCamera = new WebCamTexture(DeviceName, (int)CameraSize.x, (int)CameraSize.y, (int)CameraFPS);
            #region MyRegion

                      //Todo 摄像头图片实时显示到面板上
            //PlaneGameObject.GetComponent<Renderer>().material.mainTexture = _webCamera;
            //PlaneGameObject.transform.localScale = new Vector3(1, 1, 1);  

            #endregion
            _webCamera.Play();
        }
    }
    /// <summary>
    /// 获取像素
    /// </summary>  
    private byte[] GetPhotoPixel(WebCamTexture ca)
    {
        Texture2D texture = new Texture2D(ca.width, ca.height);
        int y = 0;
        while (y < texture.height)
        {
            int x = 0;
            while (x < texture.width)
            {
                UnityEngine.Color color = ca.GetPixel(x, y);
                texture.SetPixel(x, y, color);
                ++x;
            }
            ++y;
        }
        texture.Apply();  
        byte[] pngData = GetJpgData(texture);
        return pngData;
    }
    /// <summary>
    /// 控制照片大小
    /// /// </summary>  
    private byte[] GetJpgData(Texture2D te)
    {
        byte[] data = null;
        int quelity = 75;
        while (quelity > 20)
        {
            data = te.EncodeToJPG(quelity);
            int size = data.Length / 1024;
            if (size > 30)
            {
                quelity -= 5;
            }
            else
            {
                break;
            }
        }
        return data;
    }
    /// <summary>
    /// 文件流加载图片
    /// </summary>
    private void FileLoadTexture()
    {
        FileStream fileStream=new FileStream(PathTex,FileMode.Open);
        byte[] buffer=new byte[fileStream.Length];
        fileStream.Read(buffer, 0, buffer.Length);
        fileStream.Close();
        originalTex = new Texture2D(2, 2);
        var iSLoad = originalTex.LoadImage(buffer);
        originalTex.Apply();
        if (!iSLoad)
        {
            Debug.Log("Texture存在但生成Texture失败");
        }
        else
        {
            Debug.Log("加载生成成功");
            //Todo    
            //将本地图片再次赋值Plane用
            if (Number==1)
            {
                Debug.Log("1");
                   PlaneGameObject.GetComponent<Renderer>().material.mainTexture = originalTex;
            }
            else
            {               
            //Todo 对比 
                Debug.Log("对比");
             MatchPho();   
            }
         
        }

    

    }
   /// <summary>
   /// 百度人脸对比
   /// </summary>
    private void MatchPho()
    {
        ResulText.text = "对比";
       Face clicent = new Face(clientId,clientSecret);
        clicent.Timeout = 6000;
        JArray faces = new JArray
        {
            new JObject
            {
                {"image", ReadImg(this.Path1)},
                {"image_type", "BASE64"},
                {"face_type", "LIVE"},
                {"quality_control", "LOW"},
                {"liveness_control", "NONE"},
            },
            new JObject
            {
                {"image", ReadImg(this.Path2)},
                {"image_type", "BASE64"},
                {"face_type", "LIVE"},
                {"quality_control", "LOW"},
                {"liveness_control", "NONE"},
            }
        };

        // 调用人脸比对,可能会抛出网络等异常使用try/catch捕获
        try
        {
            JObject result = clicent.Match(faces);
            Debug.Log(result);
            ResulText.text = "匹配结果:"+result;
        }
        catch (Exception e)
        {
           Debug.Log(e);
            ResulText.text = e.ToString();
            throw;
        }
    }
    public string ReadImg(string img)
    {
        return Convert.ToBase64String(File.ReadAllBytes(img));
    }
}

调用摄像头拍照,照片储存,调用百度HttpV3.5API进行图片识别对比。得到对比后的json数据内容。解析即可!

以上是关于百度HttpV3版本图片识别的主要内容,如果未能解决你的问题,请参考以下文章

Python|基于百度API五行代码实现OCR文字高识别率

python实现百度OCR图片识别

Python实战,截图识别文字,过万使用量版本?

Python实战,截图识别文字,过万使用量版本?

C# 10分钟完成百度图片提取文字(文字识别)——入门篇

使用百度AI平台图像识别-人脸动漫化与黑白图片上色(PHP)