# Object Detection

Roboflow Hosted API を使用して object detection の推論を実行する方法はいくつかあります。さまざまな SDK のいずれかを使うか、ホストされたエンドポイントに REST リクエストを送信できます。

{% tabs %}
{% tab title="Python" %}
依存関係をインストールするには、 `pip install inference-sdk`.

```python
# inference-sdk をインポート
from inference_sdk import InferenceHTTPClient

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

result = CLIENT.infer(your_image.jpg, model_id="football-players-detection-3zvbc/12")
```

{% endtab %}

{% tab title="cURL" %}
**Linux または MacOS**

というローカルファイルの JSON 予測を取得します `YOUR_IMAGE.jpg`:

```bash
base64 YOUR_IMAGE.jpg | curl -d @- \\
"https://serverless.roboflow.com/your-model/42?api_key=YOUR_KEY"
```

Web 上の別の場所でホストされている画像を、その URL 経由で推論する場合（ [URL エンコードするのを忘れずに](https://www.urlencoder.org/)):

```bash
curl -X POST "https://serverless.roboflow.com/your-model/42?\
api_key=YOUR_KEY&\
image=https%3A%2F%2Fi.imgur.com%2FPEEvqPN.png"
```

**Windows**

インストールする必要があります [Windows 用 curl](https://curl.se/windows/) および [Windows 用 GNU の base64 ツール](http://gnuwin32.sourceforge.net/packages/coreutils.htm)。これを行う最も簡単な方法は、 [Git for Windows インストーラー](https://git-scm.com/downloads) を使用することです。これには次のものも含まれます `curl` および `base64` インストール中に「Use Git and optional Unix tools from the Command Prompt」を選択すると、コマンドラインツールが利用できます。

その後は、上記と同じコマンドを使用できます。
{% endtab %}

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

この例では [axios](https://github.com/axios/axios) を使って POST リクエストを実行するので、まず次を実行してください `npm install axios` 依存関係をインストールするために。

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

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

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

axios({
    method: "POST",
    url: "https://serverless.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);
});
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

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

axios({
    method: "POST",
    url: "https://serverless.roboflow.com/your-model/42",
    params: {
        api_key: "YOUR_KEY",
        image: "https://i.imgur.com/PEEvqPN.png"
    }
})
.then(function(response) {
    console.log(response.data);
})
.catch(function(error) {
    console.log(error.message);
});
```

**Web**

で利用できるリアルタイムのオンデバイス推論があります `roboflow.js`； [こちらのドキュメントを参照してください](/roboflow/roboflow-jp/deploy/sdks/web-browser.md).
{% endtab %}

{% tab title="Swift/iOS" %}
**Swift**

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

```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://serverless.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()
```

**Objective C**

[Objective-C のスニペットをリクエストするにはここをクリックしてください。](https://app.roboflow.com/request/snippet.inference-objc)
{% endtab %}

{% tab title="Android" %}
**Kotlin**

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

```kotlin
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.*

fun main() {
    // 画像のパスを取得
    val filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg"
    val file = File(filePath)

    // Base64 でエンコード
    val encodedFile: String
    val fileInputStreamReader = FileInputStream(file)
    val bytes = ByteArray(file.length().toInt())
    fileInputStreamReader.read(bytes)
    encodedFile = String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII)
    val API_KEY = "" // API キー
    val MODEL_ENDPOINT = "dataset/v" // モデルのエンドポイントを設定（Dataset URL にあります）

    // URL を構築
    val uploadURL ="https://serverless.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&name=YOUR_IMAGE.jpg";

    // HTTP リクエスト
    var connection: HttpURLConnection? = null
    try {
        // URL への接続を設定
        val url = URL(uploadURL)
        connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded")
        connection.setRequestProperty("Content-Length",
                Integer.toString(encodedFile.toByteArray().size))
        connection.setRequestProperty("Content-Language", "en-US")
        connection.useCaches = false
        connection.doOutput = true

        // リクエストを送信
        val wr = DataOutputStream(
                connection.outputStream)
        wr.writeBytes(encodedFile)
        wr.close()

        // レスポンスを取得
        val stream = connection.inputStream
        val reader = BufferedReader(InputStreamReader(stream))
        var line: String?
        while (reader.readLine().also { line = it } != null) {
            println(line)
        }
        reader.close()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        connection?.disconnect()
    }
}
main()
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```kotlin
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder

fun main() {
    val imageURL = "https://i.imgur.com/PEEvqPN.png" // 画像 URL を置き換えてください
    val API_KEY = "" // API キー
    val MODEL_ENDPOINT = "dataset/v" // モデルのエンドポイントを設定

    // アップロード URL
    val uploadURL = "https://serverless.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image=" + URLEncoder.encode(imageURL, "utf-8");

    // HTTP リクエスト
    var connection: HttpURLConnection? = null
    try {
        // URL への接続を設定
        val url = URL(uploadURL)
        connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
        connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.toByteArray().size))
        connection.setRequestProperty("Content-Language", "en-US")
        connection.useCaches = false
        connection.doOutput = true

        // リクエストを送信
        val wr = DataOutputStream(connection.outputStream)
        wr.writeBytes(uploadURL)
        wr.close()

        // レスポンスを取得
        val stream = URL(uploadURL).openStream()
        val reader = BufferedReader(InputStreamReader(stream))
        var line: String?
        while (reader.readLine().also { line = it } != null) {
            println(line)
        }
        reader.close()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        connection?.disconnect()
    }
}

main()
```

**Java**

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

```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class InferenceLocal {
    public static void main(String[] args) throws IOException {
        // 画像のパスを取得
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg";
        File file = new File(filePath);

        // Base64 でエンコード
        String encodedFile;
        FileInputStream fileInputStreamReader = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fileInputStreamReader.read(bytes);
        encodedFile = new String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII);

        String API_KEY = ""; // API キー
        String MODEL_ENDPOINT = "dataset/v"; // モデルのエンドポイント

        // URL を構築
        String uploadURL = "https://serverless.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY
                + "&name=YOUR_IMAGE.jpg";

        // HTTP リクエスト
        HttpURLConnection connection = null;
        try {
            // URL への接続を設定
            URL url = new URL(uploadURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", Integer.toString(encodedFile.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoOutput(true);

            // リクエストを送信
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(encodedFile);
            wr.close();

            // レスポンスを取得
            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }

}
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class InferenceHosted {
    public static void main(String[] args) {
        String imageURL = "https://i.imgur.com/PEEvqPN.png"; // 画像 URL を置き換えてください
        String API_KEY = ""; // API キー
        String MODEL_ENDPOINT = "dataset/v"; // モデルのエンドポイント

        // アップロード URL
        String uploadURL = "https://serverless.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image="
                + URLEncoder.encode(imageURL, StandardCharsets.UTF_8);

        // HTTP リクエスト
        HttpURLConnection connection = null;
        try {
            // URL への接続を設定
            URL url = new URL(uploadURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoOutput(true);

            // リクエストを送信
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(uploadURL);
            wr.close();

            // レスポンスを取得
            InputStream stream = new URL(uploadURL).openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
```

{% endtab %}

{% tab title="Ruby" %}
**Gemfile**

{% code title="Gemfile" %}

```ruby
source "https://rubygems.org"

gem "httparty", "~> 0.18.1"
gem "base64", "~> 0.1.0"
gem "cgi", "~> 0.2.1"
```

{% endcode %}

**Gemfile.lock**

{% code title="Gemfile.lock" %}

```ruby
GEM
  remote: https://rubygems.org/
  specs:
    base64 (0.1.0)
    cgi (0.2.1)
    httparty (0.18.1)
      mime-types (~> 3.0)
      multi_xml (>= 0.5.2)
    mime-types (3.3.1)
      mime-types-data (~> 3.2015)
    mime-types-data (3.2021.0225)
    multi_xml (0.6.0)

PLATFORMS
  x64-mingw32
  x86_64-linux

DEPENDENCIES
  base64 (~> 0.1.0)
  cgi (~> 0.2.1)
  httparty (~> 0.18.1)

BUNDLED WITH
   2.2.15
```

{% endcode %}

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

```ruby
require 'base64'
require 'httparty'

encoded = Base64.encode64(File.open("YOUR_IMAGE.jpg", "rb").read)
model_endpoint = "dataset/v" # モデルのエンドポイントを設定
api_key = "" # API キーをここに入力

params = "?api_key=" + api_key
+ "&name=YOUR_IMAGE.jpg"

response = HTTParty.post(
    "https://serverless.roboflow.com/" + model_endpoint + params,
    body: encoded, 
    headers: {
    'Content-Type' => 'application/x-www-form-urlencoded',
    'charset' => 'utf-8'
  })

  puts response

 
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```ruby
require 'httparty'
require 'cgi'

model_endpoint = "dataset/v" # モデルのエンドポイントを設定
api_key = "" # API キーをここに入力
img_url = "https://i.imgur.com/PEEvqPN.png" # URL を構築

img_url = CGI::escape(img_url)

params =  "?api_key=" + api_key + "&image=" + img_url

response = HTTParty.post(
    "https://serverless.roboflow.com/" + model_endpoint + params,
    headers: {
    'Content-Type' => 'application/x-www-form-urlencoded',
    'charset' => 'utf-8'
  })

puts response
```

{% endtab %}

{% tab title="PHP" %}
**ローカル画像で推論する**

```php
<?php

// 画像を Base64 でエンコード
$data = base64_encode(file_get_contents("YOUR_IMAGE.jpg"));

$api_key = ""; // API キーを設定
$model_endpoint = "dataset/v"; // モデルのエンドポイントを設定（Dataset URL にあります）

// HTTP リクエスト用 URL
$url = "https://serverless.roboflow.com/" . $model_endpoint
. "?api_key=" . $api_key
. "&name=YOUR_IMAGE.jpg";

// HTTP リクエストを設定 + 送信
$options = array(
  'http' => array (
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => $data
  ));

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```php
<?php

$api_key = ""; // API キーを設定
$model_endpoint = "dataset/v"; // モデルのエンドポイントを設定（Dataset URL にあります）
$img_url = "https://i.imgur.com/PEEvqPN.png";

// HTTP リクエスト用 URL
$url =  "https://serverless.roboflow.com/" . $model_endpoint
. "?api_key=" . $api_key
. "&image=" . urlencode($img_url);

// HTTP リクエストを設定 + 送信
$options = array(
  'http' => array (
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST'
  ));

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
```

{% endtab %}

{% tab title="Go" %}
**ローカル画像で推論する**

```go
package main

import (
    "bufio"
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "os"
	"net/http"
	"strings"
)

func main() {
	api_key := ""  // API キー
	model_endpoint := "dataset/v" // モデルのエンドポイントを設定

    // ディスク上のファイルを開く。
    f, _ := os.Open("YOUR_IMAGE.jpg")

    // JPG 全体を byte slice に読み込む。
    reader := bufio.NewReader(f)
    content, _ := ioutil.ReadAll(reader)

    // base64 としてエンコード。
    data := base64.StdEncoding.EncodeToString(content)
	uploadURL := "https://serverless.roboflow.com/" + model_endpoint + "?api_key=" + api_key + "&name=YOUR_IMAGE.jpg"

	req, _ := http.NewRequest("POST", uploadURL, strings.NewReader(data))
    req.Header.Set("Accept", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

   	bytes, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(bytes))

}
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```go
package main

import (
    "fmt"
	"net/http"
	"net/url"
  "io/ioutil"
)

func main() {
	api_key := ""  // API キー
	model_endpoint := "dataset/v" // モデルのエンドポイントを設定
	img_url := "https://i.ibb.co/jzr27x0/YOUR-IMAGE.jpg"


	uploadURL := "https://serverless.roboflow.com/" + model_endpoint + "?api_key=" + api_key + "&image=" + url.QueryEscape(img_url)

	req, _ := http.NewRequest("POST", uploadURL, nil)
    req.Header.Set("Accept", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

   	bytes, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(bytes))


}
```

{% endtab %}

{% tab title=".NET" %}
**ローカル画像で推論する**

```csharp
using System;
using System.IO;
using System.Net;
using System.Text;

namespace InferenceLocal
{
    class InferenceLocal
    {

        static void Main(string[] args)
        {
            byte[] imageArray = System.IO.File.ReadAllBytes(@"YOUR_IMAGE.jpg");
            string encoded = Convert.ToBase64String(imageArray);
            byte[] data = Encoding.ASCII.GetBytes(encoded);
            string API_KEY = ""; // API キー
            string MODEL_ENDPOINT = "dataset/v"; // モデルのエンドポイントを設定

            // URL を構築
            string uploadURL =
                    "https://serverless.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY
                + "&name=YOUR_IMAGE.jpg";

            // サービスリクエスト設定
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // リクエストを設定
            WebRequest request = WebRequest.Create(uploadURL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            // データを書き込む
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            // レスポンスを取得
            string responseContent = null;
            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader sr99 = new StreamReader(stream))
                    {
                        responseContent = sr99.ReadToEnd();
                    }
                }
            }

            Console.WriteLine(responseContent);

        }
    }
}
```

**URL 経由で Web 上の別の場所にホストされている画像で推論する**

```csharp
using System;
using System.IO;
using System.Net;
using System.Web;

