はじめる

Ultralytics YOLOによるインスタンスセグメンテーション

Ultralytics YOLO instance segmentation examples

インスタンスセグメンテーションは物体検出をさらに発展させたもので、画像内の個々の物体を識別し、画像のほかの部分から分割します。

インスタンスセグメンテーションモデルの出力は、画像内の各オブジェクトの輪郭を示すマスクまたは輪郭線の集合であり、各オブジェクトのクラスラベルと信頼度スコアも含まれます。画像内でオブジェクトの位置だけでなく、正確な形状も把握する必要がある場合に、インスタンスセグメンテーションが役立ちます。



視聴: Python で学習済み Ultralytics YOLO モデルを使ってセグメンテーションを実行する方法。
ヒント

YOLO26 Segmentモデルでは -seg サフィックスを使用します(例:yolo26n-seg.pt)。COCOで事前学習されています。

モデル#

COCOデータセットで事前学習されたYOLO26 Segmentモデルを以下に示します。

モデルは、初回使用時に最新のUltralytics リリースから自動的にダウンロードされます。

モデルサイズ
(ピクセル)
mAPbox50-95
(e2e)
mAPmask50-95
(e2e)
速度
CPU ONNX
(ms)
速度
T4 TensorRT10
(ms)
パラメーター
(M)
FLOPs
(B)
YOLO26n-seg64039.633.953.3 ± 0.52.1 ± 0.02.79.3
YOLO26s-seg64047.340.0118.4 ± 0.93.3 ± 0.010.434.5
YOLO26m-seg64052.544.1328.2 ± 2.46.7 ± 0.123.6121.7
YOLO26l-seg64054.445.5387.0 ± 3.78.0 ± 0.128.0140.1
YOLO26x-seg64056.547.0787.0 ± 6.816.4 ± 0.162.8314.0
  • mAPvalの値は、COCO val2017データセットにおける単一モデル、単一スケールでのものです。
    yolo segment val data=coco.yaml device=0 nms=Falseで再現できます。
  • 速度は、COCO val画像に対してONNXをCPUで、TensorRT10をNVIDIA T4 GPUで使用した場合の平均値です。
    yolo segment val data=coco.yaml batch=1 device=0|cpu nms=Falseで再現できます。
  • ParamsとFLOPsの値は、Conv/BatchNormのfoldingと未使用の検出ブランチの削除を適用した後の、融合済みモデルの値です。事前学習済みチェックポイントにはトレーニング時のアーキテクチャ全体が保持されているため、より大きな値が表示される場合があります。

これらのチェックポイントは、COCOの80クラスをセグメント化します。再トレーニングせずにリスト外のカテゴリをセグメント化するには、クラスをテキストプロンプト、視覚的な例、または組み込み語彙として指定できるYOLOEをご覧ください。

予備的なCOCOのボックスおよびマスクの結果については、未リリースのYOLO27プレビューをご覧ください。

学習#

COCO8-segデータセットで、画像サイズ640、100エポックの条件でYOLO26n-segモデルをトレーニングします。

例
from ultralytics import YOLO

# モデルを読み込む
model = YOLO("yolo26n-seg.yaml")  # YAMLから新しいモデルを構築します
model = YOLO("yolo26n-seg.pt")  # 事前トレーニング済みモデルを読み込みます(トレーニングにはこちらを推奨します)
model = YOLO("yolo26n-seg.yaml").load("yolo26n-seg.pt")  # YAMLからモデルを構築し、重みを転送します

# モデルをトレーニングする
results = model.train(data="coco8-seg.yaml", epochs=100, imgsz=640)

trainモードの詳細は、Trainページをご覧ください。セグメンテーションモデルは、Ultralytics Platformのクラウドトレーニングでもトレーニングできます。

データセットのフォーマット#

YOLOセグメンテーションデータセットの形式について詳しくは、Dataset Guideをご覧ください。既存のCOCO JSONデータセットをYOLO形式に変換するには、COCOからYOLOへのガイドで説明されているように、use_segments=Trueを指定して組み込みのconvert_coco関数を使用します。また、ポリゴンツールとSAMを活用したスマートアノテーションを備えたUltralytics Platformのアノテーションでセグメンテーションマスクを作成することもできます。

