인스턴스 세그멘테이션 데이터셋 개요

인스턴스 세그멘테이션은 이미지 내 개별 객체를 식별하고 경계를 구분하는 컴퓨터 비전 작업입니다. 이 가이드에서는 Ultralytics YOLO가 지원하는 인스턴스 세그멘테이션 데이터셋 형식을 개괄하고, 모델 학습을 위해 데이터셋을 준비, 변환, 사용하는 방법을 안내합니다.

지원되는 데이터셋 형식#

Ultralytics YOLO 형식#

YOLO 세그멘테이션 모델 학습에 사용하는 데이터셋 라벨 형식은 다음과 같습니다:

  1. 이미지마다 텍스트 파일 하나: 데이터셋의 각 이미지에는 이미지 파일과 이름이 같고 확장자가 ".txt"인 텍스트 파일이 하나씩 대응됩니다.
  2. 객체마다 한 행: 텍스트 파일의 각 행은 이미지의 객체 인스턴스 하나에 해당합니다.
  3. 행마다 객체 정보 포함: 각 행에는 객체 인스턴스에 관한 다음 정보가 포함됩니다:
    • 객체 클래스 인덱스: 객체의 클래스를 나타내는 정수입니다(예: 사람은 0, 자동차는 1 등).
    • 객체 폴리곤 좌표: 객체 마스크의 윤곽을 나타내는 (x, y) 좌표이며, 값은 0과 1 사이로 정규화됩니다.

세그멘테이션 데이터셋 파일에서 단일 행의 형식은 다음과 같습니다:

<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>

이 형식에서 <class-index>은 객체의 클래스 인덱스이고, <x1> <y1> <x2> <y2> ... <xn> <yn>은 객체 세그멘테이션 마스크의 정규화된 폴리곤 좌표입니다(값은 이미지 너비와 높이를 기준으로 [0, 1]에 해당합니다). 좌표는 공백으로 구분됩니다.

다음은 3개 점으로 이루어진 세그먼트 하나와 5개 점으로 이루어진 세그먼트 하나, 총 두 객체가 있는 단일 이미지의 YOLO 데이터셋 형식 예시입니다.

0 0.681 0.485 0.670 0.487 0.676 0.487
1 0.504 0.000 0.501 0.004 0.498 0.004 0.493 0.010 0.492 0.0104
팁
  • 각 행의 길이가 동일할 필요는 없습니다.
  • 각 세그멘테이션 라벨에는 최소 3개의 (x, y) 점이 있어야 합니다: <class-index> <x1> <y1> <x2> <y2> <x3> <y3>
  • 모든 객체에는 폴리곤이 필요합니다. Detect 형식의 행(<class-index> <x_center> <y_center> <width> <height>)에는 폴리곤이 없으며, 박스 수와 폴리곤 수가 일치하지 않는 세그먼테이션 데이터셋은 라벨을 로드할 때 ValueError 오류와 함께 거부됩니다.

데이터셋 YAML 형식#

Ultralytics 프레임워크는 세그멘테이션 모델 학습을 위한 데이터셋 및 모델 구성을 정의할 때 YAML 파일 형식을 사용합니다. 다음은 세그멘테이션 데이터셋을 정의하는 데 사용하는 YAML 형식의 예입니다:

ultralytics/cfg/datasets/coco8-seg.yaml
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# COCO8-seg dataset (first 8 images from COCO train2017) by Ultralytics
# Documentation: https://docs.ultralytics.com/datasets/segment/coco8-seg
# Example usage: yolo train data=coco8-seg.yaml
# parent
# ├── ultralytics
# └── datasets
#     └── coco8-seg ← downloads here (1 MB)

# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: coco8-seg # dataset root dir
train: images/train # train images (relative to 'path') 4 images
val: images/val # val images (relative to 'path') 4 images
test: # test images (optional)

