Ultralytics YOLO26を使用したインスタンスセグメンテーションとトラッキング
インスタンスセグメンテーションとは?#
インスタンスセグメンテーションは、画像内の個々のオブジェクトをピクセル単位で識別し、輪郭を描画するコンピュータービジョンタスクです。カテゴリごとにピクセルを分類するだけのセマンティックセグメンテーションとは異なり、インスタンスセグメンテーションでは各オブジェクトインスタンスに固有のラベルを付与し、正確に輪郭を描画します。そのため、医用画像、自動運転、産業オートメーションなど、詳細な空間把握を必要とするアプリケーションで重要です。
Ultralytics YOLO26は、YOLOモデルで知られる速度と効率性を維持しながら、物体の境界を正確に描画します。
Ultralyticsパッケージでは、次の2種類のインスタンスセグメンテーショントラッキングを利用できます。
-
クラスオブジェクトによるインスタンスセグメンテーション:各クラスオブジェクトに固有の色を割り当て、視覚的に明確に区別します。
-
オブジェクトトラックによるインスタンスセグメンテーション:各トラックを異なる色で表すことで、動画フレーム間での識別と追跡を容易にします。
視聴: Ultralytics YOLO26 による物体追跡を使ったインスタンスセグメンテーション
サンプル数#
| インスタンスセグメンテーション | インスタンスセグメンテーション + オブジェクトトラッキング |
|---|---|
![]() | ![]() |
| Ultralyticsインスタンスセグメンテーション | 物体トラッキング機能を備えたUltralyticsインスタンスセグメンテーション |
YOLO26でセグメンテーションとトラッキングを行う#
InstanceSegmentationソリューションは、各フレームでYOLO26セグメンテーションモデルを実行し、物体ごとのマスクを描画して、各インスタンスを個別に色分けします。これにより、動画全体で個々の物体を追跡できます。YOLO26n-segなどの-segモデルを読み込み、Python APIまたはCLIで入力データに対して実行します。
# Instance segmentation using Ultralytics YOLO26
yolo solutions isegment show=True
# Pass a source video
yolo solutions isegment source="path/to/video.mp4"
# Monitor the specific classes
yolo solutions isegment classes="[0, 5]"InstanceSegmentationの引数#
InstanceSegmentationの引数を以下の表に示します。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
model | str | None | Ultralytics YOLOモデルファイルへのパスです。 |
line_width | int | 2 | Solutionが描画するボックス、キーポイント、カウント表示の線幅です。 |
verbose | bool | True | 各フレームの入力shape、クラス数、処理速度を記録するSolutionのログを有効にします。トラッキング呼び出し自体は常にログを出力しません。 |
InstanceSegmentationソリューションでは、trackの引数も使用できます。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | 使用するトラッキングアルゴリズムを指定します。組み込みのオプション:botsort.yaml、bytetrack.yaml、ocsort.yaml、deepocsort.yaml、fasttrack.yaml、tracktrack.yaml。 |
conf | float | 0.25 | 検出の信頼度しきい値を設定します。値を低くすると、より多くの物体を追跡できますが、誤検出が含まれる可能性があります。 |
iou | float | 0.5 | 重複する検出をフィルタリングするためのIntersection over Union(IoU)しきい値を設定します。 |
classes | list | None | クラスインデックスで結果をフィルタリングします。たとえば、classes=[0, 2, 3]を指定すると、指定したクラスのみを追跡します。 |
device | str | None | 推論に使用するデバイスを指定します(例:cpu、cuda:0、0)。モデル実行に使用するCPU、特定のGPU、その他の計算デバイスを選択できます。 |
imgsz | int or tuple | 640 | 推論時の入力画像サイズです。正方形の場合は整数、または(height, width)のペアを指定します。形状はモデルのストライドに合わせて調整されます。 |
max_det | int | 300 | トラッキング前にフレームごとに保持する検出の最大数です。混雑したシーンでソリューションが処理する物体数を制限します。 |
quantize | int or str | None | 推論精度: CPU以外で実行するPyTorchおよびTorchScriptモデルでは、16(FP16)または32/未設定(FP32)を使用します。その他の形式では、アーティファクトとランタイムによって選択される精度が使用されます。非推奨のhalf引数を置き換えます。 |
さらに、以下の可視化引数を使用できます。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
show | bool | False | Trueの場合、注釈付き画像または動画をウィンドウに表示します。開発やテスト中にすぐ視覚的なフィードバックを得るのに便利です。 |
show_conf | bool | True | 各検出のラベルとともに信頼度スコアを表示します。各検出に対するモデルの確信度を確認できます。 |
show_labels | bool | True | 可視化出力で各検出のラベルを表示します。検出されたオブジェクトをすぐに把握できます。 |
show_boxes | bool | True | 検出されたオブジェクトの周囲にバウンディングボックスを描画します。画像や動画フレーム内のオブジェクトを視覚的に識別し、位置を確認するために不可欠です。 |
インスタンスセグメンテーションの活用例#
YOLO26によるインスタンスセグメンテーションは、さまざまな業界で数多くの実用的な用途があります。
廃棄物管理とリサイクル#
YOLO26は、廃棄物処理施設でさまざまな種類の素材を識別し、分類するために使用できます。このモデルは、プラスチックごみ、段ボール、金属、その他のリサイクル可能な素材を高精度にセグメント化し、自動仕分けシステムによる廃棄物処理の効率化を可能にします。世界で発生する70億トンのプラスチックごみのうち、リサイクルされるのは約10%にすぎないことを考えると、これは特に重要です。
自動運転車#
自動運転車では、インスタンスセグメンテーションによって、歩行者、車両、交通標識、その他の道路要素をピクセル単位で識別し、追跡できます。環境を正確に把握することは、ナビゲーションや安全に関する判断に欠かせません。YOLO26はリアルタイム性能を備えているため、時間的制約の厳しいこうした用途に適しています。
医用画像#
インスタンスセグメンテーションは、医用スキャン内の腫瘍、臓器、細胞構造を識別し、輪郭を描画できます。オブジェクトの境界を正確に描画できるYOLO26は、医療診断や治療計画に役立ちます。
建設現場のモニタリング#
建設現場では、インスタンスセグメンテーションによって、重機、作業員、資材を追跡できます。機器の位置を監視し、作業員が危険区域に入ったことを検出して安全を確保するとともに、ワークフローとリソース配分を最適化できます。
よくある質問#
Ultralytics YOLO26でインスタンスセグメンテーションを実行するには、YOLO26のセグメンテーションモデルを使用して
InstanceSegmentationソリューションを初期化し、動画フレームを処理します。簡単なコード例を以下に示します。import cv2 from ultralytics import solutions cap = cv2.VideoCapture("path/to/video.mp4") assert cap.isOpened(), "Error reading video file" # 動画ライター w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS)) video_writer = cv2.VideoWriter("instance-segmentation.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) # InstanceSegmentationを初期化 isegment = solutions.InstanceSegmentation( show=True, # 出力を表示する model="yolo26n-seg.pt", # model="yolo26n-seg.pt" for YOLO26によるオブジェクトセグメンテーション。 ) # 動画を処理 while cap.isOpened(): success, im0 = cap.read() if not success: print("Video frame is empty or processing is complete.") break results = isegment(im0) video_writer.write(results.plot_im) cap.release() video_writer.release() cv2.destroyAllWindows()インスタンスセグメンテーションは、画像内の個々の物体を識別して輪郭を描き、各物体に固有のラベルとマスクを割り当てます。物体トラッキングでは、動画の各フレームで物体に一貫したIDを割り当て、同じ物体を継続的に追跡できます。YOLO26の実装のように両者を組み合わせると、境界情報を正確に保持しながら、動画内の物体の動きや挙動を分析できます。
Ultralytics YOLO26は、Mask R-CNNやFaster R-CNNのような2段階モデルと比べて、リアルタイム性能、競争力のある精度、使いやすさを備えています。YOLO26は画像を1回のパスで処理する(1段階検出)ため、高い精度を維持しながら大幅に高速化できます。また、モデル、データセット、トレーニングパイプラインを管理するためのUltralytics Platformとも統合されています。速度と精度の両方が必要な用途において、YOLO26は優れたバランスを実現します。
はい。Ultralyticsは、インスタンスセグメンテーション向けYOLO26モデルのトレーニングに適した複数のデータセットを提供しています。これには、COCO-Seg、COCO8-Seg(迅速なテスト用の小規模なサブセット)、Package-Seg、Crack-Segが含まれます。これらのデータセットには、インスタンスセグメンテーションタスクに必要なピクセルレベルのアノテーションが含まれています。より専門的なアプリケーション向けには、Ultralytics形式に従ってカスタムデータセットを作成することもできます。データセットの詳細と使用方法については、Ultralyticsデータセットのドキュメントを参照してください。
コメント99
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
CatFatOw
Hello, I am trying to analyze a video and see if features grow/shrink over time. I am currently trying to use instance segmentation with object tracking; however, specifying
save_txt=Trueparameter inmodel.tracksaves every single prediction into a single huge txt file. Trying to count the frames by going through this large txt apparently doesn't work as the class ID are not in order and sorting it would lose all information.Is there any way for Ultralytics to save the txt files by frame number? For example, frame1.txt only contains the predictions of the first frame.
Any help would be greatly appreciated!
1
Glenn JocherUltralyticsFor per-frame TXT saving with tracking, you'll need to process results in your video loop and write custom frame-specific files. Here's a minimal adaptation of the Instance Segmentation and Tracking example:
frame_count = 0 while cap.isOpened(): ret, im0 = cap.read() if not ret: break results = model.track(im0, persist=True) # Save current frame's tracked objects with open(f'frame{frame_count}.txt', 'w') as f: for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()): f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n") frame_count += 1This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates. The official documentation shows similar frame processing in the Instance Segmentation with Object Tracking examples.
CatFatOw
Thank you!
Glenn JocherUltralyticsFor per-frame TXT saving during tracking, you'll need to process each frame individually in your video loop as shown in the Instance Segmentation with Object Tracking example. Here's a minimal adaptation that creates frame-specific files:
frame_count = 0 while cap.isOpened(): ret, im0 = cap.read() if not ret: break results = model.track(im0, persist=True) with open(f'frame{frame_count}.txt', 'w') as f: for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()): f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n") frame_count += 1This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates per frame. The approach mirrors the frame processing shown in our official tracking documentation.
pedmindset
Been trying to figure this out for a while now. I want to ask, can I use object counting in regions with instance sementation and tracking? You want to count vehicles that cross two specific regions, like so Object 001 crossed region A and region B. Is this possible to do
1
Glenn JocherUltralytics@pedmindset yes, it is possible to combine object counting in regions with instance segmentation and tracking using Ultralytics YOLO11. You can use the
trackmethod to assign consistent IDs to objects across frames and define regions to monitor their crossings. For guidance, refer to the segmentation and tracking examples in the Instance Segmentation and Tracking Guide. Let us know if you need further clarification!
DP1701
Cool, but I can't define an imgsz via solutions.InstanceSegmentation(…). Is there another option for this?
Glenn JocherUltralyticssolutions.InstanceSegmentationis a higher-level wrapper and doesn’t currently exposeimgszdirectly; if you need to control input size, run segmentation+tracking via the coreYOLO(...).track()API (supportsimgsz) as shown in the Tracking mode docs and keep using the Instance Segmentation and Tracking guide for solution-level usage.from ultralytics import YOLO model = YOLO("yolo26n-seg.pt") results = model.track(source="path/to/video.mp4", imgsz=640, show=True, tracker="botsort.yaml")
CatFatOw
Hello, I noticed that when using tracking mode compared to normal segmentation prediction, the number of features predicted decreased by quite a lot for feature dense videos even if I use the same parameters of confidence and maximum detection?
Glenn JocherUltralytics@CatFatOw great observation! This is actually expected behavior when using tracking mode compared to plain segmentation. Tracking algorithms apply additional filtering beyond confidence thresholds to maintain stable tracks, which can reduce the total number of detections.
Here are a few things that might help increase detections while maintaining tracking:
# Try adjusting these tracking-specific parameters results = model.track( frame, persist=True, conf=0.3, # Lower confidence threshold iou=0.5, # Adjust IoU threshold for NMS max_det=1000, # Increase max detections tracker="bytetrack.yaml" # Try different trackers )You can also experiment with different tracking algorithms - ByteTrack tends to be more permissive with new track creation compared to BoTSORT. The trade-off is between detection sensitivity and tracking stability, where tracking prioritizes consistent object IDs over detecting every possible instance.
If you need maximum detection sensitivity, consider running both modes and using tracking results only when you need the temporal consistency.
CatFatOw
Ok, thank you for the reply!
Mauricio566
Hello. Please, I need your help. I know exactly what segmenting an object is and how to do it. But I don't know what to do with an already segmented object or pixel mask. You can find a lot of information online about "how to segment a model or fit it to your dataset," but they don't tell you what to do with those masks in real projects. Can you give me some ideas or help, please? for r in results:
if r.masks is not None: mask = r.masks.data[0].cpu().numpy() there is the mask but honestly I don't know what to do. thankse-roe
Hello Glenn, thanks for the example! Actually, I had already figured it out—it was more of a suggestion for the documentation examples. []´s
Glenn JocherUltralyticsThank you for the suggestion! We always welcome community contributions to improve our documentation through GitHub Pull Requests. Feel free to submit any specific improvements you'd like to see in the Instance Segmentation with Object Tracking guide.
1
e-roe
Hello, Wouldn't it be good to have a complete example showing how to extract the track ID, contour points, class, and confidence? These methods that handle everything automatically end up being of little practical use, and finding this information in the documentation is quite challenging—it's often easier to find from third-party sources. []´s
Glenn JocherUltralytics(編集済み)@e-roe thanks for your feedback! You can access track IDs, classes, masks, and confidence scores directly from the results object. Here's a concise example showing how to extract these details:
results = isegment(im0) for i in range(len(isegment.clss)): track_id = isegment.track_ids[i] class_name = isegment.names[isegment.clss[i]] confidence = isegment.confs[i] mask = isegment.masks[i].data[0].numpy() # Binary mask array contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)For full implementation details, see the InstanceSegmentation reference in our documentation. Let us know if you need further clarification!
expen6ve
Hi! I tried training a pretrained yolov8m-seg model on our custom 1 class dataset consisting of 1,307 images with 5 augmentations like:
Flip: Horizontal, Vertical Rotation: Between -15° and +15° Saturation: Between -25% and +25% Blur: Up to 1.4px Noise: Up to 1.49% of pixels
with these training configurations:
# Train the model results = model.train( data="data6.yaml", epochs=250, imgsz=320, batch=8, workers=4, device=device, patience=18, copy_paste=0.1 # Add this line to enable copy-paste augmentation )this is my 16th model training as i tried testing out from 200+ images that and so on. In my val plots, i always get bad results. What can i further do to make a good model? it stopped training at 128 with the results below:
epoch,time,train/box_loss,train/seg_loss,train/cls_loss,train/dfl_loss,metrics/precision(B),metrics/recall(B),metrics/mAP50(B),metrics/mAP50-95(B),metrics/precision(M),metrics/recall(M),metrics/mAP50(M),metrics/mAP50-95(M),val/box_loss,val/seg_loss,val/cls_loss,val/dfl_loss,lr/pg0,lr/pg1,lr/pg2
126,4123.96,0.47628,0.76702,0.30532,0.85667,0.9862,0.96565,0.98972,0.94445,0.9775,0.97566,0.98923,0.83189,0.35178,0.67432,0.26286,0.89191,0.00101,0.00101,0.00101 127,4156.45,0.47613,0.76458,0.30439,0.85872,0.96877,0.98339,0.98913,0.94227,0.98701,0.96962,0.99053,0.83626,0.34228,0.67744,0.25083,0.88958,0.00100208,0.00100208,0.00100208
Glenn JocherUltralytics(編集済み)@expen6ve thank you for sharing your training details. For improved segmentation results with YOLO26, consider these adjustments:
- Dataset Size: 1.3k images may be insufficient for robust segmentation. Aim for ≥5k high-quality annotated images.
- Augmentation Tuning: Reduce rotation range (try ±5°) and remove noise augmentation, which can degrade mask precision.
- Hyperparameters: Increase imgsz to 640 (standard for segmentation tasks) and lower learning rate to 0.0001 with cosine scheduler.
- Model Selection: Try YOLO26s-seg instead of medium-sized models for better generalization on limited data.
For detailed guidance, see the Segmentation Training Tips in our documentation.
ShreyasChhetri
Hi can we implement a Reinforcement Learning function up above the Yolo training function for more accuracy can it happen ?
Glenn JocherUltralytics@ShreyasChhetri integrating reinforcement learning (RL) with YOLO training is an interesting idea, but YOLO models are not inherently designed for RL workflows. While it is theoretically possible, it would require substantial custom development outside the scope of the provided Ultralytics framework. You might consider exploring hybrid approaches combining RL and computer vision if your use case demands it. For standard training, refer to the existing YOLO training documentation: https://docs.ultralytics.com/modes/train.
ZhangAiyi
I have a question when run the code for Instance Segmentation with Object Tracking. The pycharm said UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 401: illegal multibyte sequence. Does anyone have the similar question? Thank you.
Glenn JocherUltralytics@ZhangAiyi it seems like you're encountering a Unicode encoding issue. You can try setting your environment's encoding to UTF-8 in PyCharm to resolve this. If the problem persists, please check the PyCharm settings or your system's locale configuration.

