Bắt đầu

Tổng quan về dataset Instance Segmentation

Phân đoạn instance là tác vụ thị giác máy tính nhằm xác định và phân định từng đối tượng riêng lẻ trong hình ảnh. Hướng dẫn này tổng quan về các định dạng dataset được Ultralytics YOLO hỗ trợ cho tác vụ phân đoạn instance, đồng thời hướng dẫn cách chuẩn bị, chuyển đổi và sử dụng các dataset này để huấn luyện model.

Các định dạng dataset được hỗ trợ#

Định dạng Ultralytics YOLO#

Định dạng nhãn dataset được sử dụng để huấn luyện model segmentation YOLO như sau:

  1. Một tệp văn bản cho mỗi ảnh: Mỗi ảnh trong dataset có một tệp văn bản tương ứng, mang cùng tên với tệp ảnh và có phần mở rộng ".txt".
  2. Một dòng cho mỗi đối tượng: Mỗi dòng trong tệp văn bản tương ứng với một đối tượng trong ảnh.
  3. Thông tin đối tượng trên mỗi dòng: Mỗi dòng chứa thông tin sau về đối tượng:
    • Chỉ số lớp của đối tượng: Số nguyên biểu thị lớp của đối tượng (ví dụ: 0 cho người, 1 cho ô tô, v.v.).
    • Tọa độ polygon của đối tượng: Các điểm (x, y) xác định đường bao mask của đối tượng, được chuẩn hóa trong khoảng từ 0 đến 1.

Định dạng của một dòng trong tệp dataset segmentation như sau:

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

Trong định dạng này, <class-index> là chỉ số lớp của đối tượng, còn <x1> <y1> <x2> <y2> ... <xn> <yn> là tọa độ polygon đã chuẩn hóa của mask segmentation của đối tượng (các giá trị nằm trong [0, 1] theo chiều rộng và chiều cao của ảnh). Các tọa độ được phân tách bằng dấu cách.

Dưới đây là ví dụ về định dạng dataset YOLO cho một ảnh đơn có hai đối tượng, lần lượt gồm một segment 3 điểm và một segment 5 điểm.

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
Mẹo
  • Độ dài của mỗi dòng không nhất thiết phải bằng nhau.
  • Mỗi nhãn segmentation phải có tối thiểu 3 điểm (x, y): <class-index> <x1> <y1> <x2> <y2> <x3> <y3>
  • Mỗi object cần có polygon. Các hàng ở định dạng detect (<class-index> <x_center> <y_center> <width> <height>) không có polygon, và dataset segmentation có số lượng box và polygon không khớp sẽ bị từ chối với ValueError khi tải nhãn.

Định dạng YAML của dataset#

Framework Ultralytics sử dụng định dạng tệp YAML để xác định cấu hình dataset và model khi huấn luyện model phân đoạn. Sau đây là ví dụ về định dạng YAML dùng để khai báo dataset phân đoạn:

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

Các trường train, val và test trỏ đến ảnh huấn luyện, xác thực và kiểm thử. Mỗi trường chấp nhận một thư mục, một tệp ảnh, danh sách thư mục hoặc tệp ảnh, hoặc tệp *.txt mã hóa UTF-8, liệt kê mỗi đường dẫn ảnh trên một dòng (các đường dẫn bắt đầu bằng ./ được phân giải tương đối với tệp *.txt). Tệp *.txt hữu ích khi huấn luyện trên một tập con của thư mục, bỏ qua ảnh chưa được gán nhãn hoặc kết hợp ảnh từ nhiều nguồn vào cùng một split.

