Bắt đầu

Tổng quan về dataset hộp giới hạn xoay (OBB)

DOTA8 Multispectral preview 1
DOTA8 Multispectral preview 2
DOTA8 Multispectral preview 3
DOTA8 Multispectral preview 4
8
DOTA8 Multispectral
ultralytics
PublicOBB

Tiny 10-channel version of the DOTA8 aerial images for testing multispectral oriented-box pipelines, created by Ultralytics. Channels are synthesized by interpolating each RGB tile across the visible spectrum rather than captured by a multispectral sensor, so it exercises multi-channel loading, training, and export, not real spectral signal. Source: Xia, Bai, Ding, et al., "DOTA: A Large-Scale Dataset for Object Detection in Aerial Images," CVPR 2018; captain-whu.github.io/DOTA.

15 classes36 MBOct 23, 2026
planeshipstorage tankbaseball diamond+11
aerialobbremote-sensing+3

Huấn luyện model phát hiện đối tượng chính xác với bounding box xoay (OBB) đòi hỏi một bộ dữ liệu toàn diện. Hướng dẫn này giải thích các định dạng bộ dữ liệu OBB khác nhau tương thích với model Ultralytics YOLO, đồng thời cung cấp thông tin về cấu trúc, ứng dụng và phương pháp chuyển đổi định dạng.

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

Định dạng YOLO OBB#

Định dạng YOLO OBB biểu diễn hộp giới hạn bằng bốn điểm góc, với tọa độ được chuẩn hóa trong khoảng từ 0 đến 1. Định dạng này tuân theo cấu trúc sau:

class_index x1 y1 x2 y2 x3 y3 x4 y4

Trong nội bộ, YOLO xử lý loss và đầu ra ở định dạng xywhr, biểu diễn tâm của hộp giới hạn (xy), chiều rộng, chiều cao và góc xoay.

Oriented bounding box annotation format examples

Ví dụ về file nhãn *.txt cho ảnh trên, trong đó có một đối tượng thuộc lớp 0 ở định dạng OBB, có thể trông như sau:

0 0.780811 0.743961 0.782371 0.74686 0.777691 0.752174 0.776131 0.749758

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

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

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

# DOTA8 dataset (8 images from the DOTAv1 split) by Ultralytics
# Documentation: https://docs.ultralytics.com/datasets/obb/dota8
# Example usage: yolo train model=yolov8n-obb.pt data=dota8.yaml
# parent
# ├── ultralytics
# └── datasets
#     └── dota8 ← 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: dota8 # dataset root dir
train: images/train # train images (relative to 'path') 4 images
val: images/val # val images (relative to 'path') 4 images

# Classes for DOTA 1.0
names:
  0: plane
  1: ship
  2: storage tank
  3: baseball diamond
  4: tennis court
  5: basketball court
  6: ground track field
  7: harbor
  8: bridge
  9: large vehicle
  10: small vehicle
  11: helicopter
  12: roundabout
  13: soccer ball field
  14: swimming pool

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

Mỗi train, val và test 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/dota8 # 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: plane

Cách sử dụng#

Để huấn luyện model bằng các định dạng OBB này:

Ví dụ
from ultralytics import YOLO

# Tải model YOLO26n-OBB đã huấn luyện trước
model = YOLO("yolo26n-obb.pt")

# Huấn luyện model trên dataset DOTAv1
results = model.train(data="DOTAv1.yaml", epochs=100, imgsz=1024)

Dataset được hỗ trợ#