# Classes
names:
  0: person
  1: bicycle
  2: car
  3: motorcycle
  4: airplane
  5: bus
  6: train
  7: truck
  8: boat
  9: traffic light
  10: fire hydrant
  11: stop sign
  12: parking meter
  13: bench
  14: bird
  15: cat
  16: dog
  17: horse
  18: sheep
  19: cow
  20: elephant
  21: bear
  22: zebra
  23: giraffe
  24: backpack
  25: umbrella
  26: handbag
  27: tie
  28: suitcase
  29: frisbee
  30: skis
  31: snowboard
  32: sports ball
  33: kite
  34: baseball bat
  35: baseball glove
  36: skateboard
  37: surfboard
  38: tennis racket
  39: bottle
  40: wine glass
  41: cup
  42: fork
  43: knife
  44: spoon
  45: bowl
  46: banana
  47: apple
  48: sandwich
  49: orange
  50: broccoli
  51: carrot
  52: hot dog
  53: pizza
  54: donut
  55: cake
  56: chair
  57: couch
  58: potted plant
  59: bed
  60: dining table
  61: toilet
  62: tv
  63: laptop
  64: mouse
  65: remote
  66: keyboard
  67: cell phone
  68: microwave
  69: oven
  70: toaster
  71: sink
  72: refrigerator
  73: book
  74: clock
  75: vase
  76: scissors
  77: teddy bear
  78: hair drier
  79: toothbrush

# Download script/URL (optional)
download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-seg.zip

train, val, test 필드는 각각 학습, 검증, 테스트 이미지를 가리킵니다. 각 필드는 디렉터리, 이미지 파일, 디렉터리 또는 이미지 파일 목록, 또는 줄마다 이미지 경로 하나가 지정된 UTF-8 *.txt 파일을 입력으로 받습니다(경로가 ./로 시작하면 *.txt 파일을 기준으로 확인합니다). *.txt 파일은 디렉터리의 일부만 선택해 학습하거나, 라벨이 없는 이미지를 건너뛰거나, 여러 소스의 이미지를 하나의 split으로 결합할 때 유용합니다.

`*.txt` 파일의 이미지 경로
path: datasets/coco8-seg # dataset root
train: train.txt # a directory, an image, a list e.g. [images/a, images/b], or a *.txt file
val: val.txt
names:
  0: person

names은 클래스 이름으로 구성된 딕셔너리입니다. 이름의 순서는 YOLO 데이터셋 파일에 지정된 객체 클래스 인덱스의 순서와 일치해야 합니다.

사용법#

예제
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n-seg.pt")  # 사전 학습된 모델을 불러옵니다(학습에 권장).

# 모델 학습
results = model.train(data="coco8-seg.yaml", epochs=100, imgsz=640)

지원되는 데이터셋#

Ultralytics YOLO는 인스턴스 세그먼테이션 작업에 다양한 데이터셋을 지원합니다. 가장 일반적으로 사용되는 데이터셋은 다음과 같습니다. 이 데이터셋 중 대부분은 Ultralytics Platform에서도 호스팅되므로, 이미지와 어노테이션을 살펴보고 데이터셋 통계를 확인하며 클라우드 학습을 위해 데이터셋을 복제할 수 있습니다.

  • Carparts-seg: 자동차 부품 세그먼테이션에 중점을 둔 특화 데이터셋으로, 자동차 분야 애플리케이션에 적합합니다. 다양한 차량과 개별 자동차 부품에 대한 상세 어노테이션을 제공합니다.
  • COCO: 객체 탐지, 세그먼테이션, 캡셔닝을 위한 종합 데이터셋으로, 다양한 카테고리에 걸쳐 20만 개 이상의 라벨링된 이미지를 제공합니다.
  • COCO8-seg: 세그먼테이션 모델 학습을 빠르게 테스트할 수 있도록 설계된 COCO의 소규모 8개 이미지 하위 집합입니다. ultralytics 저장소에서 CI 검사와 워크플로 검증에 적합합니다.
  • COCO128-seg: 분할 어노테이션이 포함된 COCO 이미지 128개 하위 집합으로 구성된 소규모 인스턴스 분할 작업용 데이터셋입니다.
  • Crack-seg: 다양한 표면의 균열 세그먼테이션을 위해 설계된 데이터셋입니다. 인프라 유지보수와 품질 관리에 필수적이며, 구조적 결함을 식별하는 모델을 학습할 수 있도록 상세한 이미지를 제공합니다.
  • Package-seg: 다양한 유형과 형태의 포장재 세그먼테이션을 위한 데이터셋입니다. 물류 및 창고 자동화에 특히 유용하며, 포장물 취급 및 분류 시스템 개발을 지원합니다.

