Keypoint Detection
Roboflow でホストされているオブジェクト検出モデルで推論を実行します。
Pythonを使用してホストされたAPIで推論を実行するには、次を使用してください: roboflow Pythonパッケージ:
from roboflow import Roboflow
rf = Roboflow(api_key="API_KEY")
project = rf.workspace().project("MODEL_ENDPOINT")
model = project.version(VERSION).model
# ローカル画像で推論する
print(model.predict("your_image.jpg", confidence=40, overlap=30).json())
# 予測を可視化する
# model.predict("your_image.jpg", confidence=40, overlap=30).save("prediction.jpg")
# 他の場所にホストされている画像で推論する
# print(model.predict("URL_OF_YOUR_IMAGE", hosted=True, confidence=40, overlap=30).json())Linux または MacOS
ローカルファイルという名前の JSON 予測を取得する YOUR_IMAGE.jpg:
base64 YOUR_IMAGE.jpg | curl -d @- \
"https://detect.roboflow.com/your-model/42?api_key=YOUR_KEY"URL を介してウェブ上にホストされている画像で推論する(以下を忘れずに URL エンコードする):
curl -X POST "https://detect.roboflow.com/your-model/42?\
api_key=YOUR_KEY&\
image=https%3A%2F%2Fi.imgur.com%2FPEEvqPN.png"Windows
次をインストールする必要があります Windows 用 curl および Windows 用 GNU の base64 ツール。これを行う最も簡単な方法は git for Windows インストーラー を使用することです(これには curl および base64 が含まれます)。インストール時に「Use Git and optional Unix tools from the Command Prompt」を選択すると、コマンドラインツールも含まれます。
その後、上記と同じコマンドを使用できます。
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://detect.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://detect.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で利用できます;詳細は こちらのドキュメントを参照してください.
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" // モデルエンドポイントを設定(Dataset URL に表示)
// URL を構築
val uploadURL ="https://detect.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://detect.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://detect.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://detect.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 キー
params = "?api_key=" + api_key
+ "&name=YOUR_IMAGE.jpg"
response = HTTParty.post(
"https://detect.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 キー
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://detect.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"; // モデルエンドポイントを設定(Dataset URL で確認)
// HTTP リクエストの URL
$url = "https://detect.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"; // モデルエンドポイントを設定(Dataset URL で確認)
$img_url = "https://i.imgur.com/PEEvqPN.png";
// HTTP リクエストの URL
$url = "https://detect.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://detect.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://detect.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://detect.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://detect.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アプリにInference APIを統合したい場合は、 ここをクリックしてアップボートを記録してください.
レスポンスオブジェクトの形式
ホストされたAPI推論ルートは次を返します JSON 配列 predictions を含むオブジェクトを返します。各 prediction は以下のプロパティを持ちます:
x= 検出されたオブジェクトの水平中心点y= 検出されたオブジェクトの垂直中心点width= バウンディングボックスの幅height= バウンディングボックスの高さclass= 検出されたオブジェクトのクラスラベルconfidence= 検出されたオブジェクトが正しいラベルと位置座標であるというモデルの確信度keypoints= キーポイント予測の配列x= キーポイントの水平中心(画像の左上を基準)y= キーポイントの垂直中心(画像の左上を基準)class_name= キーポイントの名前class_id= キーポイントのID。スケルトンにマッピングされるverticesバージョンレコード内で、頂点の色とスケルトンのエッジをマップするには、 プロジェクトバージョンを表示confidence= キーポイントが正しい位置にあり、可視(遮蔽または削除されていない)である確信度
以下は REST API からのサンプルレスポンスオブジェクトです:
{
"predictions": [
{
"x": 189.5,
"y": 100,
"width": 163,
"height": 186,
"class": "helmet",
"confidence": 0.544,
"keypoints": [
{
"x": 189,
"y": 20,
"class_name": "top",
"class_id": 0,
"confidence": 0.91
},
{
"x": 188,
"y": 180,
"class_name": "bottom",
"class_id": 1,
"confidence": 0.93
}
]
}
],
"image": {
"width": 2048,
"height": 1371
}
}The image attribute は推論に送信した画像の高さと幅を含みます。バウンディングボックスの計算でこれらの値を使用する必要がある場合があります。
推論APIパラメータ
Inference APIの使用方法
POST https://detect.roboflow.com/:datasetSlug/:versionNumber
base64エンコードされた画像を直接モデルエンドポイントにPOSTできます。あるいは、画像が既に別の場所にホストされている場合は、クエリ文字列の image パラメータとしてURLを渡すことができます。
パスパラメータ
datasetSlug
string
データセット名の URL セーフなバージョン。これは、Web UI のメインプロジェクトビューの URL を見るか、モデルをトレーニングした後のデータセットバージョンのトレイン結果セクションにある「Get curl command」ボタンをクリックして確認できます。
version
number
データセットのバージョンを識別するバージョン番号
Query Parameters
image
string
追加する画像の URL。画像が別の場所にホストされている場合に使用します。(リクエストボディで base64 エンコードされた画像を POST しない場合は必須。) 注意: URL エンコードするのを忘れないでください。
classes
string
予測を特定のクラスのものに制限します。カンマ区切りの文字列で指定してください。 例: dog,cat デフォルト: 指定なし(すべてのクラスを表示)
overlap
number
同一クラスのバウンディングボックス予測が結合されて単一のボックスになる前に許容される最大重なり率(0〜100 の尺度)。 デフォルト: 30
confidence
number
返される予測の閾値(0〜100 の尺度)。低い数値ほど多くの予測を返します。高い数値ほど確信度の高い予測のみを返します。 デフォルト: 40
stroke
number
予測周りに表示されるバウンディングボックスの幅(ピクセル単位)(効果があるのは format が image).
デフォルト: 1
labels
boolean
予測にテキストラベルを表示するかどうか(効果があるのは format が image).
デフォルト: false
format
string
json - JSON予測の配列を返します。(レスポンス形式タブを参照してください)。
image - 注釈付き予測を含む画像をバイナリブロブとして返します。 Content-Type は image/jpeg. image_and_json - base64のvisualizationフィールドを含むJSON予測の配列を返します。
デフォルト: json
api_key
string
あなたの API キー(ワークスペースの API 設定ページから取得)
Request Body
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": "User is not authorized to access this resource"
}Last updated
Was this helpful?