namespace InferenceHosted
{
    class InferenceHosted
    {
        static void Main(string[] args)
        {
            string API_KEY = ""; // API キー
            string imageURL = "https://i.ibb.co/jzr27x0/YOUR-IMAGE.jpg";
            string MODEL_ENDPOINT = "dataset/v"; // モデルのエンドポイントを設定

            // URL を構築
            string uploadURL =
                    "https://serverless.roboflow.com/" + MODEL_ENDPOINT
                    + "?api_key=" + API_KEY
                    + "&image=" + HttpUtility.UrlEncode(imageURL);

            // Service Point 設定
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // HTTP リクエストを設定
            WebRequest request = WebRequest.Create(uploadURL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = 0;

            // レスポンスを取得
            string responseContent = null;
            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader sr99 = new StreamReader(stream))
                    {
                        responseContent = sr99.ReadToEnd();
                    }
                }
            }

            Console.WriteLine(responseContent);

        }
    }
}
```

{% endtab %}

{% tab title="その他" %}
{% hint style="info" %}
AI 搭載チャットボットの Lenny に、コードサンプルを作ってもらうよう頼んでみてください！
{% endhint %}
{% endtab %}
{% endtabs %}

## API リファレンス

### URL

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

<table><thead><tr><th width="157">名前</th><th width="101">タイプ</th><th>説明</th></tr></thead><tbody><tr><td>projectId</td><td>string</td><td>データセット名の URL 安全なバージョンです。トレーニング後に、データセットの各 version の train results セクションにあるメインの project view の URL を確認するか、「Get curl command」ボタンをクリックすると、web UI で見つけられます。</td></tr><tr><td>version</td><td>number</td><td>データセットの version を識別するバージョン番号</td></tr></tbody></table>

{% hint style="info" %}
project ID と version number の取得方法はこちら [こちら](https://docs.roboflow.com/api-reference/workspace-and-project-ids#how-to-retrieve-a-project-id-and-version-number).
{% endhint %}

REST リクエストを介して Serverless Hosted API に画像を送信する方法は 2 つあります。

* を添付する `base64` エンコード済み画像を `POST` リクエスト本文に
* 画像ファイルの URL を `image` URL クエリ
  * 例: `https://serverless.roboflow.com/:datasetSlug/:versionNumber?image=https://imageurl.com`

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