사용자 데이터셋 추가#

자체 데이터셋을 Ultralytics YOLO 형식으로 세그먼테이션 모델 학습에 사용하려면, 위의 "Ultralytics YOLO 형식"에 명시된 형식을 따르는지 확인하십시오. 어노테이션을 필요한 형식으로 변환하고 YAML 구성 파일에 경로, 클래스 수, 클래스 이름을 지정하십시오. images/과 labels/은 같은 수준의 별도 폴더로 유지하고 하위 폴더 구조를 일치시켜야 합니다. 이미지 폴더에 라벨 .txt 파일을 넣으면 모델이 라벨을 놓칠 수 있습니다.

레이블 형식 포팅 또는 변환#

COCO 데이터셋 형식을 YOLO 형식으로 변환#

다음 코드 예제를 사용하면 널리 사용되는 COCO 데이터셋 형식의 레이블을 YOLO 형식으로 변환할 수 있습니다:

예제
from ultralytics.data.converter import convert_coco

convert_coco(labels_dir="path/to/coco/annotations/", use_segments=True)

이 변환 도구를 사용하면 COCO 데이터셋이나 COCO 형식의 데이터셋을 Ultralytics YOLO 형식으로 변환할 수 있습니다.

사용하려는 데이터셋이 모델과 호환되고 필요한 형식 규칙을 따르는지 다시 확인하십시오. 형식이 올바른 데이터셋은 성공적인 세그먼테이션 모델 학습에 매우 중요합니다.

자동 어노테이션#

자동 어노테이션은 사전 학습된 감지 모델로 세그멘테이션 데이터셋을 생성하므로 모든 마스크를 수작업으로 그리지 않고도 많은 이미지에 레이블을 지정할 수 있습니다. 대신 브라우저에서 레이블을 지정하려면 Ultralytics Platform에서 SAM, YOLO, 클래스 프롬프트 기반 스마트 어노테이션을 사용할 수 있으며, VLM 리더보드에서 프롬프트 기반 모델의 감지 정확도, 비용, 속도를 비교할 수 있습니다.

탐지 모델을 사용해 세그먼테이션 데이터셋 생성하기#

Ultralytics 프레임워크를 사용해 데이터셋에 자동으로 어노테이션을 추가하려면 다음과 같이 auto_annotate 함수를 사용하면 됩니다.

예제
from ultralytics.data.annotator import auto_annotate

auto_annotate(data="path/to/images", det_model="yolo26x.pt", sam_model="sam_b.pt")
인수유형기본값설명
datastr필수어노테이션 또는 세분화 대상 이미지가 포함된 디렉터리 경로입니다.
det_modelstr'yolo26x.pt'초기 객체 탐지를 위한 YOLO 탐지 모델 경로입니다.
sam_modelstr'sam_b.pt'세분화를 위한 SAM 모델 경로입니다(SAM, SAM 2, MobileSAM 및 SAM 3 가중치 지원).
devicestr''연산 장치입니다(예: 'cuda:0', 'cpu' 또는 자동 장치 감지를 위한 '').
conffloat0.25약한 탐지를 필터링하기 위한 YOLO 탐지 신뢰도 임계값입니다.
ioufloat0.5겹치는 박스를 필터링하기 위한 비최대 억제의 IoU 임계값입니다.
imgszint640이미지 크기 조정에 사용할 입력 크기입니다(필요한 경우 32의 배수로 올림).
max_detint300메모리 효율성을 위한 이미지당 최대 탐지 수입니다.
classeslist[int]None탐지할 클래스 인덱스 목록입니다(예: 사람 및 자전거의 경우 [0, 1]).
output_dirstrNone어노테이션 저장 디렉터리입니다(기본값: 동일한 상위 디렉터리의 <data>_auto_annotate_labels).

