インスタンスセグメンテーション
Roboflowでホストされているインスタンス分類モデルで推論を実行します。
LinuxまたはMacOS
ローカルファイル YOUR_IMAGE.jpg
:
base64 YOUR_IMAGE.jpg | curl -d @- \
"https://outline.roboflow.com/your-model/42?api_key=YOUR_KEY"
ウェブ上の他の場所にホストされている画像にURL経由で推論する( URLエンコードを忘れずに):
curl -X POST "https://outline.roboflow.com/your-model/42?\
api_key=YOUR_KEY&\
image=https%3A%2F%2Fi.imgur.com%2FPEEvqPN.png"
Windows
インストールが必要です Windows用curl と Windows用GNUのbase64ツール。これを行う最も簡単な方法は、 Windows用gitインストーラー を使用することです。これには curl
と base64
インストール時に「コマンドプロンプトからGitおよびオプションのUnixツールを使用する」を選択すると、コマンドラインツールも含まれます。
その後、上記と同じコマンドを使用できます。
Node.js
ここでは axios を使ってPOSTリクエストを実行するので、まず 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://outline.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で推論
const axios = require("axios");
axios({
method: "POST",
url: "https://outline.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.js
;詳細は こちらのドキュメントを参照してください.
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://detect.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
}
// レスポンス文字列を辞書に変換
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
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" // モデルエンドポイントを設定(データセットURLで確認)
// URLを構築
val uploadURL ="https://outline.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で推論
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://outline.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
ローカル画像での推論
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://outline.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で推論
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://outline.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();
}
}
}
}
Gemfile
source "https://rubygems.org"
gem "httparty", "~> 0.18.1"
gem "base64", "~> 0.1.0"
gem "cgi", "~> 0.2.1"
Gemfile.lock
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
ローカル画像での推論
require 'base64'
require 'httparty'
encoded = Base64.encode64(File.open("YOUR_IMAGE.jpg", "rb").read)
model_endpoint = "dataset/v" # モデルエンドポイントを設定
api_key = "" # ここにAPI KEY
params = "?api_key=" + api_key
+ "&name=YOUR_IMAGE.jpg"
response = HTTParty.post(
"https://outline.roboflow.com/" + model_endpoint + params,
body: encoded,
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'charset' => 'utf-8'
})
puts response
他の場所にホストされている画像のURLで推論
require 'httparty'
require 'cgi'
model_endpoint = "dataset/v" # モデルエンドポイントを設定
api_key = "" # ここにAPI KEY
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://outline.roboflow.com/" + model_endpoint + params,
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'charset' => 'utf-8'
})
puts response
ローカル画像での推論
<?php
// 画像をBase64エンコード
$data = base64_encode(file_get_contents("YOUR_IMAGE.jpg"));
$api_key = ""; // APIキーを設定
$model_endpoint = "dataset/v"; // モデルエンドポイントを設定(データセットURLで確認)
// Httpリクエスト用URL
$url = "https://outline.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で推論
<?php
$api_key = ""; // APIキーを設定
$model_endpoint = "dataset/v"; // モデルエンドポイントを設定(データセットURLで確認)
$img_url = "https://i.imgur.com/PEEvqPN.png";
// Httpリクエスト用URL
$url = "https://outline.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;
?>
ローカル画像での推論
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全体をバイトスライスに読み込む。
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
// base64としてエンコード。
data := base64.StdEncoding.EncodeToString(content)
uploadURL := "https://outline.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で推論
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://outline.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))
}
ローカル画像での推論
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://outline.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で推論
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://outline.roboflow.com/" + MODEL_ENDPOINT
+ "?api_key=" + API_KEY
+ "&image=" + HttpUtility.UrlEncode(imageURL);
// サービスポイント設定
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);
}
}
}
コードスニペットはユーザーからのリクエストに応じて追加しています。Elixirアプリに推論APIを統合したい場合は、 ここをクリックして投票を記録してください.
レスポンスオブジェクト形式
ホストAPI推論ルートは JSON
予測配列を含むオブジェクトを返します。各予測には以下のプロパティがあります:
x
= 検出オブジェクトの水平方向の中心点y
= 検出オブジェクトの垂直方向の中心点width
= バウンディングボックスの幅height
= バウンディングボックスの高さclass
= 検出オブジェクトのクラスラベルconfidence
= 検出オブジェクトが正しいラベルと座標を持つ確信度(モデルの信頼度)ポイント
= ポリゴンのアウトラインを構成する点のリスト - リスト内の各項目はキーを持つオブジェクトですx
とy
それぞれ点の水平座標と垂直座標のためのものです
// JSONオブジェクトの例
{
"predictions": [
{
"x": 179.2,
"y": 247,
"width": 231,
"height": 147,
"class": "A",
"confidence": 0.98,
"points": [
{
"x": 134,
"y": 314
},
{
"x": 116,
"y": 313
},
{
"x": 103,
"y": 310.1
},
{
"x": 72.7,
"y": 282
},
{
"x": 66.8,
"y": 273
},
]
}
]
}
APIリファレンス
推論APIの使用方法
POST
https://outline.roboflow.com/:datasetSlug/:versionNumber
base64エンコードされた画像をモデルエンドポイントに直接POSTできます。または、画像が他の場所にホストされている場合はURLを 画像
クエリ文字列のパラメータとして渡すことができます。
パスパラメータ
datasetSlug
string
データセット名のURLセーフバージョンです。Web UIのメインプロジェクトビューのURLを見るか、モデルのトレーニング後にデータセットバージョンのトレイン結果セクションで「curlコマンドを取得」ボタンをクリックすると見つけられます。
version
number
データセットのバージョンを識別するバージョン番号です
クエリパラメータ
画像
string
追加する画像のURL。他の場所に画像がホストされている場合に使用します。(リクエストボディでbase64エンコード画像をPOSTしない場合は必須) 注意: URLエンコードを忘れずに。
overlap
number
同じクラスのバウンディングボックス予測が1つのボックスにまとめられる前に許容される最大重なり率(0-100スケール)。 デフォルト: 30
confidence
number
返される予測のしきい値(0-100スケール)。数値が低いほど多くの予測が返され、高いほど高確度の予測のみ返されます。 デフォルト: 40
api_key
string
あなたのAPIキー(ワークスペースAPI設定ページで取得)
リクエストボディ
string
base64エンコード画像。(クエリパラメータで画像URLを渡さない場合は必須)
{
"predictions": [{
"x": 234.0,
"y": 363.5,
"width": 160,
"height": 197,
"class": "hand",
"confidence": 0.943
}, {
"x": 504.5,
"y": 363.0,
"width": 215,
"height": 172,
"class": "hand",
"confidence": 0.917
}, {
"x": 1112.5,
"y": 691.0,
"width": 139,
"height": 52,
"class": "hand",
"confidence": 0.87
}, {
"x": 78.5,
"y": 700.0,
"width": 139,
"height": 34,
"class": "hand",
"confidence": 0.404
}]
}
{
"Message": "ユーザーはこのリソースへのアクセス権限がありません"
}
Last updated
Was this helpful?