clarifai api with dot net Web api



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

我该怎么做?

提前感谢

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

以下示例是一个采用流的方法。该流随后被转换成字节数组并在基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);
    }
}

希望这能有所帮助。

编辑:

要使用Clarifai API的v2从URL标记图像,只需使用以下内容。

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

Clarifai API的完整文档可在https://www.clarifai.com/developer/guide/.

此项目可能对您有用:https://github.com/codingbrent/clarifai-nsfw-detection-csharp/blob/master/httpclartest/Program.cs#L33

长话短说,你必须构建一个网址:

string url = "http://api.clarifai.com/v1/tag/?&url=" + your_image_url + "&access_token=" + your_access_token

您的访问令牌将来自您的客户端ID和客户端机密。然后,您可以运行以下操作来发出GET请求:

WebClient myWebClient = new WebClient()
byte[] myDataBuffer = myWebClient.DownloadData(url);
string download = Encoding.ASCII.GetString(myDataBuffer);

然后,您所要做的就是从那里解析JSON。

最新更新