<table><thead><tr><th width="120">名前</th><th width="106">タイプ</th><th>説明</th></tr></thead><tbody><tr><td>image</td><td>string</td><td>追加する画像の URL。画像が別の場所でホストされている場合に使用します。（リクエスト本文に base64 エンコード済み画像を POST しない場合に必要です。）<br><br><strong>注:</strong> URL エンコードするのを忘れないでください。</td></tr><tr><td>classes</td><td>string</td><td>予測を特定のクラスのみに制限します。カンマ区切りの文字列で指定してください。<br><br><strong>例:</strong> dog,cat<br><br><strong>デフォルト:</strong> なし（すべてのクラスを表示）</td></tr><tr><td>overlap</td><td>number</td><td><p>同じクラスの bounding box 予測が、1 つの box に統合される前に重なりを許容できる最大割合（0〜100 の尺度）。</p><p><strong>デフォルト:</strong> 30</p><p>このパラメータは RF-DETR モデルには影響しません。</p></td></tr><tr><td>confidence</td><td>number</td><td><p>返される予測のしきい値（0〜100 の尺度）。数値が低いほど、より多くの予測が返されます。数値が高いほど、確信度の高い予測が少なく返されます。</p><p><strong>デフォルト:</strong> 40</p></td></tr><tr><td>stroke</td><td>number</td><td><p>予測の周囲に表示される bounding box の太さ（ピクセル単位）（ <code>format</code> です <code>image</code>).</p><p><strong>デフォルト:</strong> 1</p></td></tr><tr><td>ラベル</td><td>boolean</td><td><p>予測結果にテキストラベルを表示するかどうか（これは次の場合にのみ有効です <code>format</code> です <code>image</code>).</p><p><strong>デフォルト:</strong> false</p></td></tr><tr><td>format</td><td>string</td><td><p><strong>オプション:</strong></p><ul><li><strong>json:</strong> JSON の予測配列を返します。（response format タブを参照）。</li><li><strong>image:</strong> 注釈付きの予測結果を含む画像を、バイナリ blob として返します。 <code>Content-Type</code> は <code>image/jpeg</code>.</li></ul><p><strong>Default</strong>: <code>json</code></p></td></tr><tr><td>api_key</td><td>string</td><td>あなたの API key（workspace の API settings ページで取得できます）</td></tr></tbody></table>