Hiện tại, các dataset có hộp giới hạn xoay sau đây được hỗ trợ. 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 xem ảnh và chú thích, xem thống kê dataset và sao chép dataset để huấn luyện trên cloud.

  • DOTA-v1: Phiên bản đầu tiên của dataset DOTA, cung cấp một tập hợp toàn diện các ảnh chụp từ trên không có hộp giới hạn xoay để phát hiện đối tượng.
  • DOTA-v1.5: Phiên bản trung gian của dataset DOTA, cung cấp thêm chú thích và cải tiến so với DOTA-v1 nhằm nâng cao các tác vụ phát hiện đối tượng.
  • DOTA-v2: Phiên bản 2 của DOTA (Dataset quy mô lớn để phát hiện đối tượng trong ảnh chụp từ trên không), tập trung vào phát hiện từ góc nhìn trên không và chứa các hộp giới hạn xoay với 1,7 triệu đối tượng trong 11.268 ảnh.
  • DOTA8: Tập con nhỏ gồm 8 ảnh của dataset DOTA đầy đủ, phù hợp để kiểm thử quy trình và kiểm tra Continuous Integration (CI) cho huấn luyện OBB trong repository ultralytics.
  • DOTA8 Multispectral: Tập con gồm 8 ảnh TIFF, 10 kênh, để kiểm thử huấn luyện OBB đa phổ trên Ultralytics Platform.
  • DOTA128: Tập con gồm 128 ảnh của dataset DOTA, trong đó tất cả ảnh nằm trong thư mục train (dùng cho cả train và val), tạo nên sự cân bằng phù hợp giữa kích thước và độ đa dạng để kiểm thử model OBB.
  • Văn bản trong cảnh: Bộ dữ liệu gồm 65.325 ảnh, kết hợp COCO-Text và HierText, với 1,29 triệu đa giác từ dễ đọc để huấn luyện OBB phát hiện văn bản trong cảnh.

Tích hợp dataset OBB của riêng bạn#

Nếu muốn đưa vào các dataset hộp giới hạn xoay của riêng mình, hãy đảm bảo chúng tương thích với "định dạng YOLO OBB" nêu trên. Chuyển đổi chú thích sang định dạng bắt buộc này, rồi khai báo đường dẫn, lớp và tên lớp trong file cấu hình YAML tương ứng.

Chuyển đổi định dạng nhãn#

Chuyển đổi định dạng dataset DOTA sang định dạng YOLO OBB#

Có thể chuyển đổi nhãn từ định dạng dataset DOTA sang định dạng YOLO OBB bằng script sau:

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

convert_dota_to_yolo_obb("path/to/DOTA")

Việc chuyển đổi này giúp các bộ dữ liệu định dạng DOTA tương thích với định dạng OBB của Ultralytics YOLO.

