# 분류

{% tabs %}
{% tab title="Python" %}
**로컬 및 호스팅 이미지에서 추론**

의존성을 설치하려면, `pip install inference-sdk`.

```python
from inference_sdk import InferenceHTTPClient

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

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

{% endtab %}

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

다음을 사용합니다 [axios](https://github.com/axios/axios) 를 사용하므로 먼저 다음을 실행하세요. `npm install axios` 를 실행하여 의존성을 설치하세요.

**로컬 이미지에서 추론하기**

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

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

axios({
    method: "POST",
    url: "https://classify.roboflow.com/your-model/42",
    params: {
        api_key: "YOUR_KEY"
    },
    data: image,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
})
.then(function(response) {
    console.log(response.data);
})
.catch(function(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, Model, Model Version으로 Inference Server 요청 초기화
var request = URLRequest(url: URL(string: "https://classify.roboflow.com/your-model/your-model-version?api_key=YOUR_APIKEY&name=YOUR_IMAGE.jpg")!,timeoutInterval: Double.infinity)
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
    }
    
    // 응답 문자열을 Dictionary로 변환
    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 %}

## Response Object Formats

{% tabs %}
{% tab title="Single-Label Classification" %}
**Single-Label Classification**

호스팅된 API 추론 경로는 다음을 반환합니다. `JSON` 예측 배열을 포함하는 객체를 반환합니다. 각 예측에는 다음 속성이 있습니다:

* `time` = 이미지를 처리하고 예측을 반환하는 데 걸리는 총 시간(초)
* `image` = 이미지에 대한 정보를 담고 있는 객체 `width` 및 `height`
  * `width` 예측된 이미지의 높이
  * `height` = 예측된 이미지의 높이
* `predictions` = 예측에 대한 모든 예측 클래스와 해당 confidence 값의 모음
  * `class` = classification의 레이블
  * `confidence` = 이미지에 감지된 classification의 객체가 포함되어 있다는 model의 confidence
* `top` = 가장 높은 confidence의 예측 클래스
* `confidence` = 가장 높은 예측 confidence 점수
* `image_path` = 예측된 이미지의 경로
* `prediction_type` = inference를 수행하는 데 사용된 model 유형, `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="Multi-Label Classification" %}
**Multi-Label Classification**

호스팅된 API 추론 경로는 다음을 반환합니다. `JSON` 예측 배열을 포함하는 객체를 반환합니다. 각 예측에는 다음 속성이 있습니다:

* `time` = 이미지를 처리하고 예측을 반환하는 데 걸리는 총 시간(초)
* `image` = 이미지에 대한 정보를 담고 있는 객체 `width` 및 `height`
  * `width` 예측된 이미지의 높이
  * `height` = 예측된 이미지의 높이
* `predictions` = 예측에 대한 모든 예측 클래스와 해당 confidence 값의 모음
  * `class` = classification의 레이블
  * `confidence` = 이미지에 감지된 classification의 객체가 포함되어 있다는 model의 confidence
* `predicted_classes` = model 예측에서 반환된 모든 classification(레이블/클래스) 목록을 포함하는 배열
* `image_path` = 예측된 이미지의 경로
* `prediction_type` = inference를 수행하는 데 사용된 model 유형, `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 Reference

## Inference API 사용하기

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

base64로 인코딩된 이미지를 모델 엔드포인트에 직접 POST할 수 있습니다. 또는 이미지가 이미 다른 곳에 호스팅되어 있다면 쿼리 문자열의 `image` 매개변수로 URL을 전달할 수도 있습니다.

#### 경로 매개변수

| Name        | 유형     | 설명                                                                     |
| ----------- | ------ | ---------------------------------------------------------------------- |
| datasetSlug | string | dataset 이름의 URL-safe 버전입니다. 메인 project view의 URL을 보면 웹 UI에서 찾을 수 있습니다. |
|             | string | dataset의 버전을 식별하는 버전 번호입니다.                                            |

#### 쿼리 매개변수

| Name     | 유형     | 설명                                      |
| -------- | ------ | --------------------------------------- |
| api\_key | string | API 키 (workspace API settings 페이지에서 획득) |

{% 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: 금지됨 " %}

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

{% endtab %}
{% endtabs %}