### Request Body

<table><thead><tr><th width="104">タイプ</th><th>説明</th></tr></thead><tbody><tr><td>string</td><td>base64 エンコードされた画像。（クエリパラメータで image URL を渡さない場合は必須です）。</td></tr></tbody></table>

content type は `application/x-www-form-urlencoded` で、文字列の body を指定してください。

## Response Format

ホストされた API の inference endpoint は、ほとんどの SDK と同様に、 `JSON` オブジェクトを返し、その中に予測の配列が含まれます。各 prediction には次のプロパティがあります:

* `x` = 検出されたオブジェクトの水平方向の中心点
* `y` = 検出されたオブジェクトの垂直方向の中心点
* `width` = bounding box の幅
* `height` = bounding box の高さ
* `class` = 検出されたオブジェクトの class ラベル
* `confidence` = 検出されたオブジェクトに正しいラベルと位置座標が付いているという model の confidence

REST API からのレスポンスオブジェクトの例はこちらです:

```json
{
    "predictions": [
        {
            "x": 189.5,
            "y": 100,
            "width": 163,
            "height": 186,
            "class": "helmet",
            "confidence": 0.544
        }
    ],
    "image": {
        "width": 2048,
        "height": 1371
    }
}
```

この `image` 属性には、inference に送信された画像の高さと幅が含まれます。bounding box の計算にこれらの値を使用する必要がある場合があります。