Xác thực để đảm bảo bộ dữ liệu đã chuyển đổi tuân theo quy ước định dạng YOLO OBB trước khi huấn luyện; cấu trúc bộ dữ liệu chính xác là yếu tố thiết yếu để huấn luyện các model phát hiện đối tượng chính xác với bounding box xoay.

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

  • Bounding box xoay (OBB) là một kiểu gán nhãn bounding box cho phép xoay khung để căn chỉnh sát hơn với đối tượng cần phát hiện, thay vì chỉ căn theo trục. Cách này đặc biệt hữu ích với ảnh chụp từ trên không hoặc ảnh vệ tinh, nơi các đối tượng có thể không song song với trục ảnh. Trong model Ultralytics YOLO, OBB được biểu diễn bằng bốn điểm góc theo định dạng YOLO OBB. Nhờ đó, việc phát hiện đối tượng chính xác hơn vì bounding box có thể xoay để khớp với đối tượng.

  • Bạn có thể chuyển nhãn bộ dữ liệu DOTA sang định dạng YOLO OBB bằng hàm convert_dota_to_yolo_obb của Ultralytics. Việc chuyển đổi này giúp nhãn tương thích với các model Ultralytics YOLO OBB. Dưới đây là ví dụ nhanh:

    from ultralytics.data.converter import convert_dota_to_yolo_obb
    
    convert_dota_to_yolo_obb("path/to/DOTA")

    Script này sẽ định dạng lại các chú thích DOTA của bạn sang định dạng tương thích với YOLO.

  • Huấn luyện model YOLO26 với OBB đòi hỏi dataset phải ở định dạng YOLO OBB, sau đó sử dụng API Ultralytics để huấn luyện model. Sau đây là ví dụ bằng cả Python và CLI:

    Ví dụ
    from ultralytics import YOLO
    
    # Tạo model YOLO26n-OBB mới từ đầu
    model = YOLO("yolo26n-obb.yaml")
    
    # Huấn luyện model trên dataset tùy chỉnh
    results = model.train(data="your_dataset.yaml", epochs=100, imgsz=640)

    Huấn luyện với nhãn OBB cho phép model khớp sát hơn với các đối tượng xoay, cải thiện độ chính xác phát hiện.

  • Hiện tại, Ultralytics hỗ trợ các dataset sau để huấn luyện OBB:

    • DOTA-v1: Phiên bản đầu tiên của dataset DOTA, cung cấp một tập hợp toàn diện các ảnh chụp từ trên không có hộp giới hạn xoay để phát hiện đối tượng.
    • DOTA-v1.5: Phiên bản trung gian của dataset DOTA, cung cấp thêm chú thích và cải tiến so với DOTA-v1 nhằm nâng cao các tác vụ phát hiện đối tượng.
    • DOTA-v2: Dataset này bao gồm 1,7 triệu đối tượng được gán nhãn bằng hộp giới hạn xoay và 11.268 ảnh, chủ yếu tập trung vào phát hiện đối tượng trên không.
    • DOTA8: Tập con nhỏ hơn gồm 8 ảnh của dataset DOTA, được dùng để kiểm thử và kiểm tra tích hợp liên tục (CI).
    • DOTA128: Tập con gồm 128 ảnh, tất cả đều nằm trong thư mục train (dùng cho cả train và val), đa dạng hơn DOTA8 nhưng vẫn dễ quản lý để phát triển model OBB và thử nghiệm ban đầu.
    • Văn bản trong cảnh: COCO-Text và HierText được kết hợp thành một bộ dữ liệu phát hiện văn bản trong cảnh một lớp, với chú thích từ được xoay và đa điểm.

    Các bộ dữ liệu này được thiết kế cho những tình huống OBB mang lại lợi thế đáng kể, chẳng hạn như ảnh chụp từ trên không và phân tích ảnh vệ tinh.

  • Có, bạn có thể dùng dataset riêng với hộp giới hạn xoay để huấn luyện YOLO26. Hãy đảm bảo các chú thích của dataset được chuyển đổi sang định dạng YOLO OBB, trong đó hộp giới hạn được xác định bằng bốn điểm góc. Sau đó, bạn có thể tạo file cấu hình YAML để chỉ định đường dẫn dataset, các lớp và những thông tin cần thiết khác. Để biết thêm thông tin về cách tạo và cấu hình dataset, hãy tham khảo mục Dataset được hỗ trợ.

