For the complete documentation index, see llms.txt. This page is also available as Markdown.

Roboflow 2.0

Serverless Hosted API を通じて Roboflow 2.0 のセマンティックセグメンテーションモデルを使用します

Roboflow 2.0 は、DeepLabv3 ベースの semantic segmentation model です。Roboflow 2.0 のモデルは Roboflow platform で train し、当社の Serverless Hosted API.

セルフホスト型デプロイについては、こちらを参照してください Roboflow Inference.

コードサンプル

1

API Key を取得する

Roboflow アカウントを作成し、キーを次の場所で見つけます Roboflow API 設定ページ そしてシェルで利用できるようにします:

export ROBOFLOW_API_KEY="your-key-here"
2

依存関係をインストールする

次をインストールします: Inference SDKsupervision:

pip install inference-sdk supervision
3

モデルを実行する

train 済みの Roboflow 2.0 semantic segmentation model に対して inference を実行し、ピクセルごとの class map をデコードして、注釈付き PNG を書き出します。モデルはその {workspace}/{model-slug} ID で呼び出すことができます( Versions, Trainings, and Models).

レスポンスには segmentation_mask (各ピクセル値が class ID である base64 エンコードされたグレースケール PNG で、 0 は background であり、さらに class_map class ID を class 名に対応付けるものです。スクリプトはそれを 1 つの sv.Detections クラスごとに 1 行に分割するので sv.MaskAnnotator ソース画像上にマスクを重ねることができます。

import base64
import os
import cv2
import numpy as np
import requests
import supervision as sv
from inference_sdk import InferenceHTTPClient

content = requests.get("https://media.roboflow.com/quickstart/traffic.jpg").content
image = cv2.imdecode(np.frombuffer(content, np.uint8), cv2.IMREAD_COLOR)

client = InferenceHTTPClient(
    api_url="https://serverless.roboflow.com",
    api_key=os.environ["ROBOFLOW_API_KEY"],
)
# 学習済みエイリアスはありません: 独自のモデルを学習し、"your-project/1" をモデル ID に置き換えてください。
result = client.infer(image, model_id="your-project/1")
predictions = result["predictions"]

mask_bytes = base64.b64decode(predictions["segmentation_mask"])
class_map = predictions.get("class_map", {})
class_mask = cv2.imdecode(np.frombuffer(mask_bytes, np.uint8), cv2.IMREAD_GRAYSCALE)
class_mask = cv2.resize(class_mask, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)

class_ids = [cid for cid in np.unique(class_mask).tolist() if cid != 0]
if class_ids:
    masks, xyxy, names = [], [], []
    for cid in class_ids:
        binary = class_mask == cid
        rows = np.where(np.any(binary, axis=1))[0]
        cols = np.where(np.any(binary, axis=0))[0]
        xyxy.append([cols[0], rows[0], cols[-1], rows[-1]])
        masks.append(binary)
        names.append(class_map.get(str(cid), str(cid)))

    detections = sv.Detections(
        xyxy=np.array(xyxy, dtype=np.float64),
        mask=np.array(masks),
        class_id=np.array(class_ids),
        data={"class_name": np.array(names)},
    )
    annotated = sv.MaskAnnotator().annotate(image.copy(), detections)
    annotated = sv.LabelAnnotator().annotate(annotated, detections)
else:
    annotated = image

cv2.imwrite("annotated.png", annotated)
print("Saved annotated.png")

設定する api_url をデプロイ先に合わせてください:

  • https://serverless.roboflow.com Serverless Hosted API 用。

  • http://localhost:9001 ローカルの Inference サーバー用。

  • あなたの Dedicated Deployment プライベートエンドポイントの URL。

最終更新

役に立ちましたか?