码迷,mamicode.com
首页 > Web开发 > 详细

百度HttpV3版本图片识别

时间:2018-10-19 14:03:03      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:control   ice   点击   jpg   ace   turn   crypto   code   base   

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版本图片识别

标签:control   ice   点击   jpg   ace   turn   crypto   code   base   

原文地址:https://www.cnblogs.com/VR-1024/p/9815558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!