> 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/ko/legacy/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할 수 있습니다. 또는 이미지가 다른 곳에 호스팅되어 있다면 URL을 쿼리 문자열의 `image` 매개변수로 전달할 수 있습니다.

#### 경로 매개변수

| 이름          | 유형  | 설명                                                                          |
| ----------- | --- | --------------------------------------------------------------------------- |
| datasetSlug | 문자열 | 데이터셋 이름을 URL에 사용할 수 있는 형태로 바꾼 값입니다. 웹 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: 금지됨 " %}

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

{% endtab %}
{% endtabs %}
