Unity 接入百度AI人像抠图

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

public class OpenCamera : MonoBehaviour
{

    public Image img;
    private void Start()
    {

        
    }

    public void OPEn()
    {
        Invoke("open", 2);
    }


    public void open()
    {
        Base64ToImg(img, body_seg());
    }

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



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

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

    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;
        //Debug.Log("REsult:" + result);
        return result;
    }

    public string body_seg()
    {
        string token = "24.ad0cd3223538a86613ba068acb99bb73.2592000.1602990697.282335-19410153";
        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.png");
        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();
        Debug.Log(result);
        string newBase64= json(result);
        return newBase64;
    }



    public string json(string str)
    {


        JsonData jd;
        jd = JsonMapper.ToObject(str);
        return jd["foreground"].ToString();

    }

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

 

要在Unity接入百度AI接口,你需要进行以下步骤: 1. 注册百度AI开放平台账号并创建应用,获取AppID、API Key和Secret Key。 2. 下载百度AI SDK for Unity,并将其导入到Unity项目中。 3. 在Unity项目中创建一个脚本,并在其中编写调用百度AI接口的代码。例如,你可以使用语音识别接口,将用户的语音转换成文本。代码示例如下: ``` using Baidu.Aip.Speech; using UnityEngine; public class SpeechRecognition : MonoBehaviour { private const string APP_ID = "你的AppID"; private const string API_KEY = "你的API Key"; private const string SECRET_KEY = "你的Secret Key"; private readonly AudioClip _microphoneClip = Microphone.Start(null, true, 10, 16000); private SpeechRecognizer _speechRecognizer; private void Start() { _speechRecognizer = new SpeechRecognizer(API_KEY, SECRET_KEY); _speechRecognizer.Timeout = 60000; } private void Update() { // 等待录音结束 if (Microphone.IsRecording(null) && Microphone.GetPosition(null) > 0) { return; } // 停止录音 Microphone.End(null); // 调用语音识别接口 var result = _speechRecognizer.Recognize(_microphoneClip.GetData(), "pcm", 16000); if (result != null && result.ErrorCode == 0) { Debug.Log(result.Result[0]); } } } ``` 4. 在Unity中添加麦克风权限,以允许应用访问麦克风。 5. 对于其他的百度AI接口,你可以参考百度AI SDK for Unity中的示例代码,并根据具体需求进行修改。 以上就是在Unity接入百度AI接口的基本步骤。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值