如何将本地图像文件上传到Clarifai API

问题描述

我正在尝试使用clarifai中的食品分类API,但示例使用的是公开托管的图片。是否可以通过本地文件夹中的图像使用API​​?我正在使用nodejs。

const Clarifai = require('clarifai');
const app = new Clarifai.App({
 apiKey: 'apikey'

// example code from Clarifai Docs
app.models.predict("bd367be194cf45149e75f01d59f77ba7","https://samples.clarifai.com/food.jpg").then(
    function(response) {
      // do something with response
    },function(err) {
      // there was an error
    }
  );

我获得示例API请求的链接https://www.clarifai.com/models/food-image-recognition-model-bd367be194cf45149e75f01d59f77ba7

解决方法

您需要提供字节流而不是URL才能从本地文件上传。例如:

// Insert here the initialization code as outlined on this page:
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions

const fs = require("fs");
const imageBytes = fs.readFileSync("{YOUR_IMAGE_LOCATION}");

stub.PostInputs(
    {
        inputs: [{data: {image: {base64: imageBytes}}}]
    },metadata,(err,response) => {
        if (err) {
            throw new Error(err);
        }

        if (response.status.code !== 10000) {
            throw new Error("Post inputs failed,status: " + response.status.description);
        }
    }
);

此代码将读取本地图像的base64字节并将其发送(用base64替换url)。这是使用基于grpc的nodejs API。 https://docs.clarifai.com/api-guide/data/create-get-update-delete中包含一些其他信息,包括此示例。