## Inference API の JSON 出力から Box を描画する

bounding box を描画するための framework や package は、位置指定の形式が異なる場合があります。レスポンスの `JSON` オブジェクトのプロパティがあれば、次のルールの組み合わせを使って常に bounding box を描画できます:

* 中心点は常に（`x`,`y`)
* 角の点 `(x1, y1)` および `(x2, y2)` は次の方法で求められます:
  * `x1` = `x - (width/2)`
  * `y1` = `y - (height/2)`
  * `x2` = `x + (width/2)`
  * `y2` = `y + (height/2)`

角の点を使う方法は一般的なパターンであり、次のようなライブラリでも見られます `Pillow` を使って `box` オブジェクトを作成し、 `Image`.

で bounding box を描画する場合は、検出されたすべての対象を反復処理するのを忘れないでください `predictions`!

```python
# Pillow ライブラリの box オブジェクトの例
for bounding_box in detections:
    x1 = bounding_box['x'] - bounding_box['width'] / 2
    x2 = bounding_box['x'] + bounding_box['width'] / 2
    y1 = bounding_box['y'] - bounding_box['height'] / 2
    y2 = bounding_box['y'] + bounding_box['height'] / 2
    box = (x1, x2, y1, y2)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.roboflow.com/roboflow/roboflow-jp/deploy/serverless/object-detection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