Đường dẫn ảnh trong tệp `*.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 là một dictionary chứa tên các class. Thứ tự tên phải khớp với thứ tự chỉ số class của object trong các file dataset YOLO.

Cách sử dụng#

Ví dụ
from ultralytics import YOLO

# Tải model
model = YOLO("yolo26n-seg.pt")  # tải model đã huấn luyện trước (được khuyến nghị khi huấn luyện)

# Huấn luyện model
results = model.train(data="coco8-seg.yaml", epochs=100, imgsz=640)

Dataset được hỗ trợ#

Ultralytics YOLO hỗ trợ nhiều dataset cho các tác vụ instance segmentation. Sau đây là danh sách những dataset được sử dụng phổ biến nhất. Hầu hết các dataset này cũng được lưu trữ trên Ultralytics Platform, nơi bạn có thể duyệt ảnh và annotation, xem thống kê dataset và sao chép dataset để huấn luyện trên cloud.

  • Carparts-seg: Dataset chuyên biệt tập trung vào segmentation các bộ phận ô tô, lý tưởng cho các ứng dụng trong ngành ô tô. Dataset bao gồm nhiều loại xe với annotation chi tiết cho từng bộ phận.
  • COCO: Dataset toàn diện phục vụ phát hiện object, segmentation và tạo chú thích, gồm hơn 200K ảnh được gán nhãn thuộc nhiều danh mục.
  • COCO8-seg: Tập con nhỏ gọn gồm 8 ảnh từ COCO, được thiết kế để kiểm thử nhanh quá trình huấn luyện model segmentation, lý tưởng cho các bước kiểm tra CI và xác thực workflow trong repository ultralytics.
  • COCO128-seg: Dataset nhỏ dành cho các tác vụ phân đoạn đối tượng, gồm tập con 128 ảnh COCO có chú thích phân đoạn.
  • Crack-seg: Dataset dành riêng cho segmentation vết nứt trên nhiều bề mặt. Dataset này rất cần thiết cho việc bảo trì cơ sở hạ tầng và kiểm soát chất lượng, cung cấp hình ảnh chi tiết để huấn luyện model nhận diện điểm yếu kết cấu.
  • Package-seg: Dataset dành riêng cho segmentation nhiều loại vật liệu và hình dạng bao bì. Dataset đặc biệt hữu ích trong logistics và tự động hóa kho hàng, hỗ trợ phát triển các hệ thống xử lý và phân loại kiện hàng.

Thêm dataset của riêng bạn#

Nếu có dataset riêng và muốn dùng dataset đó để huấn luyện model segmentation theo định dạng Ultralytics YOLO, hãy đảm bảo dataset tuân theo định dạng được mô tả ở trên trong phần "Định dạng Ultralytics YOLO". Chuyển đổi annotation sang định dạng bắt buộc và chỉ định đường dẫn, số lượng class cùng tên class trong file cấu hình YAML. Giữ images/ và labels/ trong các thư mục riêng biệt ở cùng cấp, với cấu trúc thư mục con khớp nhau; đặt các file nhãn .txt trong thư mục ảnh có thể khiến model bỏ sót nhãn.

Chuyển đổi hoặc chuyển đổi định dạng nhãn#

Chuyển định dạng dataset COCO sang định dạng YOLO#

Bạn có thể chuyển đổi nhãn từ định dạng dataset COCO phổ biến sang định dạng YOLO bằng đoạn mã sau:

Ví dụ
from ultralytics.data.converter import convert_coco

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

Có thể sử dụng công cụ chuyển đổi này để chuyển dataset COCO hoặc bất kỳ dataset nào ở định dạng COCO sang định dạng Ultralytics YOLO.

Hãy nhớ kiểm tra kỹ xem dataset bạn muốn sử dụng có tương thích với model và tuân theo các quy ước định dạng cần thiết hay không. Dataset được định dạng đúng là yếu tố quan trọng để huấn luyện model segmentation hiệu quả.

Tự động gán nhãn#

Tự động gán nhãn tạo dataset phân đoạn từ model phát hiện đã tiền huấn luyện, nhờ đó bạn có thể gán nhãn cho nhiều hình ảnh mà không cần tự vẽ từng mask. Nếu muốn gán nhãn trực tiếp trên trình duyệt, Ultralytics Platform cung cấp tính năng gán nhãn thông minh bằng SAM, YOLO và prompt lớp; bảng xếp hạng VLM so sánh các model dùng prompt về độ chính xác phát hiện, chi phí và tốc độ.

Tạo Dataset Segmentation bằng Model Phát hiện#

Để tự động gán nhãn cho dataset bằng framework Ultralytics, bạn có thể sử dụng hàm auto_annotate như minh họa bên dưới:

Ví dụ
from ultralytics.data.annotator import auto_annotate

auto_annotate(data="path/to/images", det_model="yolo26x.pt", sam_model="sam_b.pt")
Đối sốKiểuMặc địnhMô tả
datastrbắt buộcĐường dẫn đến thư mục chứa ảnh mục tiêu cần chú thích hoặc phân đoạn.
det_modelstr'yolo26x.pt'Đường dẫn đến model phát hiện YOLO để phát hiện đối tượng ban đầu.
sam_modelstr'sam_b.pt'Đường dẫn đến model SAM để phân đoạn (hỗ trợ các weight của SAM, SAM 2, MobileSAM và SAM 3).
devicestr''Thiết bị tính toán (ví dụ: 'cuda:0', 'cpu' hoặc '' để tự động phát hiện thiết bị).
conffloat0.25Ngưỡng confidence của model phát hiện YOLO để lọc các kết quả phát hiện yếu.
ioufloat0.5Ngưỡng IoU cho Non-Maximum Suppression để lọc các hộp chồng lấn.
imgszint640Kích thước đầu vào để thay đổi kích thước ảnh (nếu cần, làm tròn lên bội số của 32).
max_detint300Số lượng kết quả phát hiện tối đa trên mỗi ảnh để tiết kiệm bộ nhớ.
classeslist[int]NoneDanh sách chỉ số class cần phát hiện (ví dụ: [0, 1] cho người và xe đạp).
output_dirstrNoneThư mục lưu chú thích (mặc định: thư mục cùng cấp với <data>_auto_annotate_labels).

Hàm auto_annotate nhận đường dẫn đến ảnh của bạn cùng các đối số tùy chọn để chỉ định model phát hiện đã được pretrained, chẳng hạn như YOLO26, YOLO11 hoặc các model khác; model segmentation, chẳng hạn như SAM, SAM 2, MobileSAM hoặc SAM 3; thiết bị chạy các model; và thư mục đầu ra để lưu kết quả đã gán nhãn.

Việc sử dụng model tiền huấn luyện để tự động gán nhãn giúp giảm đáng kể thời gian và công sức cần thiết để tạo dataset phân đoạn chất lượng cao. Điều này đặc biệt hữu ích cho các nhà nghiên cứu và nhà phát triển làm việc với bộ sưu tập hình ảnh lớn, vì cho phép họ tập trung vào phát triển và đánh giá model thay vì gán nhãn thủ công.

Trực quan hóa chú thích dataset#

Trước khi huấn luyện model, bạn thường nên trực quan hóa annotation của dataset để đảm bảo annotation chính xác. Ultralytics cung cấp một hàm tiện ích cho mục đích này. Hàm chỉ đọc nhãn box ở định dạng detect (<class-index> <x_center> <y_center> <width> <height>), vì vậy không thể phân tích cú pháp các file nhãn polygon segmentation:

from ultralytics.data.utils import visualize_image_annotations

label_map = {  # Định nghĩa ánh xạ nhãn với tất cả nhãn lớp đã được chú thích.
    0: "person",
    1: "car",
}

# Visualize
visualize_image_annotations(
    "path/to/image.jpg",  # Đường dẫn ảnh đầu vào.
    "path/to/annotations.txt",  # Đường dẫn tệp chú thích của ảnh.
    label_map,
)

Hàm này vẽ bounding box, gắn nhãn object bằng tên class và điều chỉnh màu văn bản để dễ đọc hơn, giúp bạn xác định và sửa lỗi annotation trước khi huấn luyện.

Chuyển đổi Mask Segmentation sang Định dạng YOLO#

Nếu bạn có ảnh mask grayscale trong đó giá trị pixel là chỉ số class + 1 (0 là nền), bạn có thể chuyển đổi ảnh sang định dạng segmentation YOLO bằng cách sử dụng:

from ultralytics.data.converter import convert_segment_masks_to_yolo_seg

# Dành cho các dataset như COCO có 80 class
convert_segment_masks_to_yolo_seg(masks_dir="path/to/masks_dir", output_dir="path/to/output_dir", classes=80)

Tiện ích này chuyển đổi ảnh mask sang định dạng segmentation YOLO và lưu vào thư mục đầu ra được chỉ định.

Câu hỏi thường gặp#

  • Ultralytics YOLO hỗ trợ nhiều định dạng dataset cho phân đoạn đối tượng, trong đó định dạng chính là định dạng Ultralytics YOLO. Mỗi ảnh trong dataset cần có một file văn bản tương ứng chứa thông tin đối tượng được phân đoạn thành nhiều dòng (mỗi đối tượng một dòng), liệt kê chỉ số lớp và tọa độ đa giác đã chuẩn hóa.

  • Có thể dễ dàng chuyển annotation từ định dạng COCO sang định dạng YOLO bằng các công cụ Ultralytics. Bạn có thể sử dụng hàm convert_coco từ module ultralytics.data.converter:

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

    Script này chuyển annotation của dataset COCO sang định dạng YOLO bắt buộc, giúp dataset phù hợp để huấn luyện model YOLO. Để biết thêm chi tiết, hãy tham khảo Chuyển hoặc Chuyển đổi Định dạng Nhãn.

  • Để chuẩn bị file YAML huấn luyện model YOLO bằng Ultralytics, bạn cần xác định đường dẫn dataset và tên class. Sau đây là ví dụ cấu hình 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

    Hãy cập nhật đường dẫn và tên class cho phù hợp với dataset của bạn. Để biết thêm thông tin, hãy xem phần Định dạng YAML của Dataset.

  • Tính năng tự động gán nhãn trong Ultralytics YOLO cho phép bạn tạo annotation segmentation cho dataset bằng model phát hiện đã được pretrained. Tính năng này giảm đáng kể nhu cầu gán nhãn thủ công. Bạn có thể sử dụng hàm auto_annotate như sau:

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

    Hàm này tự động hóa quy trình gán nhãn, giúp quy trình nhanh hơn và hiệu quả hơn. Để biết thêm chi tiết, hãy xem Tài liệu tham khảo về Tự động Gán nhãn.

Bình luận80

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  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(đã chỉnh sửa)

      @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. johnlockejrrGitHub

      90% ok, most of the lines are in the correct position, some are not... I sorted by x1, was I wrong?

    2. 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(đã chỉnh sửa)

    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(đã chỉnh sửa)

    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