Ultralytics YOLO를 사용한 인스턴스 세그멘테이션
인스턴스 세그멘테이션은 객체 탐지에서 한 단계 더 나아가 이미지 내 개별 객체를 식별하고 이미지의 나머지 부분과 분리하는 작업입니다.
인스턴스 분할 모델의 출력은 이미지의 각 객체 윤곽을 나타내는 마스크 또는 윤곽선 집합이며, 각 객체의 클래스 레이블과 신뢰도 점수도 포함됩니다. 이미지에서 객체의 위치뿐 아니라 정확한 모양까지 알아야 하는 경우 인스턴스 분할이 유용합니다.
시청: 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-seg | 640 | 39.6 | 33.9 | 53.3 ± 0.5 | 2.1 ± 0.0 | 2.7 | 9.3 |
| YOLO26s-seg | 640 | 47.3 | 40.0 | 118.4 ± 0.9 | 3.3 ± 0.0 | 10.4 | 34.5 |
| YOLO26m-seg | 640 | 52.5 | 44.1 | 328.2 ± 2.4 | 6.7 ± 0.1 | 23.6 | 121.7 |
| YOLO26l-seg | 640 | 54.4 | 45.5 | 387.0 ± 3.7 | 8.0 ± 0.1 | 28.0 | 140.1 |
| YOLO26x-seg | 640 | 56.5 | 47.0 | 787.0 ± 6.8 | 16.4 ± 0.1 | 62.8 | 314.0 |
- mAPval 값은 COCO val2017 데이터셋에서 단일 모델, 단일 스케일로 측정한 결과입니다.
yolo segment val data=coco.yaml device=0 nms=False로 재현할 수 있습니다. - 속도는 CPU의 ONNX와 NVIDIA T4 GPU의 TensorRT10을 사용하여 COCO val 이미지에서 측정한 평균값입니다.
yolo segment val data=coco.yaml batch=1 device=0|cpu nms=False로 재현할 수 있습니다. - Params 및 FLOPs 값은 Conv/BatchNorm 폴딩과 사용하지 않는 감지 브랜치 제거 후의 융합 모델 기준입니다. 사전 학습된 체크포인트에는 전체 학습 아키텍처가 유지되므로 값이 더 높을 수 있습니다.
이 체크포인트는 COCO의 80개 클래스를 세그멘테이션합니다. 재학습 없이 목록에 없는 카테고리를 세그멘테이션하려면, 텍스트 프롬프트, 시각적 예시 또는 내장 어휘를 입력으로 받는 YOLOE를 참조하세요.
예비 COCO 박스 및 마스크 결과는 미출시 YOLO27 미리 보기를 참조하세요.
학습#
이미지 크기 640으로 COCO8-seg 데이터셋에서 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 to YOLO guide에 설명된 대로 내장 convert_coco 함수를 use_segments=True와 함께 사용하세요. 다각형 도구와 SAM 기반 스마트 어노테이션을 사용하여 Ultralytics Platform 어노테이션으로 세그멘테이션 마스크를 만들 수도 있습니다.
검증#
학습된 YOLO26n-seg 모델의 정확도를 박스 및 마스크 평균 정밀도(mAP)로 측정해 검증합니다. model은 학습 data와 인수를 모델 속성으로 보존하므로 인수를 지정할 필요가 없습니다. Train 예제의 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); val 세트에 없는 클래스는 전체 mAP(B) 값을 사용합니다
metrics.box.ap_class_index # 실제로 평가된 클래스 인덱스
metrics.box.image_metrics # 정밀도, 재현율, F1, TP, FP, FN을 포함하는 이미지별 det 메트릭 딕셔너리
metrics.seg.map # map50-95(M)
metrics.seg.map50 # map50(M)
metrics.seg.map75 # map75(M)
metrics.seg.maps # 클래스별 mAP50-95(M); val 세트에 없는 클래스는 전체 mAP(M) 값을 사용합니다
metrics.seg.ap_class_index # 실제로 평가된 클래스 인덱스
metrics.seg.image_metrics # 정밀도, 재현율, F1, TP, FP, FN을 포함하는 이미지별 seg 메트릭 딕셔너리예측#
학습된 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.uint8Predict 페이지에서 predict 모드의 전체 세부 정보를 확인하세요.
결과 출력#
YOLO 인스턴스 세그멘테이션은 이미지마다 하나의 Results 객체를 반환합니다. 각 결과에는 객체 수준 예측이 저장되며, 각 감지된 인스턴스에는 자체 이진 마스크, 클래스, 신뢰도 및 박스가 포함됩니다.
| 속성 | 유형 | 형태 | 설명 |
|---|---|---|---|
result.masks | Masks | (N) | 인스턴스 마스크입니다. |
result.masks.data | torch.uint8 | (N,H,W) | 값이 0 또는 1인 이진 마스크입니다. |
result.masks.xy | np.float32 | list[(P,2)] | 픽셀 다각형입니다. |
result.masks.xyn | np.float32 | list[(P,2)] | 정규화된 다각형입니다. |
result.boxes | Boxes | (N) | 인스턴스 박스/클래스/신뢰도입니다. |
result.boxes.cls | torch.float32 | (N,) | 클래스 ID이며, 이름을 가져오려면 int으로 변환합니다. |
모든 작업에서 작업별 Results 필드를 확인하려면 작업별 예측 결과 섹션을 참조하세요.
인스턴스 세그멘테이션과 시맨틱 세그멘테이션 비교#
인스턴스 세그멘테이션은 객체 수준 세그멘테이션입니다. 자동차 두 대는 마스크 두 개, 박스 두 개, 신뢰도 점수 두 개를 생성합니다. 시맨틱 세그멘테이션은 픽셀 수준 분류입니다. 동일한 자동차 두 대는 객체별 박스, 신뢰도 또는 기본 다각형 목록 없이 한 이미지 크기의 클래스 맵에서 같은 클래스 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은 정적 shape에서 객체 탐지, 인스턴스 세그멘테이션 및 포즈를 위한 내장 NMS(nms=True)를 지원합니다. 기본 세그멘테이션 내보내기(nms=None)에서는 NMS 처리를 사용자가 맡습니다.
| 형식 | format 인수 | 모델 | 메타데이터 | 인수 |
|---|---|---|---|---|
| PyTorch | - | yolo26n-seg.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-seg.torchscript | ✅ | imgsz, quantize, dynamic, nms, batch, device |
| ONNX | onnx | yolo26n-seg.onnx | ✅ | imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n-seg_openvino_model/ | ✅ | imgsz, quantize, dynamic, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n-seg.engine | ✅ | imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n-seg.mlpackage | ✅ | imgsz, dynamic, quantize, nms, batch, device |
| Apple Core AI | coreai | yolo26n-seg.aimodel | ✅ | imgsz, batch, quantize |
| TF SavedModel | saved_model | yolo26n-seg_saved_model/ | ✅ | imgsz, quantize, opset, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n-seg.pb | ❌ | imgsz, opset, batch, device |
| TF Edge TPU | edgetpu | yolo26n-seg_edgetpu.tflite | ✅ | imgsz, quantize, opset, data, fraction, device |
| LiteRT | litert | yolo26n-seg.tflite | ✅ | imgsz, quantize, batch, data, fraction, device |
| PaddlePaddle | paddle | yolo26n-seg_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n-seg.mnn | ✅ | imgsz, batch, dynamic, quantize, simplify, opset, nms, device |
| NCNN | ncnn | yolo26n-seg_ncnn_model/ | ✅ | imgsz, quantize, device |
| IMX500 | imx | yolo11n_imx_model/ | ✅ | imgsz, quantize, data, fraction, nms, device |
| RKNN | rknn | yolo26n-seg_rknn_model/ | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| ExecuTorch | executorch | yolo26n-seg_executorch_model/ | ✅ | imgsz, quantize, batch, data, fraction, device |
| Axelera | axelera | yolo26n-seg_axelera_model/ | ✅ | imgsz, batch, quantize, data, fraction, device |
| DEEPX | deepx | yolo26n-seg_deepx_model/ | ✅ | imgsz, quantize, simplify, opset, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n-seg_qnn.onnx | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| Hailo | hailo | yolo26n-seg_hailo_model/ | ✅ | imgsz, name, quantize, data, fraction, simplify, conf, iou, device |
| Huawei Ascend | ascend | yolo26n-seg_ascend_model/ | ✅ | imgsz, batch, name, quantize, opset, simplify, nms, device |
| AMD Xilinx | xilinx | yolo26n-seg_xilinx_model/ | ✅ | imgsz, name, quantize, data, fraction, opset, simplify, device |
| NXP | nxp | yolo26n-seg_nxp.tflite | ✅ | imgsz, quantize, data, fraction, device |
| ST Edge AI | stedgeai | yolo26n-seg_stedgeai.onnx | ✅ | imgsz, quantize, data, fraction, opset, simplify, device |
nms=None은 외부 NMS를 위해 기본적으로 원시 출력을 사용합니다(YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다). 사용 가능한 NMS가 필요 없는 헤드를 선택하려면 nms=False를 설정하세요. 지원되지 않는 형식은 해당 형식의 기본 출력 경로로 대체됩니다. 위의 nms 항목은 nms=True로 NMS를 포함할 수 있는 형식을 나타냅니다.
자세한 export 내용은 내보내기 페이지를 참조하세요.
자주 묻는 질문#
사용자 지정 데이터셋으로 YOLO26 분할 모델을 학습하려면 먼저 YOLO 분할 형식으로 데이터셋을 준비해야 합니다. 기본 제공
convert_coco유틸리티를 사용해 COCO JSON 데이터셋을 변환할 수 있습니다. 데이터셋을 준비한 후 Python 또는 CLI 명령을 사용해 모델을 학습할 수 있습니다.예제from ultralytics import YOLO # 사전 학습된 YOLO 세그먼트 모델 로드 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개를 분할하며, 사용자 지정 데이터로 파인튜닝할 때 탄탄한 출발점이 됩니다. 동일한
YOLOAPI로 연구 및 산업 애플리케이션의 학습, 검증, 예측, 내보내기를 모두 처리할 수 있습니다.사전 학습된 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)와 같은 검증 지표를 얻을 수 있습니다.
Python 또는 CLI 명령을 사용하면 YOLO 세그멘테이션 모델을 간편하게 ONNX 형식으로 내보낼 수 있습니다.
예제from ultralytics import YOLO # 사전 학습된 모델 불러오기 model = YOLO("yolo26n-seg.pt") # 모델을 ONNX 형식으로 내보내기 model.export(format="onnx")다양한 형식으로 내보내는 방법에 대한 자세한 내용은 Export 페이지를 참조하세요.
댓글418
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
hp0716
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?
1hp0716
Additionally, is there a method to fit the boundary of the ID card mask into four straight lines for locating the ID card?
Glenn JocherUltralytics@hp0716 for smoother segmentation results on ID cards, try using
retina_masks=Trueduring 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
cyberpunk-edgerunner
Just to confirm, while auto annotating, instead of using SAM one can also use one's custom build model. right ??
1rugvedjalit
Yes, you can annotate using custom build model but please check the annotation class id after annotation.
LwpZoe
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?
1LwpZoe
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
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.
LwpZoe
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
Glenn JocherUltralytics@LwpZoe your command is almost correct for training from scratch without pretrained weights. Ensure the
resume=Trueargument 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,1This will train your YOLO11 segmentation model from scratch using your custom dataset. For more details, visit the Segment Task Documentation.
potatoandtomatowhy
how to use two camera segment with gpu?
1ZhaoHaoran0613
Same question
1
Paula DerrengerUltralyticsTo 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
YOLOclass 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.
Boaruzhanchik
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
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
im0with your frame variable if it's named differently. Hope this helps! 😊Boaruzhanchik
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)
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_maskis defined before using it inauto_transformations_first(coordinates_mask)for theelif 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! 😊
uqasha524
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!
Glenn JocherUltralyticsUltralytics training uses one task per model (
detect,segment, orobb), 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.1rugvedjalit
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
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.
TrieuCris
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?
Glenn JocherUltralyticsThat’s usually expected with standard instance segmentation:
yolo26-seglearns 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 tor.masksafter 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.
miracle101000
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.
Glenn JocherUltralyticsYes — use a
-segmodel on your webcam feed, setclasses=[...]if you only want one class, andmax_det=1if 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)miracle101000
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.
Glenn JocherUltralyticsIf 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
imgszlow 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.
Heyujie96
你是不是加载模型的时候没有写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: @.***>
liyongkang2000
result = model.predict(os.path.join(path,file), nms = True, )这是我的预测代码是官方提供的呀
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, )liyongkang2000
您好,您的建议是有效的,但边界还是没有那么光滑,以及大目标效果更差,有时会出现正方形,您这边还有其他的解决方案吗?期待您的回复
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的文本输出,我这边可以帮你确认主要瓶颈是分辨率、标注轮廓质量还是框裁剪造成的。
