clarifai api with dot net Web api

1 c# asp.net-web-api

我正在使用.net创建一个Web API C#,我想调用clarifaiapi来获取图像标记.

我怎样才能做到这一点?

提前致谢

KWI*_*AMS 5

这是一个更新的答案,向您展示如何将图像从本地计算机发送到Clarifai的API.此示例使用API​​的版本2.如果您尝试使用版本1,则会收到429的状态错误.这是为了鼓励人们使用版本2.这将在https://community.clarifai.com/t/request-was-throttled/402中讨论.

以下示例是一个获取流的方法.此流稍后转换为字节数组并在base 64中编码.此编码数据以JSON格式发送到Clarifai的API.

public void ClarifaiTagging(Stream imageStream)
{
    const string ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
    const string CLARIFAI_API_URL = "https://api.clarifai.com/v2/models/{model}/outputs";

    // Convert the stream to a byte array and convert it to base 64 encoding
    MemoryStream ms = new MemoryStream();
    imageStream.CopyTo(ms);
    string encodedData = Convert.ToBase64String(ms.ToArray());

    using (HttpClient client = new HttpClient())
    {
        // Set the authorization header
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + ACCESS_TOKEN);

        // The JSON to send in the request that contains the encoded image data
        // Read the docs for more information - https://developer.clarifai.com/guide/predict#predict
        HttpContent json = new StringContent(
            "{" +
                "\"inputs\": [" +
                    "{" +
                        "\"data\": {" +
                            "\"image\": {" +
                                "\"base64\": \"" + encodedData + "\"" +
                            "}" +
                       "}" +
                    "}" +
                "]" +
            "}", Encoding.UTF8, "application/json");

        // Send the request to Clarifai and get a response
        var response = client.PostAsync(CLARIFAI_API_URL, json).Result;

        // Check the status code on the response
        if (!response.IsSuccessStatusCode)
        {
            // End here if there was an error
            return null;
        }

        // Get response body
        string body = response.Content.ReadAsStringAsync().Result.ToString();

        Debug.Write(body);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助.

编辑:

要使用Clarifai API的v2标记来自URL的图像,只需使用以下内容.

HttpContent json = new StringContent(
    "{" +
        "\"inputs\": [" +
            "{" +
                "\"data\": {" +
                    "\"image\": {" +
                        "\"url\": \"" + yourUrlHere + "\"" +
                    "}" +
                "}" +
            "}" +
        "]" +
    "}", Encoding.UTF8, "application/json");
Run Code Online (Sandbox Code Playgroud)

有关Clarifai API的完整文档,请访问https://www.clarifai.com/developer/guide/.