Bình luận129

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

  1. hodat2608GitHub

    Hi everyone! i have a question. As we know, when i use labelimg obb to labeling images, it will export xywhr coordinates, example : 0 88.000000 101.000000 141.785406 14.314282 89.065522 0 477.548407 102.450004 140.874897 13.174511 -89.889658 0 218.000000 102.500000 140.785539 14.297973 89.065522

    but if i use this format for training it gives error, can not train, i think i need to convert this xywhr format to xyxyxyxy format. So I need to consult everyone, how to convert this format. thanks *note: we need to pay attention to the angle during labeling, because when we use label img obb, the angle will be output as negative and positive, which means if it is less than 90 degrees it is negative, if it is greater than 90 degrees it is positive. However, in YOLOv8 it will not be shown like that, it will output the result always positive, **for example : label img obb : -89 degrees < 90 degrees < 89 degrees yolov8 : 89 degrees < 90 degrees < 91 degrees i use this source : https://github.com/heshameraqi/labelImg_OBB

    1
    1. Chen-chang-yuGitHub

      Hi, I used roLabelImg-master to label and the output is xml file. Here is my convert code( from xml (xywhr fotmat) -> txt (xyxyxyxy format) ). For your reference.

      import math import xml.etree.ElementTree as ET import os

      def rotate_point(x, y, angle): """ Rotate point (x, y) by angle around origin (0, 0). """ x_rot = x * math.cos(angle) - y * math.sin(angle) y_rot = x * math.sin(angle) + y * math.cos(angle) return x_rot, y_rot

      def convert_to_xyxyxyxy(cx, cy, w, h, angle): """ Convert rotated bounding box to xyxyxyxy format. """ # Half width and height half_w = w / 2 half_h = h / 2

      # Corner points relative to center
      corners = [
          (-half_w, -half_h),
          (half_w, -half_h),
          (half_w, half_h),
          (-half_w, half_h)
      ]
      
      # Rotate corners and translate
      rotated_corners = []
      for corner in corners:
          x_rot, y_rot = rotate_point(corner[0], corner[1], angle)
          rotated_corners.append((cx + x_rot, cy + y_rot))
      
      # Format as xyxyxyxy
      xyxyxyxy = " ".join([f"{int(round(x))},{int(round(y))}" for x, y in rotated_corners])
      return xyxyxyxy

      def convert_annotation(xml_file_path, output_dir): tree = ET.parse(xml_file_path) root = tree.getroot()

      # Get image dimensions
      size = root.find('size')
      if size is None:
          raise ValueError("Size element not found in XML")
      
      width = int(size.find('width').text)
      height = int(size.find('height').text)
      
      class_id = int(root.find('segmented').text)
      
      # Create output file path
      base_name = os.path.splitext(os.path.basename(xml_file_path))[0]
      txt_file_path = os.path.join(output_dir, f"{base_name}.txt")
      
      with open(txt_file_path, 'w') as txt_file:
          for obj in root.findall('object'):
              robndbox = obj.find('robndbox')
      
              if robndbox is not None:
                  cx = float(robndbox.find('cx').text)
                  cy = float(robndbox.find('cy').text)
                  w = float(robndbox.find('w').text)
                  h = float(robndbox.find('h').text)
                  angle = float(robndbox.find('angle').text)
      
                  # Convert to OBB format
                  result = convert_to_xyxyxyxy(cx, cy, w, h, angle)
      
                  result = result.replace(",", " ")
                  # print(len(result))
      
                  # 分割字符串,去掉逗号并转换为浮点数,除以1024
                  normalized_results = [float(x) / 1024 for x in result.split()]
                  print(normalized_results)
      
                  # 将列表转换为字符串,元素用逗号和空格分隔
                  result_str = ' '.join(map(str, normalized_results))
      
                  # Write to file
                  txt_file.write(f"{class_id} {result_str}\n")
      
      # print(f"Converted {xml_file_path} to {txt_file_path}")

      Example usage

      xml_dir = r'C:\Users\datasets_HTC\xmllabels' output_dir = r'C:\Users\datasets_HTC\labels_OBB_format'

      Ensure the output directory exists

      os.makedirs(output_dir, exist_ok=True)

      Convert all XML files in the directory

      for xml_file in os.listdir(xml_dir): if xml_file.endswith('.xml'): convert_annotation( xml_file_path=os.path.join(xml_dir, xml_file), output_dir=output_dir, )

      1
    2. luo-rossGitHub

      No matter what annotation software you use for annotation, in the end, you only need to focus on xywhr. If it's detect, focus on xywh. If it's obb, then focus on xywhr. With this data, you can directly use the encapsulated methods provided in ultralytics. utilities

      from ultralytics.utils import ops

      For example, ops. xywhr 2xyxyxy (xywhr)

      You don't need to repeatedly make wheels and do so much work.

    3. luo-rossGitHub

      For appropriation, here is ready-made code, hoping it will be helpful to you

      from ultralytics import YOLO import time import torch import math import cv2 import numpy as np import ultralytics

      from ultralytics.utils import ops

      img=cv2.imread(r"yourfilename.png")

      #4 points x1y1=[550.0,400.0] x2y2=[450.0,400.0] x3y3=[450.0,600.0] x4y4=[550.0,600.0]

      Example bbox with rotation at 45 degrees (converted to radians if needed)

      r1=0 * np.pi / 180 r2=-45 * np.pi / 180 bbox = [500, 500, 200, 100, r1] # Convert degrees to radians xyxyxyxy =ops. xywhr2xyxyxyxy(torch.tensor(bbox)) xywhr=ops.xyxyxyxy2xywhr(xyxyxyxy.reshape(1,-1,2))

      rotate=xywhr[:,4]*180/np.pi #clockwise xywhr1=ops.xyxyxyxy2xywhr(torch.tensor([[x1y1,x2y2,x3y3,x4y4]])) xywhr2=ops.xyxyxyxy2xywhr(torch.tensor([[x2y2,x3y3,x4y4,x1y1]])) xywhr3=ops.xyxyxyxy2xywhr(torch.tensor([[x3y3,x4y4,x1y1,x2y2]])) xywhr4=ops.xyxyxyxy2xywhr(torch.tensor([[x4y4,x1y1,x2y2,x3y3]]))

      #anticlockwise xywhr5=ops.xyxyxyxy2xywhr(torch.tensor([[x1y1,x4y4,x3y3,x2y2]])) xywhr6=ops.xyxyxyxy2xywhr(torch.tensor([[x4y4,x3y3,x2y2,x1y1]])) xywhr7=ops.xyxyxyxy2xywhr(torch.tensor([[x3y3,x2y2,x1y1,x4y4]])) xywhr8=ops.xyxyxyxy2xywhr(torch.tensor([[x2y2,x1y1,x4y4,x3y3]]))

      r=[xywhr1[:,4],xywhr2[:,4],xywhr3[:,4],xywhr4[:,4],xywhr5[:,4],xywhr6[:,4],xywhr7[:,4],xywhr8[:,4]]

      #xyxyxyxy=ops.xywhr2xyxyxyxy(torch.tensor([161,152,100,170,math.radians(0)]))

      data_array=xyxyxyxy.to(torch.int32).cpu().numpy() cv2.drawContours(img, [data_array], -1, (255, 0, 0), 2)

      x=data_array[0][0] y=data_array[0][1] x1y1=[data_array[0][0], data_array[0][1]] x2y2=[data_array[1][0], data_array[1][1]] x3y3=[data_array[2][0], data_array[2][1]] x4y4=[data_array[3][0], data_array[3][1]]

      xywhr=ops.xyxyxyxy2xywhr(torch.tensor([[x1y1, x2y2,x3y3, x4y4]]).to(torch.float32))

      cv2.line(img, (x - 10, y), (x + 10, y), (0, 255, 0), 2) cv2.line(img, (x, y - 10), (x, y + 10), (0, 255, 0), 2)

      cv2.putText(img, "1", (data_array[0][0],data_array[0][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, lineType=cv2.LINE_AA) cv2.putText(img, "2", (data_array[1][0],data_array[1][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, lineType=cv2.LINE_AA) cv2.putText(img, "3", (data_array[2][0],data_array[2][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, lineType=cv2.LINE_AA) cv2.putText(img, "4", (data_array[3][0],data_array[3][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, lineType=cv2.LINE_AA) cv2.imshow('Rectangle', img) cv2.waitKey(0)

      #[tensor([1.5708]), tensor([1.5708]), tensor([1.5708]), tensor([1.5708]), tensor([1.5708]), tensor([1.5708]), tensor([1.5708]), tensor([1.5708])]

      sd2=ops.xywhr2xyxyxyxy(torch.tensor([500,500,200,100,math.radians(-90)]))

      sd3=ops.xywhr2xyxyxyxy(torch.tensor([500,500,200,100,math.radians(180)])) sd4=ops.xywhr2xyxyxyxy(torch.tensor([500,500,200,100,math.radians(270)])) sd5=ops.xywhr2xyxyxyxy(torch.tensor([500,500,200,100,math.radians(360)]))

      sd6=ops.xywhr2xyxyxyxy(torch.tensor([500,500,200,100,math.radians(45)]))

      radians=math.radians(-90)

      test1=ops.xyxyxyxy2xywhr(torch.tensor([[100, 100, 100, 461.999104, 911.0016, 272.999424, 1066.99776, 527.0016]])) test2=ops.xyxyxyxy2xywhr(torch.tensor([[ 640.999424, 461.999104, 911.0016, 272.999424, 1066.99776, 527.0016,797.999104, 706.999296]])) test3=ops.xyxyxyxy2xywhr(torch.tensor([[ 461.999104, 911.0016, 272.999424, 1066.99776, 527.0016,797.999104, 706.999296, 640.999424]])) test4=ops.xyxyxyxy2xywhr(torch.tensor([[706.999296, 640.999424,461.999104, 911.0016, 272.999424, 1066.99776, 527.0016,797.999104 ]]))

    4. hodat2608GitHub

      I have another question? I want to train with higher imgsz, so what size is best for practice? 832 or 1280 ?

    5. luo-rossGitHub

      @hodat2608 Unless your application scenario is microscopic, such as those captured under a microscope, requiring recognition of cells or bacteria, and requires precision at the pixel level. So when you train, you need to ensure the size of the image. For example, if a 2448 * 2048 size image is scaled to 640 * 640, it may not be able to recognize the target well. So you can use larger training sizes, such as twice, three times, or four times 640, or ensure that the size is a multiple of 2 for better results. Of course, the larger the size, the lower the efficiency. You need to use GPU for training and prediction.

    6. Glenn JocherUltralytics

      The best image size depends on your specific use case and hardware capabilities. Generally, larger sizes like 1280 can improve accuracy but require more computational resources. If you're limited by hardware, 832 might be a more practical choice.

    7. DeekshithaDPrakashGitHub

      Hi everyone! i have a question. As we know, when i use labelimg obb to labeling images, it will export xywhr coordinates, example : 0 88.000000 101.000000 141.785406 14.314282 89.065522 0 477.548407 102.450004 140.874897 13.174511 -89.889658 0 218.000000 102.500000 140.785539 14.297973 89.065522

      but if i use this format for training it gives error, can not train, i think i need to convert this xywhr format to xyxyxyxy format. So I need to consult everyone, how to convert this format. thanks *note: we need to pay attention to the angle during labeling, because when we use label img obb, the angle will be output as negative and positive, which means if it is less than 90 degrees it is negative, if it is greater than 90 degrees it is positive. However, in YOLOv8 it will not be shown like that, it will output the result always positive, **for example : label img obb : -89 degrees < 90 degrees < 89 degrees yolov8 : 89 degrees < 90 degrees < 91 degrees i use this source : https://github.com/heshameraqi/labelImg_OBB

      @hodat2608 Did you solve this issue and train yolo model for OBB ? It would be of great help if you could share relevant materials

  2. luckg6GitHub

    Hello Ultralytics team,

    I have a question regarding YOLO OBB (Oriented Bounding Box) object detection. I noticed that for predicted bounding boxes, the angle can be obtained via obb.xywhr. However, it seems that there is no direct way to get the angle of the ground-truth boxes in the dataset.

    Does this mean that if I want to calculate the angle error, I must manually compute it by converting the 8-point coordinates of the ground-truth boxes into an angle?

    Thank you for your clarification!

    1. Glenn JocherUltralytics

      GT labels in YOLO OBB are stored as 8 normalized corner coords (class x1 y1 ... x4 y4), so there’s no explicit angle field in the *.txt; if you want an angle/error metric, convert the GT corners to xywhr using the same helper Ultralytics uses internally via xyxyxyxy2xywhr (angle returned in radians), which matches how results[0].obb.xywhr is defined in the OBB results API and follows the OBB conventions noted in the OBB task docs.

      import cv2
      import math
      import torch
      from ultralytics.utils.ops import xyxyxyxy2xywhr
      
      img = cv2.imread("path/to/image.png")
      h, w = img.shape[:2]
      
      # label line: cls x1 y1 x2 y2 x3 y3 x4 y4  (all coords normalized 0-1)
      parts = open("path/to/label.txt").read().strip().split()
      pts = torch.tensor([float(x) for x in parts[1:]], dtype=torch.float32).view(1, 4, 2)
      pts[..., 0] *= w
      pts[..., 1] *= h
      
      gt_xywhr = xyxyxyxy2xywhr(pts.view(1, 8))
      gt_theta = gt_xywhr[0, 4].item()  # radians
      
      def angle_diff_rad(pred_theta, gt_theta):
          # smallest signed diff considering 90-degree periodicity used by OBB
          return (pred_theta - gt_theta + math.pi / 2) % math.pi - math.pi / 2

      If you have follow-ups on the exact angle convention for your evaluation, drop them here in this discussion so the team can see the context.

  3. ahrendsenGitHub

    Is it true that the YOLO implementation of OBB would report an identical result for objects that are rotated 180 degrees from each other? For example, if I wanted to detect planes flying through the air and wanted to determine the direction they were flying with the angle of the OBB, YOLO OBB would not be able to distinguish between the front and the back of the plane?

  4. msocodeGitHub

    I work with coffee bean classification. Until now, I was using yolov8-seg. However, I wanted some way to combine yolov11-obb + seg. Is there any way to run both processes together? Or would I have to do obb and then train the seg based on the previous result?

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      Great question—YOLO26 doesn’t currently provide a single multitask head that outputs OBB and masks together; OBB and Seg are separate tasks. The simplest way to get both is to run a YOLO26 segmentation model and derive an OBB per instance mask with OpenCV’s minAreaRect (one model, both outputs):

      from ultralytics import YOLO
      import numpy as np, cv2
      
      seg = YOLO("yolo26s-seg.pt")
      results = seg("image.jpg")[0]
      
      for poly in results.masks.xy:  # list of Nx2 polygons
          rect = cv2.minAreaRect(np.array(poly, dtype=np.float32))  # (cx,cy),(w,h),angle
          box = cv2.boxPoints(rect)  # 4x2 OBB corners
          # use box or rect as your OBB

      If you must use OBB first, a two-stage pipeline is fine: run yolo26*-obb.pt, crop/rotate ROIs, then run a yolo26*-seg.pt model on each ROI. See the Segmentation task guide and YOLO26 model variants in the docs: Segmentation docs and YOLO26 models.

      1
  5. UltralyticsAssistantGitHubUltralytics

    👋 Olá, obrigado pelo seu interesse nos modelos Ultralytics 🚀! Recomendamos uma visita à Documentação para novos utilizadores, onde pode encontrar vários exemplos de uso em Python e na CLI, além de respostas para as perguntas mais frequentes.

    Se este for um 🐛 Relatório de Bug, por favor forneça um exemplo mínimo reproduzível para nos ajudar a depurá-lo.

    Se for uma dúvida sobre treinamento personalizado ❓, forneça o máximo de informações possível, incluindo exemplos do conjunto de dados e logs de treinamento, e verifique se está seguindo as nossas Dicas para Melhores Resultados de Treinamento.

    Junte-se à comunidade Ultralytics onde preferir. Para conversas em tempo real, visite o Discord 🎧. Para discussões mais detalhadas, consulte o Discourse. Ou participe de discussões na nossa Subreddit para compartilhar conhecimento com outros membros.

    Atualização

    Atualize para a versão mais recente do pacote ultralytics, incluindo todos os requisitos, em um ambiente Python>=3.8 com PyTorch>=1.8, para verificar se o problema já não foi resolvido:

    pip install -U ultralytics

    Ambientes

    O YOLO pode ser executado em qualquer um dos seguintes ambientes atualizados e verificados (com todas as dependências, incluindo CUDA/CUDNN, Python e PyTorch pré-instalados):

    Status

    Ultralytics CI

    Se este badge estiver verde, todos os testes do Ultralytics CI estão a passar. Os testes CI verificam a operação correta de todos os Modos e Tarefas do YOLO em macOS, Windows e Ubuntu a cada 24 horas e a cada commit.

    Este é um comentário automatizado 🤖, mas um engenheiro da Ultralytics irá responder em breve para ajudar mais!

  6. jorgemarquesferreirajuniorGitHub

    Thank you so much! This article was very helpful for me. The OBB code works very well. Last year, I was trying to detect objects of my custom dataset and draw each oriented bounding box using OpenCV. It worked, but there were some issues with overlapping items. Using OBB perfomed by YOLO, my problems were solved.

  7. r-isrGitHub

    Hi, I'm working on reproducing MAP scores for YOLO OBB on DOTA 1.0 dataset. Despite experimenting with various batch sizes and nominal batch sizes on my 11GB GPU, the model's performance plateaus around MAP 60 on validation. The model:

    Training Configuration:

    • Used convert_dota_to_yolo_obb script for data preparation
    • Model: yolov8n-obb.yaml
    • Parameters:
      • Initial training: 20 epochs
      • Multiple additional 10-epoch iterations
      • image size: 1024
      • confidence threshold: 0.25
      • fraction: 0.5

    Despite trying different batch configurations and extending training through multiple iterations, the validation MAP consistently stalls at 60, well below the expected test score of 80.

    Questions:

    1. Are these results expected for validation performance?
    2. Would class balancing improve the results?
    3. Are my hardware limitations (11GB GPU) affecting performance?
    4. What's a reasonable MAP score to expect on the validation set?
    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @r-isr thank you for your detailed question. Here's a concise response:

      1. Validation vs Test Scores: DOTA validation scores often trail test scores due to different splits and evaluation protocols. Ensure you're using the official DOTA evaluation tools for comparable metrics (DOTA Dataset Guide).
      2. Epochs: Extend training to 100 epochs as shown in our DOTA training example - shorter runs may underfit.
      3. Hardware: While 11GB GPUs work, larger batch sizes (via batch=-1 for auto-scaling) often help stabilize training.
      4. Class Balance: DOTA's inherent class imbalance can impact results. Consider oversampling rare classes.

      For precise benchmarking, compare against the DOTAv1 results listed on the OBB task page using identical settings (those are test-set scores, reproduced with yolo obb val data=DOTAv1.yaml split=test nms=False save_json=True and the DOTA evaluation server). Let us know if you still observe discrepancies! 🚀

  8. fcndataGitHub

    With so much tools like SAM that allow us to better label, is it possible to train our model with polygons without transforming it into Bounding Boxes?

    1. Glenn JocherUltralytics

      @fcndata currently, YOLO models require annotations to follow specific formats like the YOLO OBB format for training. While SAM and similar tools can assist in creating precise polygon-based labels, these would need to be converted to bounding box formats (e.g., OBB) for YOLO compatibility. For details on conversion, please refer to the OBB Dataset Guide.

    2. fcndataGitHub

      I trust your expertise, but I came across a tutorial where they used polygon-based labels to train the model and the perform a comparison within different annotations formats on YOLOv8:

      Link to the blog

      On this analysis, they also present the overall coding here:

      Link to the tutorial

      In the tutorial, they use the following code snippet:

      !yolo task=detect mode=train model=yolov8n.yaml data={polygon_dataset.location}/data.yaml epochs=80 imgsz=640

      I reviewed the training dataset, and it follows the format of a dataset typically used for segmentation, where each annotation is structured as:

      ...

      Having said that, how do the they train the model with polygons.

      Thanks!

    3. Glenn JocherUltralytics

      Thank you for sharing the references. The tutorial you mentioned likely uses a segmentation dataset with polygon annotations converted to bounding boxes or masks during preprocessing. YOLO models, including YOLOv8 and YOLO11, require annotations in specific formats (e.g., standard bounding boxes or YOLO OBB format) for training. For polygon data, you would need to preprocess and transform the annotations into an appropriate format like bounding boxes or masks. If you'd like to explore polygon-based tasks further, tools like SAM can assist with segmentation tasks, but adaptation for YOLO training is still necessary. Let me know if you need more guidance!

  9. rihablahouarGitHub

    Issue with Incorrect Predictions from Quantized YOLOv8m-obb Model (TFLite) in TensorFlow Framework

    I have exported my YOLOv8m-obb model to TFLite format with INT8 quantization enabled, using an image size of 640x640 and a data.yaml for my dataset. When I use the quantized model for inference with the Ultralytics framework (Oriented Bounding Boxes), the predictions are correct. However, when I use the same model in the TensorFlow framework, I encounter several issues with the output:

    Confidence scores are greater than 1, which is incorrect.
    The class_id is either -1 or 0, but it should be 0 or 1 since I have only two classes.
    The x and y coordinates have values of -1, which is wrong.

    I suspect there might be an issue with how the quantization parameters (scale and zero-point) are being applied in TensorFlow, or possibly with the way I'm handling the model's output or the way I exported the model. I would appreciate guidance on how to correctly handle the quantized model in TensorFlow and resolve the issues with incorrect predictions.

    1. Glenn JocherUltralytics

      @rihablahouar the issue likely arises due to differences in how TensorFlow interprets or handles the quantized TFLite model's outputs. Ensure that the post-processing operations (like decoding bounding boxes, confidence scores, and class indices) align with the model's export format and scale/zero-point quantization parameters. Additionally, verify the TensorFlow inference pipeline against the Ultralytics implementation for any discrepancies. For further debugging, you may find it useful to test the unquantized TFLite model in TensorFlow to isolate the quantization's impact.