Unity 百度人像分割

SDK和在线API都实现了一下

ID 和 Key自己替换一下

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using UnityEngine;
using LitJson;
using UnityEngine.UI;
using System.Text.RegularExpressions;

namespace NAMESPACE 
{
	public class test : MonoBehaviour
	{

        public Image img;
        private void Start()
        {
            Base64ToImg(img, body_seg());
            Base64ToImg(img,BodySegDemo());
        }

        static string APP_ID = "";
        static string API_KEY = "";
        static string SECRET_KEY = "";

        Baidu.Aip.BodyAnalysis.Body client = new Baidu.Aip.BodyAnalysis.Body(API_KEY, SECRET_KEY);
       
        //dll
        public string BodySegDemo()
        {
            client.Timeout = 60000;  // 修改超时时间
            var image = File.ReadAllBytes(Application.streamingAssetsPath + "/2.jpg");
            // 调用人像分割,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.BodySeg(image);
            // 如果有可选参数
            var options = new Dictionary<string, object>{
            {"type", "foreground"}
        };
            // 带参数调用人像分割
            result = client.BodySeg(image, options);

            JsonData data = JsonMapper.ToObject(result.ToString());
            string byte64 = data["foreground"].ToJson();
            string newStr = byte64.Substring(1, byte64.Length - 2);
            return newStr;
        }



        // 人像分割 POST
        public static String TOKEN = "";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "lRbQ8CAh8GpVYdvTAw2uc55E";
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "fmylzATzGHp0APtFQHsdNVIL6gR7tLlO";

        public 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;
            return result;
        }

        public string body_seg()
        {
            string token = getAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = getFileBase64(Application.streamingAssetsPath+"/1.jpg");
            String str = "image=" + HttpUtility.UrlEncode(base64);
            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;
        }

        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;
        }

        public void Base64ToImg(Image imgComponent, string base64)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            Texture2D tex2D = new Texture2D(100, 100);
            tex2D.LoadImage(bytes);
            Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
            imgComponent.sprite = s;
            Resources.UnloadUnusedAssets();
        }
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值