検証#

トレーニング済みYOLO26n-segモデルの精度を、ボックスおよびマスクの平均適合率(mAP)として測定して検証します。model はトレーニング時の data と引数をモデル属性として保持するため、引数を指定する必要はありません。トレーニングの例にある path/to/best.pt はCOCO8-segで検証します。公式の重みには、使用環境に存在しないトレーニングデータセットのパスが記録されているため、警告を表示してタスクのデフォルト coco8-seg.yaml にフォールバックします。別のデータセットで検証するには、data を渡してください。

例
from ultralytics import YOLO

# モデルを読み込む
model = YOLO("yolo26n-seg.pt")  # 公式モデルを読み込みます
model = YOLO("path/to/best.pt")  # カスタムモデルを読み込む

# モデルを検証します
metrics = model.val()  # データセットと設定が記憶されるため、引数は不要です
metrics.box.map  # map50-95(B)
metrics.box.map50  # map50(B)
metrics.box.map75  # map75(B)
metrics.box.maps  # クラスごとの mAP50-95(B)。検証セットに存在しないクラスには全体の mAP(B) が設定されます
metrics.box.ap_class_index  # 実際に評価されたクラスのインデックス
metrics.box.image_metrics  # detの画像ごとのメトリクス辞書。precision、recall、F1、TP、FP、FNを含みます
metrics.seg.map  # map50-95(M)
metrics.seg.map50  # map50(M)
metrics.seg.map75  # map75(M)
metrics.seg.maps  # クラスごとの mAP50-95(M)。検証セットに存在しないクラスには全体の mAP(M) が設定されます
metrics.seg.ap_class_index  # 実際に評価されたクラスのインデックス
metrics.seg.image_metrics  # segの画像ごとのメトリクス辞書。precision、recall、F1、TP、FP、FNを含みます

推論#

トレーニング済みのYOLO26n-segモデルを使用して、画像の推論を実行します。

例
from ultralytics import YOLO

# モデルを読み込む
model = YOLO("yolo26n-seg.pt")  # 公式モデルを読み込みます
model = YOLO("path/to/best.pt")  # カスタムモデルを読み込む

# モデルで予測します
results = model("https://ultralytics.com/images/bus.jpg")  # 画像に対して予測します

# 結果にアクセスします
for result in results:
    xy = result.masks.xy  # ピクセル座標で表したマスクポリゴン
    xyn = result.masks.xyn  # 正規化されたマスクポリゴン
    masks = result.masks.data  # バイナリマスク、shape (N,H,W)、dtype torch.uint8

Predictページでpredictモードの詳細をご確認ください。

結果の出力#

YOLOのインスタンスセグメンテーションは、画像ごとに1つのResultsオブジェクトを返します。各結果には物体単位の予測が格納され、検出された各インスタンスは独自のバイナリマスク、クラス、信頼度、ボックスを持ちます。

属性種類形状説明
result.masksMasks(N)インスタンスマスクです。
result.masks.datatorch.uint8(N,H,W)バイナリマスクです。値は 0 または 1 です。
result.masks.xynp.float32list[(P,2)]ピクセルポリゴンです。
result.masks.xynnp.float32list[(P,2)]正規化されたポリゴンです。
result.boxesBoxes(N)インスタンスのボックス、クラス、信頼度です。
result.boxes.clstorch.float32(N,)クラスIDです。名前を取得するには int にキャストします。

すべてのタスクにおける、タスク固有のResultsフィールドについては、タスク別の予測結果セクションをご覧ください。

インスタンスセグメンテーションとセマンティックセグメンテーションの比較#

インスタンスセグメンテーションは物体単位のセグメンテーションです。2台の車は、2つのマスク、2つのボックス、2つの信頼度スコアになります。 セマンティックセグメンテーションはピクセル単位の分類です。同じ車は、1つの画像サイズのクラスマップ内で同じクラスIDを持つピクセルになり、物体ごとのボックス、信頼度、デフォルトのポリゴンリストはありません。セマンティックセグメンテーションのページにある項目ごとの比較をご覧ください。

エクスポート#

YOLO26n-segモデルをONNXやCoreMLなどの別の形式にエクスポートします。

例
from ultralytics import YOLO