auto_annotate 함수에는 이미지 경로와 함께 사전 학습된 탐지 모델(예: YOLO26, YOLO11 또는 기타 모델), 세그먼테이션 모델(예: SAM, SAM 2, MobileSAM 또는 SAM 3)을 지정하는 선택적 인수, 모델을 실행할 장치, 어노테이션 결과를 저장할 출력 디렉터리를 전달합니다.

사전 학습된 모델을 사용하면 자동 어노테이션을 통해 고품질 세그멘테이션 데이터셋을 만드는 데 필요한 시간과 노력을 크게 줄일 수 있습니다. 이미지 컬렉션이 큰 연구자와 개발자에게 특히 유용하며, 수동 어노테이션보다 모델 개발과 평가에 집중할 수 있습니다.

데이터셋 주석 시각화#

모델을 학습하기 전에 데이터셋 어노테이션을 시각화해 정확성을 확인하는 것이 유용합니다. Ultralytics는 이를 위한 유틸리티 함수를 제공합니다. 이 함수는 탐지 형식의 박스 라벨(<class-index> <x_center> <y_center> <width> <height>)만 읽으므로 세그먼테이션 폴리곤 라벨 파일은 파싱할 수 없습니다.

from ultralytics.data.utils import visualize_image_annotations

label_map = {  # 주석이 지정된 모든 클래스 레이블을 포함하는 레이블 맵을 정의합니다.
    0: "person",
    1: "car",
}

# Visualize
visualize_image_annotations(
    "path/to/image.jpg",  # 입력 이미지 경로입니다.
    "path/to/annotations.txt",  # 이미지의 주석 파일 경로입니다.
    label_map,
)

이 함수는 경계 상자를 그리고 클래스 이름으로 객체에 라벨을 표시하며, 가독성을 높이도록 텍스트 색상을 조정합니다. 이를 통해 학습 전에 어노테이션 오류를 찾아 수정할 수 있습니다.

세그먼테이션 마스크를 YOLO 형식으로 변환하기#

각 픽셀 값이 클래스 인덱스 + 1이고 0이 배경인 그레이스케일 마스크 이미지가 있다면, 다음을 사용해 YOLO 세그먼테이션 형식으로 변환할 수 있습니다.

from ultralytics.data.converter import convert_segment_masks_to_yolo_seg

# COCO처럼 클래스가 80개인 데이터셋의 경우
convert_segment_masks_to_yolo_seg(masks_dir="path/to/masks_dir", output_dir="path/to/output_dir", classes=80)

이 유틸리티는 마스크 이미지를 YOLO 세그먼테이션 형식으로 변환하고 지정된 출력 디렉터리에 저장합니다.

