如何在Android Studio中使用Clarifai Java API

时间:2018-04-24 00:30:20

标签: java android api clarifai

我正在制作Android Studio应用,我需要帮助整合Clarifai。我开始根据Clarifai网站上的快速启动指南设置客户端。我的代码看起来像这样:

 public static void main(String[] arg) {

    new ClarifaiBuilder("c719daa395fe42f2a1385ace59592496").buildSync();

    ClarifaiClient client = new ClarifaiBuilder("c719daa395fe42f2a1385ace59592496")
            .client(new OkHttpClient()) // OPTIONAL. Allows customization of OkHttp by the user
            .buildSync();

    client.getDefaultModels().generalModel().predict()
            .withInputs(ClarifaiInput.forImage("https://samples.clarifai.com/metro-north.jpg"))
            .executeSync();

}

据我所知,它是将样本图像带到城北,并预测它是什么。我想知道的是如何在应用程序的屏幕上编写/打印最高结果(或结果列表),以便它可见。

如果有人可以帮我解决这个问题,我将不胜感激:D

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码打印最高结果:

client.getDefaultModels().generalModel().predict()
  .withInputs(ClarifaiInput.forImage("https://samples.clarifai.com/metro-north.jpg"))
            .executeAsync(
                outputs -> System.out.println("First output of this prediction is " + outputs.get(0))
            ),
        code -> System.err.println("Error code: " + code + ". Error msg: " + message),
        e -> { throw new ClarifaiException(e); }
    );

答案 1 :(得分:-1)

基本上你可以这样做:

//Get the results from the api:

 new AsyncTask<Void, Void, ClarifaiResponse<List<ClarifaiOutput<Concept>>>>() {
      @Override protected ClarifaiResponse<List<ClarifaiOutput<Concept>>> doInBackground(Void... params) {
        // The default Clarifai model that identifies concepts in images
        final ConceptModel generalModel = App.get().clarifaiClient().getDefaultModels().generalModel();

        // Use this model to predict, with the image that the user just selected as the input
        return generalModel.predict()
            .withInputs(ClarifaiInput.forImage(ClarifaiImage.of(imageBytes)))
            .executeSync();
      }

      @Override protected void onPostExecute(ClarifaiResponse<List<ClarifaiOutput<Concept>>> response) {
        setBusy(false);
        if (!response.isSuccessful()) {
          showErrorSnackbar(R.string.error_while_contacting_api);
          return;
        }
        final List<ClarifaiOutput<Concept>> predictions = response.get();
        if (predictions.isEmpty()) {
          showErrorSnackbar(R.string.no_results_from_api);
          return;
        }else{

            //Do something with the results or get the first element.
        }

      }

取自this project

相关问题