# モデルを読み込む
model = YOLO("yolo26n-seg.pt")  # 公式モデルを読み込みます
model = YOLO("path/to/best.pt")  # カスタムモデルを読み込む

# モデルをエクスポートする
model.export(format="onnx")

使用可能なYOLO26-segのエクスポート形式を以下の表に示します。format 引数を使用して、任意の形式にエクスポートできます(例:format='onnx' または format='engine')。エクスポート済みモデルに対して直接予測または検証を実行できます(例:yolo predict model=yolo26n-seg.onnx)。エクスポートが完了すると、モデルの使用例が表示されます。

注

CoreMLは、静的形状の検出、インスタンスセグメンテーション、ポーズに対して、組み込みNMS(nms=True)をサポートしています。デフォルトのセグメンテーションエクスポート(nms=None)では、NMSをコンシューマー側で実行します。

形式format引数モデルメタデータ引数
PyTorch-yolo26n-seg.pt✅-
TorchScripttorchscriptyolo26n-seg.torchscript✅imgsz, quantize, dynamic, nms, batch, device
ONNXonnxyolo26n-seg.onnx✅imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-seg_openvino_model/✅imgsz, quantize, dynamic, nms, batch, data, fraction, device
TensorRTengineyolo26n-seg.engine✅imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-seg.mlpackage✅imgsz, dynamic, quantize, nms, batch, device
Apple Core AIcoreaiyolo26n-seg.aimodel✅imgsz, batch, quantize
TF SavedModelsaved_modelyolo26n-seg_saved_model/✅imgsz, quantize, opset, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-seg.pb❌imgsz, opset, batch, device
TF Edge TPUedgetpuyolo26n-seg_edgetpu.tflite✅imgsz, quantize, opset, data, fraction, device
LiteRTlitertyolo26n-seg.tflite✅imgsz, quantize, batch, data, fraction, device
PaddlePaddlepaddleyolo26n-seg_paddle_model/✅imgsz, batch, device
MNNmnnyolo26n-seg.mnn✅imgsz, batch, dynamic, quantize, simplify, opset, nms, device
NCNNncnnyolo26n-seg_ncnn_model/✅imgsz, quantize, device
IMX500imxyolo11n_imx_model/✅imgsz, quantize, data, fraction, nms, device
RKNNrknnyolo26n-seg_rknn_model/✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
ExecuTorchexecutorchyolo26n-seg_executorch_model/✅imgsz, quantize, batch, data, fraction, device
Axeleraaxelerayolo26n-seg_axelera_model/✅imgsz, batch, quantize, data, fraction, device
DEEPXdeepxyolo26n-seg_deepx_model/✅imgsz, quantize, simplify, opset, data, optimize, device
Qualcomm QNNqnnyolo26n-seg_qnn.onnx✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
Hailohailoyolo26n-seg_hailo_model/✅imgsz, name, quantize, data, fraction, simplify, conf, iou, device
Huawei Ascendascendyolo26n-seg_ascend_model/✅imgsz, batch, name, quantize, opset, simplify, nms, device
AMD Xilinxxilinxyolo26n-seg_xilinx_model/✅imgsz, name, quantize, data, fraction, opset, simplify, device
NXPnxpyolo26n-seg_nxp.tflite✅imgsz, quantize, data, fraction, device
ST Edge AIstedgeaiyolo26n-seg_stedgeai.onnx✅imgsz, quantize, data, fraction, opset, simplify, device

nms=None は、外部NMS用にデフォルトでraw出力を返します(YOLO26はAxelera上でNMSフリーヘッドを維持します)。利用可能なNMSフリーヘッドを選択するには、nms=Falseを設定します。非対応の形式では、ネイティブの出力経路にフォールバックします。上記のnmsの項目は、nms=Trueを使用してNMSを埋め込める形式を示しています。

詳細なexport情報については、Exportページをご覧ください。