자주 묻는 질문#

  • Ultralytics YOLO는 인스턴스 세그멘테이션을 위한 여러 데이터셋 형식을 지원하며, 기본 형식은 자체 Ultralytics YOLO 형식입니다. 데이터셋의 각 이미지에는 객체 정보가 여러 행으로 분할되어 포함된 텍스트 파일이 필요합니다(객체당 한 행). 각 행에는 클래스 인덱스와 정규화된 폴리곤 좌표가 기록됩니다.

  • Ultralytics 도구를 사용하면 COCO 형식의 어노테이션을 YOLO 형식으로 간단히 변환할 수 있습니다. ultralytics.data.converter 모듈의 convert_coco 함수를 사용할 수 있습니다.

    from ultralytics.data.converter import convert_coco
    
    convert_coco(labels_dir="path/to/coco/annotations/", use_segments=True)

    이 스크립트는 COCO 데이터셋 어노테이션을 필요한 YOLO 형식으로 변환하므로 YOLO 모델 학습에 적합하게 사용할 수 있습니다. 자세한 내용은 라벨 형식 이식 또는 변환을 참조하십시오.

  • Ultralytics로 YOLO 모델을 학습하기 위한 YAML 파일을 준비하려면 데이터셋 경로와 클래스 이름을 정의해야 합니다. 다음은 YAML 구성의 예입니다.

    # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
    
    # COCO8-seg dataset (first 8 images from COCO train2017) by Ultralytics
    # Documentation: https://docs.ultralytics.com/datasets/segment/coco8-seg
    # Example usage: yolo train data=coco8-seg.yaml
    # parent
    # ├── ultralytics
    # └── datasets
    #     └── coco8-seg ← downloads here (1 MB)
    
    # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
    path: coco8-seg # dataset root dir
    train: images/train # train images (relative to 'path') 4 images
    val: images/val # val images (relative to 'path') 4 images
    test: # test images (optional)
    
    # Classes
    names:
      0: person
      1: bicycle
      2: car
      3: motorcycle
      4: airplane
      5: bus
      6: train
      7: truck
      8: boat
      9: traffic light
      10: fire hydrant
      11: stop sign
      12: parking meter
      13: bench
      14: bird
      15: cat
      16: dog
      17: horse
      18: sheep
      19: cow
      20: elephant
      21: bear
      22: zebra
      23: giraffe
      24: backpack
      25: umbrella
      26: handbag
      27: tie
      28: suitcase
      29: frisbee
      30: skis
      31: snowboard
      32: sports ball
      33: kite
      34: baseball bat
      35: baseball glove
      36: skateboard
      37: surfboard
      38: tennis racket
      39: bottle
      40: wine glass
      41: cup
      42: fork
      43: knife
      44: spoon
      45: bowl
      46: banana
      47: apple
      48: sandwich
      49: orange
      50: broccoli
      51: carrot
      52: hot dog
      53: pizza
      54: donut
      55: cake
      56: chair
      57: couch
      58: potted plant
      59: bed
      60: dining table
      61: toilet
      62: tv
      63: laptop
      64: mouse
      65: remote
      66: keyboard
      67: cell phone
      68: microwave
      69: oven
      70: toaster
      71: sink
      72: refrigerator
      73: book
      74: clock
      75: vase
      76: scissors
      77: teddy bear
      78: hair drier
      79: toothbrush
    
    # Download script/URL (optional)
    download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-seg.zip

    데이터셋에 맞게 경로와 클래스 이름을 업데이트하십시오. 자세한 내용은 데이터셋 YAML 형식 섹션을 참조하십시오.

  • Ultralytics YOLO의 자동 어노테이션을 사용하면 사전 학습된 탐지 모델로 데이터셋의 세그먼테이션 어노테이션을 생성할 수 있습니다. 따라서 수동 라벨링이 크게 줄어듭니다. 다음과 같이 auto_annotate 함수를 사용할 수 있습니다.

    from ultralytics.data.annotator import auto_annotate
    
    auto_annotate(data="path/to/images", det_model="yolo26x.pt", sam_model="sam_b.pt")  # 또는 sam_model="mobile_sam.pt"

    이 함수는 어노테이션 프로세스를 자동화하여 더 빠르고 효율적으로 처리합니다. 자세한 내용은 자동 어노테이션 참조를 살펴보십시오.

