> 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("Request failed with status " + 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リファレンス

## 推論APIの使用

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

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

#### パスパラメーター

| 名前          | 型   | 説明                                                                   |
| ----------- | --- | -------------------------------------------------------------------- |
| datasetSlug | 文字列 | データセット名をURLで安全に使用できる形式にしたものです。Web UIでは、プロジェクトのメイン画面に表示されるURLで確認できます。 |
|             | 文字列 | データセットのバージョンを識別する番号です。                                               |

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

| 名前       | 型   | 説明                          |
| -------- | --- | --------------------------- |
| 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 %}