よくある質問#

  • カスタムデータセットでYOLO26セグメンテーションモデルをトレーニングするには、まずデータセットをYOLOセグメンテーション形式に準備する必要があります。組み込みのconvert_cocoユーティリティを使用して、COCO JSONデータセットを変換できます。データセットの準備ができたら、PythonまたはCLIコマンドでモデルをトレーニングできます。

    例
    from ultralytics import YOLO
    
    # 事前学習済みYOLO26セグメントモデルを読み込みます
    model = YOLO("yolo26n-seg.pt")
    
    # モデルをトレーニングする
    results = model.train(data="path/to/your_dataset.yaml", epochs=100, imgsz=640)

    使用可能なその他の引数については、Configurationページをご覧ください。

  • 物体検出では、オブジェクトの周囲にバウンディングボックスを描画して画像内のオブジェクトを識別し、位置を特定します。一方、インスタンスセグメンテーションはバウンディングボックスを特定するだけでなく、各オブジェクトの正確な形状も描画します。YOLO26のインスタンスセグメンテーションモデルは、検出した各オブジェクトの輪郭を示すマスクまたは輪郭線を生成します。医療画像や自動運転など、オブジェクトの正確な形状が重要なタスクで特に役立ちます。

  • Ultralytics YOLO26は、高精度とリアルタイム推論速度を両立しているため、動画ストリームやエッジデバイスでのインスタンスセグメンテーションに適しています。YOLO26 SegmentモデルはCOCOデータセットで事前学習されているため、一般的な80クラスのオブジェクトをすぐにセグメンテーションでき、カスタムデータでのファインチューニングにも適した出発点となります。同じ YOLO APIで、研究用途と産業用途の両方におけるトレーニング、検証、予測、エクスポートに対応します。

  • 事前学習済みYOLOセグメンテーションモデルの読み込みと検証は簡単です。PythonとCLIの両方を使った方法を以下に示します。

    例
    from ultralytics import YOLO
    
    # 事前トレーニング済みモデルを読み込む
    model = YOLO("yolo26n-seg.pt")
    
    # モデルを検証します
    metrics = model.val()
    print("Mean Average Precision for boxes:", metrics.box.map)
    print("Mean Average Precision for masks:", metrics.seg.map)

    これらの手順により、セグメンテーション性能の標準的な指標である平均適合率(mAP)などの検証メトリクスが得られます。

  • YOLOセグメンテーションモデルは、PythonまたはCLIコマンドを使用して簡単にONNX形式へエクスポートできます。

    例
    from ultralytics import YOLO
    
    # 事前トレーニング済みモデルを読み込む
    model = YOLO("yolo26n-seg.pt")
    
    # モデルをONNXフォーマットにエクスポート
    model.export(format="onnx")

    さまざまな形式へのエクスポートの詳細は、Exportページをご覧ください。

コメント418