댓글80

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  1. hp0716GitHub

    Hello, currently my segmentation task requires multi-channel masking, which means that one pixel may belong to multiple categories. Is there any code that implements this feature? Looking forward to receiving your reply.

    1
  2. kh-diabGitHub

    hello i tried to convert coco format to yolo format in segmented images but the generated yolo files are empty

    from ultralytics.data.converter import convert_coco

    convert_coco(labels_dir="groupC/annotations", use_segments=True)

    can you tell me

    this is example of the original annotation file exported from CVAT to coco format knowing that I used SAM model to do the segmentation

    { "id": 16, "image_id": 10, "category_id": 1, "segmentation": { "counts": [ 2815839, 2, 1817, 5, 1814, 7, 1812, 8, 1810, 10, 1809, 11, 1807, 14, 1805, 15, 1803, 17, 1802, 18, 1801, 18, 1800, 19, 1800, 19, 1800, 19, 1800, 20, 1798, 21, 1798, 21, 1798, 22, 1796, 23, 1796, 23, 1797, 23, 1796, 23, 1796, 23, 1796, 23, 1796, 23, 1797, 23, 1796, 23, 1797, 22, 1797, 23, 1797, 22, 1797, 23, 1797, 22, 1797, 22, 1798, 22, 1798, 21, 1798, 22, 1798, 21, 1798, 22, 1798, 21, 1799, 21, 1798, 21, 1799, 21, 1800, 19, 1801, 18, 1803, 15, 1807, 10, 829643 ], "size": [ 1820, 2048 ] }, "area": 861.0, "bbox": [ 1547.0, 263.0, 46.0, 42.0 ], "iscrowd": 1, "attributes": { "occluded": false } },

    1
    1. Glenn JocherUltralytics

      @kh-diab it seems like the conversion process isn't working as expected. Please ensure that your COCO annotations are correctly formatted and that the use_segments=True parameter is set. Also, make sure you're using the latest version of the Ultralytics package. If the issue persists, try running the conversion with a smaller subset of your data to isolate the problem. For more detailed guidance, you can refer to the Instance Segmentation Datasets Overview.

  3. ratomGitHub

    I have semantic segmentation data of 6 classes. But the dataset has one folder for images and another folder for segmentation mask. I have color maps for each mask and each class. In this case, I want to create a dataset for YOLO style segmentation. How can I do it.

  4. rohith-aiunikaGitHub

    hi yolo team, can i perform object tracking for my segmentation model using this kind of annotation format ... or do i need x_center, y_center, width, height ... format?

    1. Glenn JocherUltralytics

      @rohith-aiunika the annotation format <class-index> <x1> <y1> <x2> <y2> ... <xn> <yn> is sufficient for segmentation tasks, including object tracking with segmentation models, as long as it aligns with the Ultralytics YOLO format. The additional fields for bounding boxes (e.g., x_center, y_center, width, height) are not required unless explicitly specified for other tasks. For more details, you can refer to Instance Segmentation Datasets Overview.

    1. Glenn JocherUltralytics(수정됨)

      @mathrank each row in a segmentation label file is a single polygon, so a hole cannot be a separate row (it would be read as a second object). Instead, join the outer and inner boundaries into one polygon by connecting them with a thin bridge between their closest points, which is how the COCO converter (merge_multi_segment) merges multi-part segments. For details on the format, refer to Instance Segmentation Datasets Overview.

  5. johnlockejrrGitHub

    Finally I ended up with the following code, any opinion?

    from ultralytics import YOLO
    import cv2
    import numpy as np
    from pathlib import Path
    
    image_path = "/home/incognito/yolov8/datasets/sam_v1/images/a34e234a-76be-5392-9b39-4abdcd051719.jpg"
    
    # Load the YOLOv8 model
    model = YOLO('/home/incognito/yolov8/runs/segment/train/weights/best.pt')
    
    # Perform inference on an image
    results = model(image_path)
    img = cv2.imread(image_path)
    img_name = Path(image_path).stem
    
    # Extract bounding boxes, classes, names, and confidences
    boxes = results[0].boxes.xyxy.tolist()
    classes = results[0].boxes.cls.tolist()
    names = results[0].names
    confidences = results[0].boxes.conf.tolist()
    
    bboxes = []
    # Iterate through the results
    for box, cls, conf in zip(boxes, classes, confidences):
        x1, y1, x2, y2 = box
        confidence = conf
        detected_class = cls
        name = names[int(cls)]
        bboxes.append(box)
        #print(f"class: {name}, box: {box}")
    
    bboxes.sort(key=lambda x: x[0])
    
    for number, bbox in enumerate(bboxes):
        print(bbox)
        x1, y1, x2, y2 = bbox
        iso_crop = img[int(y1):int(y2), int(x1):int(x2)]
        cv2.imwrite(f"{img_name}_{number}.jpg", iso_crop)
    1. Glenn JocherUltralytics

      @johnlockejrr sorting by x1 is fine if you want to order the bounding boxes from left to right. Ensure this aligns with your intended use case. If you need further assistance, feel free to ask! For more on dataset formats, visit the Ultralytics documentation.

  6. johnlockejrrGitHub(수정됨)

    Yes, you are right, the solution is here https://docs.ultralytics.com/guides/isolating-segmentation-objects/#what-options-are-available-for-saving-the-isolated-objects-after-segmentation. Here is my code that does that (for anyone interested):

    from pathlib import Path
    
    import cv2
    import numpy as np
    
    from ultralytics import YOLO
    
    m = YOLO("/home/incognito/yolov8/runs/segment/train/weights/best.pt")
    res = m.predict("/home/incognito/yolov8/datasets/sam_v1/images/a34e234a-76be-5392-9b39-4abdcd051719.jpg")
    
    # Iterate detection results
    for r in res:
        img = np.copy(r.orig_img)
        img_name = Path(r.path).stem
    
        # Iterate each object contour
        for ci, c in enumerate(r):
            label = c.names[c.boxes.cls.tolist().pop()]
    
            b_mask = np.zeros(img.shape[:2], np.uint8)
    
            # Create contour mask
            contour = c.masks.xy.pop().astype(np.int32).reshape(-1, 1, 2)
            _ = cv2.drawContours(b_mask, [contour], -1, (255, 255, 255), cv2.FILLED)
    
            # Choose one:
    
            # OPTION-1: Isolate object with black background
            mask3ch = cv2.cvtColor(b_mask, cv2.COLOR_GRAY2BGR)
            isolated = cv2.bitwise_and(mask3ch, img)
    
            # OPTION-2: Isolate object with transparent background (when saved as PNG)
            #isolated = np.dstack([img, b_mask])
    
            # OPTIONAL: detection crop (from either OPT1 or OPT2)
            x1, y1, x2, y2 = c.boxes.xyxy.cpu().numpy().squeeze().astype(np.int32)
            iso_crop = isolated[y1:y2, x1:x2]
            cv2.imwrite(f"{img_name}_{ci}.jpg", iso_crop)

    The only problem is that the lines in page are random and not top-down in order. Is there a way to have them in order? As I read the ultralytics code the result is sorted by confidence (torch.argsort(scores, descending=True)), this, for segmenting lines of text in a page isn't helping, I should be able to sort it by masks location, from top down and left to right or right to left.

    1. Glenn JocherUltralytics

      @johnlockejrr to sort the results by mask location, you can modify your code to sort based on the bounding box coordinates. Extract the y-coordinate of the bounding boxes and sort the results accordingly. This will help you achieve a top-down order. If you need further assistance, feel free to ask!

    2. Glenn JocherUltralytics

      To sort the segmented objects by their location, you can modify your code to sort based on the y-coordinate of the bounding boxes. This will help you achieve a top-down order. If you need further assistance, feel free to ask!

  7. johnlockejrrGitHub

    @glenn-jocher, thank you for your help! I trained the model already and works pretty well, right now trying to figure out how to predict with it, I mean how to get back polygons so I forward them to a line recognition HTR (like PyLaia) for text recognition. I need to use the segmentation so I can cut the lines of text from the segmented image.

    My script:

    from ultralytics import YOLO
    # https://docs.ultralytics.com/modes/predict/#inference-arguments
    # Load a model
    model = YOLO("/home/incognito/yolov8/runs/segment/train4/weights/best.pt")  # pretrained YOLOv8n model
    
    # Run batched inference on a list of images
    results = model("29.jpg")  # return a list of Results objects
    
    # Process results list
    for result in results:
        boxes = result.boxes  # Boxes object for bounding box outputs
        masks = result.masks  # Masks object for segmentation masks outputs
        keypoints = result.keypoints  # Keypoints object for pose outputs
        probs = result.probs  # Probs object for classification outputs
        obb = result.obb  # Oriented boxes object for OBB outputs
        result.show()  # display to screen
        result.save(filename="result.jpg")  # save to disk

    My result.jpg

    result

    1. Glenn JocherUltralytics

      @johnlockejrr to extract polygons for line recognition, you can access the masks attribute in your results. This will give you the segmentation masks, which you can then process to obtain the polygon coordinates needed for your HTR system. If you need further details, please refer to the documentation on segmentation results processing.

  8. johnlockejrrGitHub(수정됨)

    I'm new to YOLO. I would like to convert my datasets for training a YOLOv8 model. My datasets are mainly in ALTO XML and PAGE XML formats (image/xml), the xml file contains polygons, any idea how to convert to YOLO format? Thank you!

    Example:

              <TextLine ID="eSc_line_48be6c40"
                        TAGREFS="LT46"
                        BASELINE="627 397 964 397 1713 373 2473 373"
                        HPOS="625"
                        VPOS="338"
                        WIDTH="1848"
                        HEIGHT="87">
                <Shape><Polygon POINTS="2470 351 2454 351 2438 349 2422 349 2407 348 2391 348 2375 346 2359 346 2344 345 2328 345 2312 343 2296 343 2281 343 2274 342 2254 345 2184 338 2183 338 2181 338 2158 349 2156 349 2139 349 1986 342 1984 342 1983 342 1959 349 1868 338 1855 340 1839 340 1823 340 1808 342 1792 342 1776 342 1775 342 1700 346 1655 345 1650 346 1634 346 1618 346 1603 346 1587 348 1571 348 1555 348 1540 349 1524 349 1508 349 1492 351 1477 351 1461 351 1445 351 1429 353 1414 353 1398 353 1382 354 1366 354 1350 354 1335 356 1319 356 1303 356 1287 356 1272 357 1256 357 1240 357 1224 359 1209 359 1193 359 1179 359 1179 360 1161 365 966 365 956 367 941 367 925 367 909 368 893 368 878 368 862 370 846 370 830 370 815 370 799 368 788 365 646 365 641 368 625 370 627 397 627 425 734 423 736 423 780 412 846 420 848 420 1111 419 1112 417 1295 403 1377 409 1379 409 1380 409 1410 400 1741 397 1820 397 1842 406 1844 406 1845 406 1847 406 1886 406 2128 397 2148 401 2159 403 2161 403 2162 403 2167 401 2184 392 2470 395 2473 373 2471 351 2470 351"/></Shape>
                <String CONTENT="את הארון ואת בדיו ואת הכפרת ואת פרכת המסך"
                        HPOS="625"
                        VPOS="338"
                        WIDTH="1848"
                        HEIGHT="87"></String>
              </TextLine>

    EDIT: I think this should do it: https://github.com/mittagessen/page2darknet

    1. Glenn JocherUltralytics

      @johnlockejrr to convert your ALTO XML and PAGE XML datasets to the YOLO format, you'll need to extract the polygon coordinates and class indices, then format them as <class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>. You might find the page2darknet tool helpful for this conversion. Once converted, ensure your dataset follows the YOLO format with a corresponding YAML file for training. For more details, you can refer to the Ultralytics documentation on dataset formats.

      1