> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/deployment/ja/regash/legacy-serverless/classification.md).

# 分類

Roboflow でホストされている分類モデルに対して推論を実行します。

{% tabs %}
{% tab title="Python" %}
**ローカル画像とホスト画像で推論**

依存関係をインストールするには、 `pip install inference-sdk`.

```python
from inference_sdk import InferenceHTTPClient, InferenceConfiguration

CLIENT = InferenceHTTPClient(
    api_url="https://classify.roboflow.com",
    api_key="API_KEY"
).configure(InferenceConfiguration(api_key_transport="header"))

result = CLIENT.infer(your_image.jpg, model_id="vehicle-classification-eapcd/2")
```

{% endtab %}

{% tab title="JavaScript" %}
**Node.js**

これらの例では組み込みの `fetch` API を使用します。Node.js 18 以降および最新のブラウザで動作するため、インストールする依存関係はありません。

**ローカル画像で推論する**

```javascript
const fs = require("fs");

const image = fs.readFileSync("YOUR_IMAGE.jpg", {
    encoding: "base64"
});

fetch("https://classify.roboflow.com/your-model/42", {
    method: "POST",
    headers: {
        "Authorization": "Bearer YOUR_KEY",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: image
})
    .then((response) => {
        if (!response.ok) throw new Error("ステータス " + response.status + " でリクエストに失敗しました");
        return response.json();
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log(error.message);
    });
```

{% endtab %}

{% tab title="Swift" %}
**base64を使用してローカル画像をアップロードする**

```swift
import UIKit

// 画像を読み込み、Base64 に変換
let image = UIImage(named: "your-image-path") // アップロードする画像へのパス 例: image.jpg
let imageData = image?.jpegData(compressionQuality: 1)
let fileContent = imageData?.base64EncodedString()
let postData = fileContent!.data(using: .utf8)

// API_KEY、モデル、モデルバージョンを使って推論サーバー要求を初期化
var request = URLRequest(url: URL(string: "https://classify.roboflow.com/your-model/your-model-version?name=YOUR_IMAGE.jpg")!,timeoutInterval: Double.infinity)
request.setValue("Bearer YOUR_APIKEY", forHTTPHeaderField: "Authorization")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData

// POST リクエストを実行
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
    
    // 応答を文字列に解析
    guard let data = data else {
        print(String(describing: error))
        return
    }
    
    // 応答文字列を辞書に変換
    do {
        let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
    } catch {
        print(error.localizedDescription)
    }
    
    // 文字列応答を出力
    print(String(data: data, encoding: .utf8)!)
}).resume()
```

{% endtab %}
{% endtabs %}

## レスポンスオブジェクトの形式

{% tabs %}
{% tab title="単一ラベル分類" %}
**単一ラベル分類**

ホスト型 API の推論ルートは `JSON` 予測の配列を含むオブジェクトを返します。各予測には次のプロパティがあります:

* `time` = 画像を処理して予測を返すまでの合計時間（秒）
* `image` = 画像に関する情報を保持するオブジェクト `width` および `height`
  * `width` 予測画像の高さ
  * `height` = 予測画像の高さ
* `predictions` = 予測に対するすべての予測クラスと、それに関連付けられた信頼度値のコレクション
  * `class` = 分類のラベル
  * `confidence` = 画像に検出された分類の対象物が含まれているとモデルが信頼する度合い
* `top` = 最も高い信頼度を持つ予測クラス
* `confidence` = 予測された最高信頼度スコア
* `image_path` = 予測画像のパス
* `prediction_type` = 推論の実行に使用されたモデルタイプ、 `ClassificationModel` この場合

{% code overflow="wrap" %}

```json
// JSON オブジェクトの例
{
  "time": 0.19064618100037478,
  "image": {
    "width": 210,
    "height": 113
  },
  "predictions": [
    {
      "class": "real-image",
      "confidence": 0.7149
    },
    {
      "class": "illustration",
      "confidence": 0.2851
    }
  ],
  "top": "real-image",
  "confidence": 0.7149,
  "image_path": "/cropped-images-1.jpg",
  "prediction_type": "ClassificationModel"
}
```

{% endcode %}
{% endtab %}

{% tab title="マルチラベル分類" %}
**マルチラベル分類**

ホスト型 API の推論ルートは `JSON` 予測の配列を含むオブジェクトを返します。各予測には次のプロパティがあります:

* `time` = 画像を処理して予測を返すまでの合計時間（秒）
* `image` = 画像に関する情報を保持するオブジェクト `width` および `height`
  * `width` 予測画像の高さ
  * `height` = 予測画像の高さ
* `predictions` = 予測に対するすべての予測クラスと、それに関連付けられた信頼度値のコレクション
  * `class` = 分類のラベル
  * `confidence` = 画像に検出された分類の対象物が含まれているとモデルが信頼する度合い
* `predicted_classes` = モデル予測で返されるすべての分類（ラベル/クラス）の一覧を含む配列
* `image_path` = 予測画像のパス
* `prediction_type` = 推論の実行に使用されたモデルタイプ、 `ClassificationModel` この場合

<pre class="language-json" data-overflow="wrap"><code class="lang-json"><strong>// JSON オブジェクトの例
</strong>{
  "time": 0.19291414400004214,
  "image": {
    "width": 113,
    "height": 210
  },
  "predictions": {
    "dent": {
      "confidence": 0.5253503322601318
    },
    "severe": {
      "confidence": 0.5804202556610107
    }
  },
  "predicted_classes": [
    "dent",
    "severe"
  ],
  "image_path": "/car-model-343.jpg",
  "prediction_type": "ClassificationModel"
}
</code></pre>

{% endtab %}
{% endtabs %}

## API リファレンス

## Inference API の使用

<mark style="color:緑;">`POST`</mark> `https://classify.roboflow.com/:datasetSlug/:versionNumber`

base64 エンコードされた画像をモデルエンドポイントに直接 POST できます。あるいは、URL を次の `image` パラメータとしてクエリ文字列に渡せます。画像がすでに別の場所でホストされている場合。

#### パスパラメータ

| 名前          | 型   | 説明                                                      |
| ----------- | --- | ------------------------------------------------------- |
| datasetSlug | 文字列 | データセット名のURL安全版です。メインのプロジェクトビューのURLを見ることで、Web UIで確認できます。 |
|             | 文字列 | データセットのバージョンを識別するバージョン番号。                               |

#### クエリパラメータ

| 名前       | 型   | 説明                                 |
| -------- | --- | ---------------------------------- |
| api\_key | 文字列 | あなたの API キー（ワークスペースの API 設定ページで取得） |

{% tabs %}
{% tab title="200: OK " %}

```json
{
   "predictions":{
      "bird":{
         "confidence":0.5282308459281921
      },
      "cat":{
         "confidence":0.5069406032562256
      },
      "dog":{
         "confidence":0.49514248967170715
      }
   },
   "predicted_classes":[
      "bird",
      "cat"
   ]
}
```

{% endtab %}

{% tab title="403: Forbidden " %}

```json
{
   "message":"Forbidden"
}j
```

{% endtab %}
{% endtabs %}