質問したり、結果を共有したり、ほかの人をサポートしたりできます。

  1. hp0716GitHub

    Thank you for sharing the YOLOV11-seg model. I have encountered a problem now. When using YOLOV11 to segment my ID card, there are many uneven areas on the edges of the segmentation result, which affects my fitting of the card certificate boundary. How can I obtain smooth segmentation results? Do you have any parameters that can be directly configured?

    1
    1. hp0716GitHub

      Additionally, is there a method to fit the boundary of the ID card mask into four straight lines for locating the ID card?

    2. Glenn JocherUltralytics

      @hp0716 for smoother segmentation results on ID cards, try using retina_masks=True during inference to get higher resolution masks:

      from ultralytics import YOLO
      model = YOLO('yolo11n-seg.pt')
      results = model(image, retina_masks=True)

      For post-processing to get smooth boundaries, you can apply morphological operations and contour approximation:

      import cv2
      import numpy as np
      
      # Get mask from results
      mask = results[0].masks.data[0].cpu().numpy()
      mask = (mask * 255).astype(np.uint8)
      
      # Apply morphological smoothing
      kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
      mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
      mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
      
      # Find contours and approximate to quadrilateral
      contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
      if contours:
          largest_contour = max(contours, key=cv2.contourArea)
          epsilon = 0.02 * cv2.arcLength(largest_contour, True)
          approx = cv2.approxPolyDP(largest_contour, epsilon, True)
          
          # Force to 4 points for ID card corners
          if len(approx) >= 4:
              corners = approx[:4]

      This approach combines higher resolution masks with geometric fitting to achieve the straight-line boundaries you need for ID card localization.

      1
    1. rugvedjalitGitHub

      Yes, you can annotate using custom build model but please check the annotation class id after annotation.

  2. LwpZoeGitHub

    I have used yolo11x-seg.yaml to do instance segmentation on my dataset, my dataset is multiclassified medical endoscopic tissue instance segmentation task, but the metrics scores are very low, I don't know how to improve these metrics scores, can you please give me some ideas?

    1
    1. LwpZoeGitHub

      The metrics score with ShuffleAttention added to the tenth layer of backbone is reduced compared to the metrics score for YOLO11x-seg.yaml alone.

      Trained my dataset using YOLO11x-seg.yaml+ShuffleAttention with no other parameters changed the metrics scores are as follows:

      Class Images Instances Box( P R mAP50 mAP50-95) Mask( P R mAP50 mAP50-95): all 58 332 0.583 0.504 0.519 0.238 0.551 0.456 0.468 0.195

      Training my dataset using the official YOLO11x-seg.yaml alone, the metrics scores are as follows:

      Class Images Instances Box( P R mAP50 mAP50-95) Mask( P R mAP50 mAP50-95): all 58 332 0.669 0.465 0.489 0.257 0.648 0.446 0.455 0.217

      1
    2. Glenn JocherUltralytics(編集済み)

      @LwpZoe thank you for sharing these details. For medical instance segmentation with YOLO11x-seg, we recommend: 1) Verify your dataset quality and annotation consistency using the Dataset Guide, 2) Try increasing input resolution (imgsz=1280) to capture fine tissue details, 3) Implement medical-specific augmentations like CLAHE or elastic transforms, and 4) Consider using our pretrained weights with progressive fine-tuning rather than architectural modifications initially. The segmentation documentation contains additional optimization strategies for medical imaging tasks.

  3. LwpZoeGitHub

    Hello, here's a question: I want to use YOLO11 to train my dataset from scratch and make predictions, and don't want to use prepared pre-trained weights, so how do I write the training commands? Is this code below ok: yolo segment train data=datasets/yolo_seg/data.yaml model=yolo11n-seg.yaml epochs=300 batch=16 resume=True imgsz=640 device=0,1

    1
    1. Glenn JocherUltralytics

      @LwpZoe your command is almost correct for training from scratch without pretrained weights. Ensure the resume=True argument is removed, as it is only used to resume interrupted training. The corrected command would be:

      yolo segment train data=datasets/yolo_seg/data.yaml model=yolo11n-seg.yaml epochs=300 batch=16 imgsz=640 device=0,1

      This will train your YOLO11 segmentation model from scratch using your custom dataset. For more details, visit the Segment Task Documentation.

    1. Paula DerrengerUltralytics

      To use two cameras for segmentation with a GPU, you'll need to set up a multi-threaded or multi-process pipeline to handle the video streams concurrently. Each camera stream can be processed in a separate thread or process, ensuring efficient utilization of the GPU. You can use the YOLO class from the Ultralytics library to load your segmentation model and process the frames from each camera. For detailed steps and code examples, please refer to the Ultralytics segmentation documentation. If you encounter any issues, make sure you're using the latest version of the package.

  4. BoaruzhanchikGitHub

    Hi, can you tell me how I can get the detected car plates in separate windows (as many as I have detected and output), my code outputs only one window.

    while True:
    ret, im0 = cap.read()
    if not ret:
    break
    results = model(im0,verbose=False,conf=0.4,retina_masks=True)
    boxes = results[0].boxes.xyxy.tolist()
    classes = results[0].boxes.cls.tolist()
    confidences = results[0].boxes.conf.tolist()
    masks = results[0].masks
    if results[0].masks is not None:
    clss = results[0].boxes.cls.cpu().tolist()
    masks = results[0].masks.xy
    coordinates_mask = masks[0]
    contour = coordinates_mask.reshape((-1, 1, 2)).astype(np.int32)
    epsilon = 0.04 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    auto_transform = four_point_transform(im0, approx.reshape(-2, 2))
    cv2.imshow('automated', auto_transform)
    1
    1. Paula DerrengerUltralytics

      @Boaruzhanchik hey there! 👋 To display each detected car plate in separate windows, you can loop through the detected boxes and create a window for each. Here's a quick example to get you started:

      for i, box in enumerate(boxes):
          x1, y1, x2, y2 = map(int, box[:4])
          plate = im0[y1:y2, x1:x2]
          cv2.imshow(f'Plate {i}', plate)
      cv2.waitKey(0)
      cv2.destroyAllWindows()

      This code snippet extracts each detected plate based on its bounding box coordinates and displays it in a new window. Make sure to replace im0 with your frame variable if it's named differently. Hope this helps! 😊

    2. BoaruzhanchikGitHub

      Thanks a lot for the help, I did it this way, it seems to work too

      if results[0].masks is not None:
          clss = results[0].boxes.cls.cpu().tolist()
          masks = results[0].masks.xy
          if len(masks) == 1:
               coordinates_mask = masks[0]
               auto_transformations_first(coordinates_mask)
          elif len(masks) <= 2:
                auto_transformations_first(coordinates_mask)
                coordinates_mask_2 = masks[1]
                auto_transformations_second_screen(coordinates_mask_2)
      def auto_transformations_first(coordinates_mask):
           contour = coordinates_mask.reshape((-1, 1, 2)).astype(np.int32)
           epsilon = 0.04 * cv2.arcLength(contour, True)
           approx = cv2.approxPolyDP(contour, epsilon, True)
           auto_transform = four_point_transform(im0, approx.reshape(-2, 2))
           cv2.imshow('automated_first', auto_transform)
    3. Paula DerrengerUltralytics

      @Boaruzhanchik hey there! 👋 It looks like you've found a way to handle different numbers of masks with your approach. Nicely done! 🎉 Just a quick tip: you might want to ensure coordinates_mask is defined before using it in auto_transformations_first(coordinates_mask) for the elif len(masks) <= 2: case, to avoid any potential errors. Other than that, your method seems solid. Keep up the great work, and if you have any more questions or need further assistance, feel free to ask. Happy coding! 😊

  5. uqasha524GitHub

    Hi everyone,

    We have fine-tuned a YOLO model primarily for segmentation, but our dataset contains mixed annotation types—the main task is segmentation, while some classes/regions use standard bounding boxes and OBB (Oriented Bounding Boxes).

    What is the recommended approach in Ultralytics for handling a dataset with mixed annotation formats in a single training pipeline, and could you explain how this is possible? Specifically, how should the data labels and model configuration be structured to handle multiple task types simultaneously?

    Any guidance, workflow explanations, or examples would be greatly appreciated!

    1. Glenn JocherUltralytics

      Ultralytics training uses one task per model (detect, segment, or obb), so mixed label formats cannot be trained jointly in a standard pipeline. Use separate label directories/YAML files and train separate models, or convert box/OBB annotations to polygon labels so every object follows the segmentation format; note that a segmentation model returns masks and axis-aligned boxes, not native OBB predictions.

      1
    2. rugvedjalitGitHub

      Ultralytics YOLO does not support mixing detection, segmentation, and OBB annotations in a single training run. Each model/task expects a specific label format and corresponding loss function.

      The recommended approach is to separate the annotations and train separate models for segmentation, detection, and OBB, then combine their outputs during inference if needed. A single multi-task model would require a custom architecture and training pipeline.

      1
    3. Glenn JocherUltralytics

      @uqasha524, do you need masks, axis-aligned boxes, and OBBs as distinct outputs at inference, or would segmentation outputs alone meet your requirements? That distinction will help us suggest the appropriate dataset structure without introducing unnecessary custom training work.

  6. TrieuCrisGitHub

    With yolo26-seg, when a small object is placed on top of a large object, I get a result where the mask of the large object is punctured right where the small object is covering it. How can I fix this?

    1. Glenn JocherUltralytics

      That’s usually expected with standard instance segmentation: yolo26-seg learns the visible region of each instance, so the larger object can appear “punctured” where it is occluded; if you want a filled large-object mask, you’ll need labels that include the full occluded shape or apply post-processing to r.masks after inference, and the segmentation object isolation guide shows where to access those masks—if you share one image plus its label here, the Ultralytics team can help confirm whether it’s annotation or model behavior.

  7. miracle101000GitHub

    hello if I wanted to use your segmentation model for inference on a live camera preview, to only detect a single item at a time, how would I go about it? thank you.

    1. Glenn JocherUltralytics

      Yes — use a -seg model on your webcam feed, set classes=[...] if you only want one class, and max_det=1 if you want at most one instance per frame; if you share your use case here, the Ultralytics team can help refine it, and the Segment task docs cover the mask outputs you’ll use.

      from ultralytics import YOLO
      
      model = YOLO("yolo26n-seg.pt")
      results = model.predict(source=0, stream=True, classes=[0], max_det=1)
    2. miracle101000GitHub

      Ok thx. I am actually trying to implement edge detection on android devices for rectangular objects. I have tried OpenCV but it's not enough. So I was thinking to use a segmentation model for my rectangular processor (overlay would only show on rectangular objects) but any time I try to implement this on android, I get serious lagging issues on the camera preview. Plus honestly new to this AI stuff.

    3. Glenn JocherUltralytics

      If you only need a rectangle-style overlay, a segmentation model is usually heavier than necessary on Android; I’d start with a small OBB or detect model instead, export it with Export mode, and keep imgsz low or run inference every few frames to reduce preview lag. If you share your device, export format, and current FPS here, the Ultralytics team can suggest the lightest setup.

  8. Heyujie96GitHub

    你是不是加载模型的时候没有写task=“segment”

    ------------------ Original ------------------ From: liyongkang2000 @.> Date: Sun,Feb 1,2026 1:12 AM To: ultralytics/ultralytics @.> Cc: Heyujie96 @.>, Comment @.> Subject: Re: [ultralytics/ultralytics] zh/tasks/segment/ (Discussion #8508)

    您好我想问一下,在YOLOV8和V11测试下来,由于目标框的存在,不管如果在后处理阶段调整目标框的范围,被分割目标的上下左右边界始终会被目标框切割,导致分割结果的边缘不平滑。会出现很多直线,但是在YOLOV26上没有尝试过,YOLOV26是否优化了这个边界问题,或者说是否其他的解决方法可以解决这个分割结果的边缘不平滑问题

    — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>

    1. Glenn JocherUltralytics

      你这段 predict() 用法本身没问题;一般也不需要手动写 task="segment",关键是确保加载的是分割权重(*-seg.pt),否则不会有 result.masks 输出;如果分割边缘出现“被框裁切/直线感强”的现象,可以在推理时尝试开启 retina_masks=True 并适当增大 imgsz(NMS 默认就会做,通常不需要单独传 nms=True),相关参数处理可参考 SegmentationPredictor 源码说明。

      from ultralytics import YOLO
      
      model = YOLO("yolo26n-seg.pt")  # 确保是 -seg 权重
      results = model.predict(
          os.path.join(path, file),
          retina_masks=True,
          imgsz=1024,
          conf=0.25,
          iou=0.7,
      )
    2. liyongkang2000GitHub

      您好,您的建议是有效的,但边界还是没有那么光滑,以及大目标效果更差,有时会出现正方形,您这边还有其他的解决方案吗?期待您的回复

    3. Glenn JocherUltralytics

      这个“边缘直线/大目标出现方块”的现象通常是分割头的掩码分辨率与“mask 会按预测框裁剪”的机制共同导致的(框越紧越容易看出裁剪痕迹,可参考这条 社区说明:inference 时 mask 是否会被 bbox 裁剪);如果你是自训练模型,想从根源提升大目标的边缘细节,建议在训练时把 mask_ratio 调小(更高 mask 分辨率)并配合更大的 imgsz/更大的 *-seg 模型,mask_ratio 参数说明见 配置参数文档。

      from ultralytics import YOLO
      
      model = YOLO("yolo26s-seg.pt")  # 也可以试试更大一点的 -seg 权重
      model.train(
          data="path/to/your_dataset.yaml",
          imgsz=1024,
          epochs=100,
          mask_ratio=2,  # 需要更细可再降到 1(显存占用会明显上升)
      )

      如果你只是想“导出/显示更光滑”的轮廓(不改变模型预测本身),可以按 Isolating Segmentation Objects 的方式拿到 result.masks.data 后做一次轻量的 blur + close 再取轮廓;另外麻烦贴一张出现“正方形”的原图和对应可视化结果,并附上 yolo checks 的文本输出,我这边可以帮你确认主要瓶颈是分辨率、标注轮廓质量还是框裁剪造成的。