diff --git a/docs/en/datasets/classify/cifar10.md b/docs/en/datasets/classify/cifar10.md
index b4742cbcb7..54f9e9c2d4 100644
--- a/docs/en/datasets/classify/cifar10.md
+++ b/docs/en/datasets/classify/cifar10.md
@@ -153,14 +153,18 @@ Each subset comprises images categorized into 10 classes, with their annotations
If you use the CIFAR-10 dataset in your research or development projects, make sure to cite the following paper:
-```bibtex
-@TECHREPORT{Krizhevsky09learningmultiple,
- author={Alex Krizhevsky},
- title={Learning multiple layers of features from tiny images},
- institution={},
- year={2009}
-}
-```
+!!! Quote ""
+
+ === "BibTeX"
+
+ ```bibtex
+ @TECHREPORT{Krizhevsky09learningmultiple,
+ author={Alex Krizhevsky},
+ title={Learning multiple layers of features from tiny images},
+ institution={},
+ year={2009}
+ }
+ ```
Acknowledging the dataset's creators helps support continued research and development in the field. For more details, see the [citations and acknowledgments](#citations-and-acknowledgments) section.
diff --git a/docs/en/datasets/classify/imagewoof.md b/docs/en/datasets/classify/imagewoof.md
index 5a76d97fc2..e6668dfcb7 100644
--- a/docs/en/datasets/classify/imagewoof.md
+++ b/docs/en/datasets/classify/imagewoof.md
@@ -59,18 +59,29 @@ ImageWoof dataset comes in three different sizes to accommodate various research
To use these variants in your training, simply replace 'imagewoof' in the dataset argument with 'imagewoof320' or 'imagewoof160'. For example:
-```python
-from ultralytics import YOLO
+!!! Example "Example"
-# Load a model
-model = YOLO("yolov8n-cls.pt") # load a pretrained model (recommended for training)
+ === "Python"
+
+ ```python
+ from ultralytics import YOLO
+
+ # Load a model
+ model = YOLO("yolov8n-cls.pt") # load a pretrained model (recommended for training)
-# For medium-sized dataset
-model.train(data="imagewoof320", epochs=100, imgsz=224)
+ # For medium-sized dataset
+ model.train(data="imagewoof320", epochs=100, imgsz=224)
-# For small-sized dataset
-model.train(data="imagewoof160", epochs=100, imgsz=224)
-```
+ # For small-sized dataset
+ model.train(data="imagewoof160", epochs=100, imgsz=224)
+ ```
+
+ === "CLI"
+
+ ```bash
+ # Load a pretrained model and train on the small-sized dataset
+ yolo classify train model=yolov8n-cls.pt data=imagewoof320 epochs=100 imgsz=224
+ ```
It's important to note that using smaller images will likely yield lower performance in terms of classification accuracy. However, it's an excellent way to iterate quickly in the early stages of model development and prototyping.
diff --git a/docs/en/datasets/detect/roboflow-100.md b/docs/en/datasets/detect/roboflow-100.md
index d8c61c37c9..541f8e8e56 100644
--- a/docs/en/datasets/detect/roboflow-100.md
+++ b/docs/en/datasets/detect/roboflow-100.md
@@ -203,7 +203,7 @@ The **Roboflow 100** dataset is accessible on [GitHub](https://github.com/robofl
When using the Roboflow 100 dataset in your research, ensure to properly cite it. Here is the recommended citation:
-!!! Quote
+!!! Quote ""
=== "BibTeX"
diff --git a/docs/en/datasets/detect/visdrone.md b/docs/en/datasets/detect/visdrone.md
index 00d84b10e9..fab2fe80f4 100644
--- a/docs/en/datasets/detect/visdrone.md
+++ b/docs/en/datasets/detect/visdrone.md
@@ -159,16 +159,19 @@ The configuration file for the VisDrone dataset, `VisDrone.yaml`, can be found i
If you use the VisDrone dataset in your research or development work, please cite the following paper:
-!!! Quote "BibTeX"
-
- ```bibtex
- @ARTICLE{9573394,
- author={Zhu, Pengfei and Wen, Longyin and Du, Dawei and Bian, Xiao and Fan, Heng and Hu, Qinghua and Ling, Haibin},
- journal={IEEE Transactions on Pattern Analysis and Machine Intelligence},
- title={Detection and Tracking Meet Drones Challenge},
- year={2021},
- volume={},
- number={},
- pages={1-1},
- doi={10.1109/TPAMI.2021.3119563}}
- ```
+!!! Quote ""
+
+ === "BibTeX"
+
+ ```bibtex
+ @ARTICLE{9573394,
+ author={Zhu, Pengfei and Wen, Longyin and Du, Dawei and Bian, Xiao and Fan, Heng and Hu, Qinghua and Ling, Haibin},
+ journal={IEEE Transactions on Pattern Analysis and Machine Intelligence},
+ title={Detection and Tracking Meet Drones Challenge},
+ year={2021},
+ volume={},
+ number={},
+ pages={1-1},
+ doi={10.1109/TPAMI.2021.3119563}
+ }
+ ```
diff --git a/docs/en/datasets/explorer/explorer.ipynb b/docs/en/datasets/explorer/explorer.ipynb
index bd00867b2b..3424753341 100644
--- a/docs/en/datasets/explorer/explorer.ipynb
+++ b/docs/en/datasets/explorer/explorer.ipynb
@@ -13,7 +13,7 @@
" \n",
" \n",
"\n",
- " [中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [हिन्दी](https://docs.ultralytics.com/hi/) | [العربية](https://docs.ultralytics.com/ar/)\n",
+ " [中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [العربية](https://docs.ultralytics.com/ar/)\n",
"\n",
" \n",
" \n",
@@ -598,4 +598,4 @@
},
"nbformat": 4,
"nbformat_minor": 5
-}
\ No newline at end of file
+}
diff --git a/docs/en/datasets/segment/crack-seg.md b/docs/en/datasets/segment/crack-seg.md
index 2dd8972639..83f019871f 100644
--- a/docs/en/datasets/segment/crack-seg.md
+++ b/docs/en/datasets/segment/crack-seg.md
@@ -135,19 +135,23 @@ Ultralytics YOLO offers advanced real-time object detection, segmentation, and c
If you incorporate the Crack Segmentation Dataset into your research, please use the following BibTeX reference:
-```bibtex
-@misc{ crack-bphdr_dataset,
- title = { crack Dataset },
- type = { Open Source Dataset },
- author = { University },
- howpublished = { \url{ https://universe.roboflow.com/university-bswxt/crack-bphdr } },
- url = { https://universe.roboflow.com/university-bswxt/crack-bphdr },
- journal = { Roboflow Universe },
- publisher = { Roboflow },
- year = { 2022 },
- month = { dec },
- note = { visited on 2024-01-23 },
-}
-```
+!!! Quote ""
+
+ === "BibTeX"
+
+ ```bibtex
+ @misc{ crack-bphdr_dataset,
+ title = { crack Dataset },
+ type = { Open Source Dataset },
+ author = { University },
+ howpublished = { \url{ https://universe.roboflow.com/university-bswxt/crack-bphdr } },
+ url = { https://universe.roboflow.com/university-bswxt/crack-bphdr },
+ journal = { Roboflow Universe },
+ publisher = { Roboflow },
+ year = { 2022 },
+ month = { dec },
+ note = { visited on 2024-01-23 },
+ }
+ ```
This citation format ensures proper accreditation to the creators of the dataset and acknowledges its use in your research.
diff --git a/docs/en/datasets/segment/package-seg.md b/docs/en/datasets/segment/package-seg.md
index af4f90a51c..86fad9e9b4 100644
--- a/docs/en/datasets/segment/package-seg.md
+++ b/docs/en/datasets/segment/package-seg.md
@@ -99,24 +99,28 @@ The [Roboflow Package Segmentation Dataset](https://universe.roboflow.com/factor
### How do I train an Ultralytics YOLOv8 model on the Package Segmentation Dataset?
-You can train an Ultralytics YOLOv8n model using both Python and CLI methods. For Python, use the snippet below:
+You can train an Ultralytics YOLOv8n model using both Python and CLI methods. Use the snippets below:
-```python
-from ultralytics import YOLO
+!!! Example "Train Example"
-# Load a model
-model = YOLO("yolov8n-seg.pt") # load a pretrained model
+ === "Python"
+
+ ```python
+ from ultralytics import YOLO
-# Train the model
-results = model.train(data="package-seg.yaml", epochs=100, imgsz=640)
-```
+ # Load a model
+ model = YOLO("yolov8n-seg.pt") # load a pretrained model
-For CLI:
+ # Train the model
+ results = model.train(data="package-seg.yaml", epochs=100, imgsz=640)
+ ```
-```bash
-# Start training from a pretrained *.pt model
-yolo segment train data=package-seg.yaml model=yolov8n-seg.pt epochs=100 imgsz=640
-```
+ === "CLI"
+
+ ```bash
+ # Start training from a pretrained *.pt model
+ yolo segment train data=package-seg.yaml model=yolov8n-seg.pt epochs=100 imgsz=640
+ ```
Refer to the model [Training](../../modes/train.md) page for more details.
diff --git a/docs/en/guides/kfold-cross-validation.md b/docs/en/guides/kfold-cross-validation.md
index ce51de30ab..6fb2f38604 100644
--- a/docs/en/guides/kfold-cross-validation.md
+++ b/docs/en/guides/kfold-cross-validation.md
@@ -82,7 +82,7 @@ Without further ado, let's dive in!
```python
import pandas as pd
- indx = [l.stem for l in labels] # uses base filename as ID (no extension)
+ indx = [label.stem for label in labels] # uses base filename as ID (no extension)
labels_df = pd.DataFrame([], columns=cls_idx, index=indx)
```
@@ -97,9 +97,9 @@ Without further ado, let's dive in!
with open(label, "r") as lf:
lines = lf.readlines()
- for l in lines:
+ for line in lines:
# classes for YOLO label uses integer at first position of each line
- lbl_counter[int(l.split(" ")[0])] += 1
+ lbl_counter[int(line.split(" ")[0])] += 1
labels_df.loc[label.stem] = lbl_counter
diff --git a/docs/en/guides/parking-management.md b/docs/en/guides/parking-management.md
index 1532938db4..cc42fb9b45 100644
--- a/docs/en/guides/parking-management.md
+++ b/docs/en/guides/parking-management.md
@@ -10,6 +10,17 @@ keywords: parking management, YOLOv8, Ultralytics, vehicle detection, real-time
Parking management with [Ultralytics YOLOv8](https://github.com/ultralytics/ultralytics/) ensures efficient and safe parking by organizing spaces and monitoring availability. YOLOv8 can improve parking lot management through real-time vehicle detection, and insights into parking occupancy.
+
\n",
"\n",
- "[中文](https://docs.ultralytics.com/zh/hub/) | [한국어](https://docs.ultralytics.com/ko/hub/) | [日本語](https://docs.ultralytics.com/ja/hub/) | [Русский](https://docs.ultralytics.com/ru/hub/) | [Deutsch](https://docs.ultralytics.com/de/hub/) | [Français](https://docs.ultralytics.com/fr/hub/) | [Español](https://docs.ultralytics.com/es/hub/) | [Português](https://docs.ultralytics.com/pt/hub/) | [Türkçe](https://docs.ultralytics.com/tr/hub/) | [Tiếng Việt](https://docs.ultralytics.com/vi/hub/) | [हिन्दी](https://docs.ultralytics.com/hi/hub/) | [العربية](https://docs.ultralytics.com/ar/hub/)\n",
+ "[中文](https://docs.ultralytics.com/zh/hub/) | [한국어](https://docs.ultralytics.com/ko/hub/) | [日本語](https://docs.ultralytics.com/ja/hub/) | [Русский](https://docs.ultralytics.com/ru/hub/) | [Deutsch](https://docs.ultralytics.com/de/hub/) | [Français](https://docs.ultralytics.com/fr/hub/) | [Español](https://docs.ultralytics.com/es/hub/) | [Português](https://docs.ultralytics.com/pt/hub/) | [Türkçe](https://docs.ultralytics.com/tr/hub/) | [Tiếng Việt](https://docs.ultralytics.com/vi/hub/) | [العربية](https://docs.ultralytics.com/ar/hub/)\n",
"\n",
"
\n",
" \n",
diff --git a/pyproject.toml b/pyproject.toml
index 4fe7bfb91b..4015161c78 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -171,6 +171,12 @@ split_before_first_argument = false
[tool.ruff]
line-length = 120
+[tool.ruff.format]
+docstring-code-format = true
+
+[tool.ruff.lint.pydocstyle]
+convention = "google"
+
[tool.docformatter]
wrap-summaries = 120
wrap-descriptions = 120
diff --git a/ultralytics/__init__.py b/ultralytics/__init__.py
index 93ca50b1ac..5d7906d07e 100644
--- a/ultralytics/__init__.py
+++ b/ultralytics/__init__.py
@@ -1,6 +1,6 @@
# Ultralytics YOLO 🚀, AGPL-3.0 license
-__version__ = "8.2.79"
+__version__ = "8.2.81"
import os
diff --git a/ultralytics/cfg/__init__.py b/ultralytics/cfg/__init__.py
index 628e1ce683..263b8a19b7 100644
--- a/ultralytics/cfg/__init__.py
+++ b/ultralytics/cfg/__init__.py
@@ -198,15 +198,15 @@ def cfg2dict(cfg):
Examples:
Convert a YAML file path to a dictionary:
- >>> config_dict = cfg2dict('config.yaml')
+ >>> config_dict = cfg2dict("config.yaml")
Convert a SimpleNamespace to a dictionary:
>>> from types import SimpleNamespace
- >>> config_sn = SimpleNamespace(param1='value1', param2='value2')
+ >>> config_sn = SimpleNamespace(param1="value1", param2="value2")
>>> config_dict = cfg2dict(config_sn)
Pass through an already existing dictionary:
- >>> config_dict = cfg2dict({'param1': 'value1', 'param2': 'value2'})
+ >>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})
Notes:
- If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
@@ -235,7 +235,7 @@ def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, ove
Examples:
>>> from ultralytics.cfg import get_cfg
>>> config = get_cfg() # Load default configuration
- >>> config = get_cfg('path/to/config.yaml', overrides={'epochs': 50, 'batch_size': 16})
+ >>> config = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})
Notes:
- If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
@@ -282,10 +282,10 @@ def check_cfg(cfg, hard=True):
Examples:
>>> config = {
- ... 'epochs': 50, # valid integer
- ... 'lr0': 0.01, # valid float
- ... 'momentum': 1.2, # invalid float (out of 0.0-1.0 range)
- ... 'save': 'true', # invalid bool
+ ... "epochs": 50, # valid integer
+ ... "lr0": 0.01, # valid float
+ ... "momentum": 1.2, # invalid float (out of 0.0-1.0 range)
+ ... "save": "true", # invalid bool
... }
>>> check_cfg(config, hard=False)
>>> print(config)
@@ -345,7 +345,7 @@ def get_save_dir(args, name=None):
Examples:
>>> from types import SimpleNamespace
- >>> args = SimpleNamespace(project='my_project', task='detect', mode='train', exist_ok=True)
+ >>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
>>> save_dir = get_save_dir(args)
>>> print(save_dir)
my_project/detect/train
@@ -413,8 +413,8 @@ def check_dict_alignment(base: Dict, custom: Dict, e=None):
SystemExit: If mismatched keys are found between the custom and base dictionaries.
Examples:
- >>> base_cfg = {'epochs': 50, 'lr0': 0.01, 'batch_size': 16}
- >>> custom_cfg = {'epoch': 100, 'lr': 0.02, 'batch_size': 32}
+ >>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
+ >>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
>>> try:
... check_dict_alignment(base_cfg, custom_cfg)
... except SystemExit:
diff --git a/ultralytics/data/annotator.py b/ultralytics/data/annotator.py
index ccd11b1ad2..5cb0058dcb 100644
--- a/ultralytics/data/annotator.py
+++ b/ultralytics/data/annotator.py
@@ -21,7 +21,7 @@ def auto_annotate(data, det_model="yolov8x.pt", sam_model="sam_b.pt", device="",
Examples:
>>> from ultralytics.data.annotator import auto_annotate
- >>> auto_annotate(data='ultralytics/assets', det_model='yolov8n.pt', sam_model='mobile_sam.pt')
+ >>> auto_annotate(data="ultralytics/assets", det_model="yolov8n.pt", sam_model="mobile_sam.pt")
Notes:
- The function creates a new directory for output if not specified.
diff --git a/ultralytics/data/augment.py b/ultralytics/data/augment.py
index 8e7640d41d..cd0e91d13f 100644
--- a/ultralytics/data/augment.py
+++ b/ultralytics/data/augment.py
@@ -38,7 +38,7 @@ class BaseTransform:
Examples:
>>> transform = BaseTransform()
- >>> labels = {'image': np.array(...), 'instances': [...], 'semantic': np.array(...)}
+ >>> labels = {"image": np.array(...), "instances": [...], "semantic": np.array(...)}
>>> transformed_labels = transform(labels)
"""
@@ -93,7 +93,7 @@ class BaseTransform:
Examples:
>>> transform = BaseTransform()
- >>> labels = {'instances': Instances(xyxy=torch.rand(5, 4), cls=torch.randint(0, 80, (5,)))}
+ >>> labels = {"instances": Instances(xyxy=torch.rand(5, 4), cls=torch.randint(0, 80, (5,)))}
>>> transformed_labels = transform.apply_instances(labels)
"""
pass
@@ -135,7 +135,7 @@ class BaseTransform:
Examples:
>>> transform = BaseTransform()
- >>> labels = {'img': np.random.rand(640, 640, 3), 'instances': []}
+ >>> labels = {"img": np.random.rand(640, 640, 3), "instances": []}
>>> transformed_labels = transform(labels)
"""
self.apply_image(labels)
@@ -338,6 +338,7 @@ class BaseMixTransform:
... def _mix_transform(self, labels):
... # Implement custom mix logic here
... return labels
+ ...
... def get_indexes(self):
... return [random.randint(0, len(self.dataset) - 1) for _ in range(3)]
>>> dataset = YourDataset()
@@ -421,7 +422,7 @@ class BaseMixTransform:
Examples:
>>> transform = BaseMixTransform(dataset)
- >>> labels = {'image': img, 'bboxes': boxes, 'mix_labels': [{'image': img2, 'bboxes': boxes2}]}
+ >>> labels = {"image": img, "bboxes": boxes, "mix_labels": [{"image": img2, "bboxes": boxes2}]}
>>> augmented_labels = transform._mix_transform(labels)
"""
raise NotImplementedError
@@ -456,20 +457,17 @@ class BaseMixTransform:
Examples:
>>> labels = {
- ... 'texts': [['cat'], ['dog']],
- ... 'cls': torch.tensor([[0], [1]]),
- ... 'mix_labels': [{
- ... 'texts': [['bird'], ['fish']],
- ... 'cls': torch.tensor([[0], [1]])
- ... }]
+ ... "texts": [["cat"], ["dog"]],
+ ... "cls": torch.tensor([[0], [1]]),
+ ... "mix_labels": [{"texts": [["bird"], ["fish"]], "cls": torch.tensor([[0], [1]])}],
... }
>>> updated_labels = self._update_label_text(labels)
- >>> print(updated_labels['texts'])
+ >>> print(updated_labels["texts"])
[['cat'], ['dog'], ['bird'], ['fish']]
- >>> print(updated_labels['cls'])
+ >>> print(updated_labels["cls"])
tensor([[0],
[1]])
- >>> print(updated_labels['mix_labels'][0]['cls'])
+ >>> print(updated_labels["mix_labels"][0]["cls"])
tensor([[2],
[3]])
"""
@@ -616,9 +614,12 @@ class Mosaic(BaseMixTransform):
Examples:
>>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=3)
- >>> labels = {'img': np.random.rand(480, 640, 3), 'mix_labels': [{'img': np.random.rand(480, 640, 3)} for _ in range(2)]}
+ >>> labels = {
+ ... "img": np.random.rand(480, 640, 3),
+ ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(2)],
+ ... }
>>> result = mosaic._mosaic3(labels)
- >>> print(result['img'].shape)
+ >>> print(result["img"].shape)
(640, 640, 3)
"""
mosaic_labels = []
@@ -670,9 +671,10 @@ class Mosaic(BaseMixTransform):
Examples:
>>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
- >>> labels = {"img": np.random.rand(480, 640, 3), "mix_labels": [
- ... {"img": np.random.rand(480, 640, 3)} for _ in range(3)
- ... ]}
+ >>> labels = {
+ ... "img": np.random.rand(480, 640, 3),
+ ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(3)],
+ ... }
>>> result = mosaic._mosaic4(labels)
>>> assert result["img"].shape == (1280, 1280, 3)
"""
@@ -734,7 +736,7 @@ class Mosaic(BaseMixTransform):
>>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=9)
>>> input_labels = dataset[0]
>>> mosaic_result = mosaic._mosaic9(input_labels)
- >>> mosaic_image = mosaic_result['img']
+ >>> mosaic_image = mosaic_result["img"]
"""
mosaic_labels = []
s = self.imgsz
@@ -898,7 +900,7 @@ class MixUp(BaseMixTransform):
Examples:
>>> from ultralytics.data.dataset import YOLODataset
- >>> dataset = YOLODataset('path/to/data.yaml')
+ >>> dataset = YOLODataset("path/to/data.yaml")
>>> mixup = MixUp(dataset, pre_transform=None, p=0.5)
"""
super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
@@ -974,10 +976,10 @@ class RandomPerspective:
Examples:
>>> transform = RandomPerspective(degrees=10, translate=0.1, scale=0.1, shear=10)
>>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- >>> labels = {'img': image, 'cls': np.array([0, 1]), 'instances': Instances(...)}
+ >>> labels = {"img": image, "cls": np.array([0, 1]), "instances": Instances(...)}
>>> result = transform(labels)
- >>> transformed_image = result['img']
- >>> transformed_instances = result['instances']
+ >>> transformed_image = result["img"]
+ >>> transformed_instances = result["instances"]
"""
def __init__(
@@ -1209,12 +1211,12 @@ class RandomPerspective:
>>> transform = RandomPerspective()
>>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
>>> labels = {
- ... 'img': image,
- ... 'cls': np.array([0, 1, 2]),
- ... 'instances': Instances(bboxes=np.array([[10, 10, 50, 50], [100, 100, 150, 150]]))
+ ... "img": image,
+ ... "cls": np.array([0, 1, 2]),
+ ... "instances": Instances(bboxes=np.array([[10, 10, 50, 50], [100, 100, 150, 150]])),
... }
>>> result = transform(labels)
- >>> assert result['img'].shape[:2] == result['resized_shape']
+ >>> assert result["img"].shape[:2] == result["resized_shape"]
"""
if self.pre_transform and "mosaic_border" not in labels:
labels = self.pre_transform(labels)
@@ -1358,9 +1360,9 @@ class RandomHSV:
Examples:
>>> hsv_augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
- >>> labels = {'img': np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)}
+ >>> labels = {"img": np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)}
>>> hsv_augmenter(labels)
- >>> augmented_img = labels['img']
+ >>> augmented_img = labels["img"]
"""
img = labels["img"]
if self.hgain or self.sgain or self.vgain:
@@ -1394,7 +1396,7 @@ class RandomFlip:
__call__: Applies the random flip transformation to an image and its annotations.
Examples:
- >>> transform = RandomFlip(p=0.5, direction='horizontal')
+ >>> transform = RandomFlip(p=0.5, direction="horizontal")
>>> result = transform({"img": image, "instances": instances})
>>> flipped_image = result["img"]
>>> flipped_instances = result["instances"]
@@ -1416,8 +1418,8 @@ class RandomFlip:
AssertionError: If direction is not 'horizontal' or 'vertical', or if p is not between 0 and 1.
Examples:
- >>> flip = RandomFlip(p=0.5, direction='horizontal')
- >>> flip = RandomFlip(p=0.7, direction='vertical', flip_idx=[1, 0, 3, 2, 5, 4])
+ >>> flip = RandomFlip(p=0.5, direction="horizontal")
+ >>> flip = RandomFlip(p=0.7, direction="vertical", flip_idx=[1, 0, 3, 2, 5, 4])
"""
assert direction in {"horizontal", "vertical"}, f"Support direction `horizontal` or `vertical`, got {direction}"
assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
@@ -1446,8 +1448,8 @@ class RandomFlip:
'instances' (ultralytics.utils.instance.Instances): Updated instances matching the flipped image.
Examples:
- >>> labels = {'img': np.random.rand(640, 640, 3), 'instances': Instances(...)}
- >>> random_flip = RandomFlip(p=0.5, direction='horizontal')
+ >>> labels = {"img": np.random.rand(640, 640, 3), "instances": Instances(...)}
+ >>> random_flip = RandomFlip(p=0.5, direction="horizontal")
>>> flipped_labels = random_flip(labels)
"""
img = labels["img"]
@@ -1493,8 +1495,8 @@ class LetterBox:
Examples:
>>> transform = LetterBox(new_shape=(640, 640))
>>> result = transform(labels)
- >>> resized_img = result['img']
- >>> updated_instances = result['instances']
+ >>> resized_img = result["img"]
+ >>> updated_instances = result["instances"]
"""
def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, center=True, stride=32):
@@ -1548,9 +1550,9 @@ class LetterBox:
Examples:
>>> letterbox = LetterBox(new_shape=(640, 640))
- >>> result = letterbox(labels={'img': np.zeros((480, 640, 3)), 'instances': Instances(...)})
- >>> resized_img = result['img']
- >>> updated_instances = result['instances']
+ >>> result = letterbox(labels={"img": np.zeros((480, 640, 3)), "instances": Instances(...)})
+ >>> resized_img = result["img"]
+ >>> updated_instances = result["instances"]
"""
if labels is None:
labels = {}
@@ -1616,7 +1618,7 @@ class LetterBox:
Examples:
>>> letterbox = LetterBox(new_shape=(640, 640))
- >>> labels = {'instances': Instances(...)}
+ >>> labels = {"instances": Instances(...)}
>>> ratio = (0.5, 0.5)
>>> padw, padh = 10, 20
>>> updated_labels = letterbox._update_labels(labels, ratio, padw, padh)
@@ -1643,7 +1645,7 @@ class CopyPaste:
Examples:
>>> copypaste = CopyPaste(p=0.5)
>>> augmented_labels = copypaste(labels)
- >>> augmented_image = augmented_labels['img']
+ >>> augmented_image = augmented_labels["img"]
"""
def __init__(self, p=0.5) -> None:
@@ -1680,7 +1682,7 @@ class CopyPaste:
(Dict): Dictionary with augmented image and updated instances under 'img', 'cls', and 'instances' keys.
Examples:
- >>> labels = {'img': np.random.rand(640, 640, 3), 'cls': np.array([0, 1, 2]), 'instances': Instances(...)}
+ >>> labels = {"img": np.random.rand(640, 640, 3), "cls": np.array([0, 1, 2]), "instances": Instances(...)}
>>> augmenter = CopyPaste(p=0.5)
>>> augmented_labels = augmenter(labels)
"""
@@ -1765,8 +1767,8 @@ class Albumentations:
Examples:
>>> transform = Albumentations(p=0.5)
>>> augmented = transform(image=image, bboxes=bboxes, class_labels=classes)
- >>> augmented_image = augmented['image']
- >>> augmented_bboxes = augmented['bboxes']
+ >>> augmented_image = augmented["image"]
+ >>> augmented_bboxes = augmented["bboxes"]
Notes:
- Requires Albumentations version 1.0.3 or higher.
@@ -1871,7 +1873,7 @@ class Albumentations:
>>> labels = {
... "img": np.random.rand(640, 640, 3),
... "cls": np.array([0, 1]),
- ... "instances": Instances(bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]]))
+ ... "instances": Instances(bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]])),
... }
>>> augmented = transform(labels)
>>> assert augmented["img"].shape == (640, 640, 3)
@@ -1927,11 +1929,11 @@ class Format:
_format_segments: Converts polygon points to bitmap masks.
Examples:
- >>> formatter = Format(bbox_format='xywh', normalize=True, return_mask=True)
+ >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
>>> formatted_labels = formatter(labels)
- >>> img = formatted_labels['img']
- >>> bboxes = formatted_labels['bboxes']
- >>> masks = formatted_labels['masks']
+ >>> img = formatted_labels["img"]
+ >>> bboxes = formatted_labels["bboxes"]
+ >>> masks = formatted_labels["masks"]
"""
def __init__(
@@ -1975,7 +1977,7 @@ class Format:
bgr (float): The probability to return BGR images.
Examples:
- >>> format = Format(bbox_format='xyxy', return_mask=True, return_keypoint=False)
+ >>> format = Format(bbox_format="xyxy", return_mask=True, return_keypoint=False)
>>> print(format.bbox_format)
xyxy
"""
@@ -2013,8 +2015,8 @@ class Format:
- 'batch_idx': Batch index tensor (if batch_idx is True).
Examples:
- >>> formatter = Format(bbox_format='xywh', normalize=True, return_mask=True)
- >>> labels = {'img': np.random.rand(640, 640, 3), 'cls': np.array([0, 1]), 'instances': Instances(...)}
+ >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
+ >>> labels = {"img": np.random.rand(640, 640, 3), "cls": np.array([0, 1]), "instances": Instances(...)}
>>> formatted_labels = formatter(labels)
>>> print(formatted_labels.keys())
"""
@@ -2275,8 +2277,8 @@ def v8_transforms(dataset, imgsz, hyp, stretch=False):
Examples:
>>> from ultralytics.data.dataset import YOLODataset
- >>> dataset = YOLODataset(img_path='path/to/images', imgsz=640)
- >>> hyp = {'mosaic': 1.0, 'copy_paste': 0.5, 'degrees': 10.0, 'translate': 0.2, 'scale': 0.9}
+ >>> dataset = YOLODataset(img_path="path/to/images", imgsz=640)
+ >>> hyp = {"mosaic": 1.0, "copy_paste": 0.5, "degrees": 10.0, "translate": 0.2, "scale": 0.9}
>>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
>>> augmented_data = transforms(dataset[0])
"""
@@ -2343,7 +2345,7 @@ def classify_transforms(
Examples:
>>> transforms = classify_transforms(size=224)
- >>> img = Image.open('path/to/image.jpg')
+ >>> img = Image.open("path/to/image.jpg")
>>> transformed_img = transforms(img)
"""
import torchvision.transforms as T # scope for faster 'import ultralytics'
@@ -2415,7 +2417,7 @@ def classify_augmentations(
(torchvision.transforms.Compose): A composition of image augmentation transforms.
Examples:
- >>> transforms = classify_augmentations(size=224, auto_augment='randaugment')
+ >>> transforms = classify_augmentations(size=224, auto_augment="randaugment")
>>> augmented_image = transforms(original_image)
"""
# Transforms to apply if Albumentations not installed
diff --git a/ultralytics/data/base.py b/ultralytics/data/base.py
index 256a2c205b..703fbae7a1 100644
--- a/ultralytics/data/base.py
+++ b/ultralytics/data/base.py
@@ -298,10 +298,10 @@ class BaseDataset(Dataset):
im_file=im_file,
shape=shape, # format: (height, width)
cls=cls,
- bboxes=bboxes, # xywh
+ bboxes=bboxes, # xywh
segments=segments, # xy
- keypoints=keypoints, # xy
- normalized=True, # or False
+ keypoints=keypoints, # xy
+ normalized=True, # or False
bbox_format="xyxy", # or xywh, ltwh
)
```
diff --git a/ultralytics/data/converter.py b/ultralytics/data/converter.py
index 3464bc1b95..ce66fabee5 100644
--- a/ultralytics/data/converter.py
+++ b/ultralytics/data/converter.py
@@ -123,8 +123,8 @@ def coco80_to_coco91_class():
```python
import numpy as np
- a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
- b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
+ a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n")
+ b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n")
x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
```
@@ -236,8 +236,8 @@ def convert_coco(
```python
from ultralytics.data.converter import convert_coco
- convert_coco('../datasets/coco/annotations/', use_segments=True, use_keypoints=False, cls91to80=True)
- convert_coco('../datasets/lvis/annotations/', use_segments=True, use_keypoints=False, cls91to80=False, lvis=True)
+ convert_coco("../datasets/coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=True)
+ convert_coco("../datasets/lvis/annotations/", use_segments=True, use_keypoints=False, cls91to80=False, lvis=True)
```
Output:
@@ -351,7 +351,7 @@ def convert_segment_masks_to_yolo_seg(masks_dir, output_dir, classes):
from ultralytics.data.converter import convert_segment_masks_to_yolo_seg
# The classes here is the total classes in the dataset, for COCO dataset we have 80 classes
- convert_segment_masks_to_yolo_seg('path/to/masks_directory', 'path/to/output/directory', classes=80)
+ convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80)
```
Notes:
@@ -429,7 +429,7 @@ def convert_dota_to_yolo_obb(dota_root_path: str):
```python
from ultralytics.data.converter import convert_dota_to_yolo_obb
- convert_dota_to_yolo_obb('path/to/DOTA')
+ convert_dota_to_yolo_obb("path/to/DOTA")
```
Notes:
diff --git a/ultralytics/data/explorer/explorer.py b/ultralytics/data/explorer/explorer.py
index 21e03c33d5..477d0981d7 100644
--- a/ultralytics/data/explorer/explorer.py
+++ b/ultralytics/data/explorer/explorer.py
@@ -163,7 +163,7 @@ class Explorer:
```python
exp = Explorer()
exp.create_embeddings_table()
- similar = exp.query(img='https://ultralytics.com/images/zidane.jpg')
+ similar = exp.query(img="https://ultralytics.com/images/zidane.jpg")
```
"""
if self.table is None:
@@ -271,7 +271,7 @@ class Explorer:
```python
exp = Explorer()
exp.create_embeddings_table()
- similar = exp.get_similar(img='https://ultralytics.com/images/zidane.jpg')
+ similar = exp.get_similar(img="https://ultralytics.com/images/zidane.jpg")
```
"""
assert return_type in {"pandas", "arrow"}, f"Return type should be `pandas` or `arrow`, but got {return_type}"
@@ -306,7 +306,7 @@ class Explorer:
```python
exp = Explorer()
exp.create_embeddings_table()
- similar = exp.plot_similar(img='https://ultralytics.com/images/zidane.jpg')
+ similar = exp.plot_similar(img="https://ultralytics.com/images/zidane.jpg")
```
"""
similar = self.get_similar(img, idx, limit, return_type="arrow")
@@ -395,8 +395,8 @@ class Explorer:
exp.create_embeddings_table()
similarity_idx_plot = exp.plot_similarity_index()
- similarity_idx_plot.show() # view image preview
- similarity_idx_plot.save('path/to/save/similarity_index_plot.png') # save contents to file
+ similarity_idx_plot.show() # view image preview
+ similarity_idx_plot.save("path/to/save/similarity_index_plot.png") # save contents to file
```
"""
sim_idx = self.similarity_index(max_dist=max_dist, top_k=top_k, force=force)
@@ -447,7 +447,7 @@ class Explorer:
```python
exp = Explorer()
exp.create_embeddings_table()
- answer = exp.ask_ai('Show images with 1 person and 2 dogs')
+ answer = exp.ask_ai("Show images with 1 person and 2 dogs")
```
"""
result = prompt_sql_query(query)
diff --git a/ultralytics/data/utils.py b/ultralytics/data/utils.py
index 2393f1dfd3..0ebda77119 100644
--- a/ultralytics/data/utils.py
+++ b/ultralytics/data/utils.py
@@ -438,11 +438,11 @@ class HUBDatasetStats:
```python
from ultralytics.data.utils import HUBDatasetStats
- stats = HUBDatasetStats('path/to/coco8.zip', task='detect') # detect dataset
- stats = HUBDatasetStats('path/to/coco8-seg.zip', task='segment') # segment dataset
- stats = HUBDatasetStats('path/to/coco8-pose.zip', task='pose') # pose dataset
- stats = HUBDatasetStats('path/to/dota8.zip', task='obb') # OBB dataset
- stats = HUBDatasetStats('path/to/imagenet10.zip', task='classify') # classification dataset
+ stats = HUBDatasetStats("path/to/coco8.zip", task="detect") # detect dataset
+ stats = HUBDatasetStats("path/to/coco8-seg.zip", task="segment") # segment dataset
+ stats = HUBDatasetStats("path/to/coco8-pose.zip", task="pose") # pose dataset
+ stats = HUBDatasetStats("path/to/dota8.zip", task="obb") # OBB dataset
+ stats = HUBDatasetStats("path/to/imagenet10.zip", task="classify") # classification dataset
stats.get_json(save=True)
stats.process_images()
@@ -598,7 +598,7 @@ def compress_one_image(f, f_new=None, max_dim=1920, quality=50):
from pathlib import Path
from ultralytics.data.utils import compress_one_image
- for f in Path('path/to/dataset').rglob('*.jpg'):
+ for f in Path("path/to/dataset").rglob("*.jpg"):
compress_one_image(f)
```
"""
diff --git a/ultralytics/engine/model.py b/ultralytics/engine/model.py
index ad29559ac5..f696ffb3ba 100644
--- a/ultralytics/engine/model.py
+++ b/ultralytics/engine/model.py
@@ -6,6 +6,7 @@ from typing import List, Union
import numpy as np
import torch
+from PIL import Image
from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir
from ultralytics.engine.results import Results
@@ -71,11 +72,11 @@ class Model(nn.Module):
Examples:
>>> from ultralytics import YOLO
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.predict('image.jpg')
- >>> model.train(data='coco128.yaml', epochs=3)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.predict("image.jpg")
+ >>> model.train(data="coco128.yaml", epochs=3)
>>> metrics = model.val()
- >>> model.export(format='onnx')
+ >>> model.export(format="onnx")
"""
def __init__(
@@ -143,7 +144,7 @@ class Model(nn.Module):
def __call__(
self,
- source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
+ source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False,
**kwargs,
) -> list:
@@ -165,8 +166,8 @@ class Model(nn.Module):
Results object.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model('https://ultralytics.com/images/bus.jpg')
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model("https://ultralytics.com/images/bus.jpg")
>>> for r in results:
... print(f"Detected {len(r)} objects in image")
"""
@@ -187,9 +188,9 @@ class Model(nn.Module):
(bool): True if the model string is a valid Triton Server URL, False otherwise.
Examples:
- >>> Model.is_triton_model('http://localhost:8000/v2/models/yolov8n')
+ >>> Model.is_triton_model("http://localhost:8000/v2/models/yolov8n")
True
- >>> Model.is_triton_model('yolov8n.pt')
+ >>> Model.is_triton_model("yolov8n.pt")
False
"""
from urllib.parse import urlsplit
@@ -252,7 +253,7 @@ class Model(nn.Module):
Examples:
>>> model = Model()
- >>> model._new('yolov8n.yaml', task='detect', verbose=True)
+ >>> model._new("yolov8n.yaml", task="detect", verbose=True)
"""
cfg_dict = yaml_model_load(cfg)
self.cfg = cfg
@@ -283,8 +284,8 @@ class Model(nn.Module):
Examples:
>>> model = Model()
- >>> model._load('yolov8n.pt')
- >>> model._load('path/to/weights.pth', task='detect')
+ >>> model._load("yolov8n.pt")
+ >>> model._load("path/to/weights.pth", task="detect")
"""
if weights.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")):
weights = checks.check_file(weights, download_dir=SETTINGS["weights_dir"]) # download and return local file
@@ -347,7 +348,7 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = Model('yolov8n.pt')
+ >>> model = Model("yolov8n.pt")
>>> model.reset_weights()
"""
self._check_is_pytorch_model()
@@ -376,8 +377,8 @@ class Model(nn.Module):
Examples:
>>> model = Model()
- >>> model.load('yolov8n.pt')
- >>> model.load(Path('path/to/weights.pt'))
+ >>> model.load("yolov8n.pt")
+ >>> model.load(Path("path/to/weights.pt"))
"""
self._check_is_pytorch_model()
if isinstance(weights, (str, Path)):
@@ -401,8 +402,8 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = Model('yolov8n.pt')
- >>> model.save('my_model.pt')
+ >>> model = Model("yolov8n.pt")
+ >>> model.save("my_model.pt")
"""
self._check_is_pytorch_model()
from copy import deepcopy
@@ -438,7 +439,7 @@ class Model(nn.Module):
TypeError: If the model is not a PyTorch model.
Examples:
- >>> model = Model('yolov8n.pt')
+ >>> model = Model("yolov8n.pt")
>>> model.info() # Prints model summary
>>> info_list = model.info(detailed=True, verbose=False) # Returns detailed info as a list
"""
@@ -493,8 +494,8 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> image = 'https://ultralytics.com/images/bus.jpg'
+ >>> model = YOLO("yolov8n.pt")
+ >>> image = "https://ultralytics.com/images/bus.jpg"
>>> embeddings = model.embed(image)
>>> print(embeddings[0].shape)
"""
@@ -504,7 +505,7 @@ class Model(nn.Module):
def predict(
self,
- source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
+ source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False,
predictor=None,
**kwargs,
@@ -517,7 +518,7 @@ class Model(nn.Module):
types of image sources and can operate in a streaming mode.
Args:
- source (str | Path | int | List[str] | List[Path] | List[int] | np.ndarray | torch.Tensor): The source
+ source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | List | Tuple): The source
of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL
images, numpy arrays, and torch tensors.
stream (bool): If True, treats the input source as a continuous stream for predictions.
@@ -530,8 +531,8 @@ class Model(nn.Module):
Results object.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.predict(source='path/to/image.jpg', conf=0.25)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.predict(source="path/to/image.jpg", conf=0.25)
>>> for r in results:
... print(r.boxes.data) # print detection bounding boxes
@@ -591,8 +592,8 @@ class Model(nn.Module):
AttributeError: If the predictor does not have registered trackers.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.track(source='path/to/video.mp4', show=True)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.track(source="path/to/video.mp4", show=True)
>>> for r in results:
... print(r.boxes.id) # print tracking IDs
@@ -634,8 +635,8 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.val(data='coco128.yaml', imgsz=640)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.val(data="coco128.yaml", imgsz=640)
>>> print(results.box.map) # Print mAP50-95
"""
custom = {"rect": True} # method defaults
@@ -676,8 +677,8 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.benchmark(data='coco8.yaml', imgsz=640, half=True)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
>>> print(results)
"""
self._check_is_pytorch_model()
@@ -726,8 +727,8 @@ class Model(nn.Module):
RuntimeError: If the export process fails due to errors.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> model.export(format='onnx', dynamic=True, simplify=True)
+ >>> model = YOLO("yolov8n.pt")
+ >>> model.export(format="onnx", dynamic=True, simplify=True)
'path/to/exported/model.onnx'
"""
self._check_is_pytorch_model()
@@ -781,8 +782,8 @@ class Model(nn.Module):
ModuleNotFoundError: If the HUB SDK is not installed.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> results = model.train(data='coco128.yaml', epochs=3)
+ >>> model = YOLO("yolov8n.pt")
+ >>> results = model.train(data="coco128.yaml", epochs=3)
"""
self._check_is_pytorch_model()
if hasattr(self.session, "model") and self.session.model.id: # Ultralytics HUB session with loaded model
@@ -846,7 +847,7 @@ class Model(nn.Module):
AssertionError: If the model is not a PyTorch model.
Examples:
- >>> model = YOLO('yolov8n.pt')
+ >>> model = YOLO("yolov8n.pt")
>>> results = model.tune(use_ray=True, iterations=20)
>>> print(results)
"""
@@ -900,15 +901,15 @@ class Model(nn.Module):
initialized, it sets it up before retrieving the names.
Returns:
- (List[str]): A list of class names associated with the model.
+ (Dict[int, str]): A dict of class names associated with the model.
Raises:
AttributeError: If the model or predictor does not have a 'names' attribute.
Examples:
- >>> model = YOLO('yolov8n.pt')
+ >>> model = YOLO("yolov8n.pt")
>>> print(model.names)
- ['person', 'bicycle', 'car', ...]
+ {0: 'person', 1: 'bicycle', 2: 'car', ...}
"""
from ultralytics.nn.autobackend import check_class_names
@@ -956,7 +957,7 @@ class Model(nn.Module):
(object | None): The transform object of the model if available, otherwise None.
Examples:
- >>> model = YOLO('yolov8n.pt')
+ >>> model = YOLO("yolov8n.pt")
>>> transforms = model.transforms
>>> if transforms:
... print(f"Model transforms: {transforms}")
@@ -985,9 +986,9 @@ class Model(nn.Module):
Examples:
>>> def on_train_start(trainer):
... print("Training is starting!")
- >>> model = YOLO('yolov8n.pt')
+ >>> model = YOLO("yolov8n.pt")
>>> model.add_callback("on_train_start", on_train_start)
- >>> model.train(data='coco128.yaml', epochs=1)
+ >>> model.train(data="coco128.yaml", epochs=1)
"""
self.callbacks[event].append(func)
@@ -1004,9 +1005,9 @@ class Model(nn.Module):
recognized by the Ultralytics callback system.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> model.add_callback('on_train_start', lambda: print('Training started'))
- >>> model.clear_callback('on_train_start')
+ >>> model = YOLO("yolov8n.pt")
+ >>> model.add_callback("on_train_start", lambda: print("Training started"))
+ >>> model.clear_callback("on_train_start")
>>> # All callbacks for 'on_train_start' are now removed
Notes:
@@ -1034,8 +1035,8 @@ class Model(nn.Module):
modifications, ensuring consistent behavior across different runs or experiments.
Examples:
- >>> model = YOLO('yolov8n.pt')
- >>> model.add_callback('on_train_start', custom_function)
+ >>> model = YOLO("yolov8n.pt")
+ >>> model.add_callback("on_train_start", custom_function)
>>> model.reset_callbacks()
# All callbacks are now reset to their default functions
"""
@@ -1058,7 +1059,7 @@ class Model(nn.Module):
(dict): A new dictionary containing only the specified include keys from the input arguments.
Examples:
- >>> original_args = {'imgsz': 640, 'data': 'coco.yaml', 'task': 'detect', 'batch': 16, 'epochs': 100}
+ >>> original_args = {"imgsz": 640, "data": "coco.yaml", "task": "detect", "batch": 16, "epochs": 100}
>>> reset_args = Model._reset_ckpt_args(original_args)
>>> print(reset_args)
{'imgsz': 640, 'data': 'coco.yaml', 'task': 'detect'}
@@ -1089,9 +1090,9 @@ class Model(nn.Module):
NotImplementedError: If the specified key is not supported for the current task.
Examples:
- >>> model = Model(task='detect')
- >>> predictor = model._smart_load('predictor')
- >>> trainer = model._smart_load('trainer')
+ >>> model = Model(task="detect")
+ >>> predictor = model._smart_load("predictor")
+ >>> trainer = model._smart_load("trainer")
Notes:
- This method is typically used internally by other methods of the Model class.
@@ -1127,8 +1128,8 @@ class Model(nn.Module):
Examples:
>>> model = Model()
>>> task_map = model.task_map
- >>> detect_class_map = task_map['detect']
- >>> segment_class_map = task_map['segment']
+ >>> detect_class_map = task_map["detect"]
+ >>> segment_class_map = task_map["segment"]
Note:
The actual implementation of this method may vary depending on the specific tasks and
diff --git a/ultralytics/engine/results.py b/ultralytics/engine/results.py
index 34a5d3e089..1c7ffb9144 100644
--- a/ultralytics/engine/results.py
+++ b/ultralytics/engine/results.py
@@ -143,7 +143,7 @@ class BaseTensor(SimpleClass):
Examples:
>>> base_tensor = BaseTensor(torch.randn(3, 4), orig_shape=(480, 640))
- >>> cuda_tensor = base_tensor.to('cuda')
+ >>> cuda_tensor = base_tensor.to("cuda")
>>> float16_tensor = base_tensor.to(dtype=torch.float16)
"""
return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)
@@ -223,7 +223,7 @@ class Results(SimpleClass):
>>> for result in results:
... print(result.boxes) # Print detection boxes
... result.show() # Display the annotated image
- ... result.save(filename='result.jpg') # Save annotated image
+ ... result.save(filename="result.jpg") # Save annotated image
"""
def __init__(
@@ -280,7 +280,7 @@ class Results(SimpleClass):
(Results): A new Results object containing the specified subset of inference results.
Examples:
- >>> results = model('path/to/image.jpg') # Perform inference
+ >>> results = model("path/to/image.jpg") # Perform inference
>>> single_result = results[0] # Get the first result
>>> subset_results = results[1:4] # Get a slice of results
"""
@@ -319,7 +319,7 @@ class Results(SimpleClass):
obb (torch.Tensor | None): A tensor of shape (N, 5) containing oriented bounding box coordinates.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> new_boxes = torch.tensor([[100, 100, 200, 200, 0.9, 0]])
>>> results[0].update(boxes=new_boxes)
"""
@@ -370,7 +370,7 @@ class Results(SimpleClass):
(Results): A new Results object with all tensor attributes on CPU memory.
Examples:
- >>> results = model('path/to/image.jpg') # Perform inference
+ >>> results = model("path/to/image.jpg") # Perform inference
>>> cpu_result = results[0].cpu() # Move the first result to CPU
>>> print(cpu_result.boxes.device) # Output: cpu
"""
@@ -384,7 +384,7 @@ class Results(SimpleClass):
(Results): A new Results object with all tensors converted to numpy arrays.
Examples:
- >>> results = model('path/to/image.jpg')
+ >>> results = model("path/to/image.jpg")
>>> numpy_result = results[0].numpy()
>>> type(numpy_result.boxes.data)
@@ -488,7 +488,7 @@ class Results(SimpleClass):
(np.ndarray): Annotated image as a numpy array.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> for result in results:
... im = result.plot()
... im.show()
@@ -578,7 +578,7 @@ class Results(SimpleClass):
**kwargs (Any): Arbitrary keyword arguments to be passed to the `plot()` method.
Examples:
- >>> results = model('path/to/image.jpg')
+ >>> results = model("path/to/image.jpg")
>>> results[0].show() # Display the first result
>>> for result in results:
... result.show() # Display all results
@@ -599,12 +599,12 @@ class Results(SimpleClass):
**kwargs (Any): Arbitrary keyword arguments to be passed to the `plot` method.
Examples:
- >>> results = model('path/to/image.jpg')
+ >>> results = model("path/to/image.jpg")
>>> for result in results:
- ... result.save('annotated_image.jpg')
+ ... result.save("annotated_image.jpg")
>>> # Or with custom plot arguments
>>> for result in results:
- ... result.save('annotated_image.jpg', conf=False, line_width=2)
+ ... result.save("annotated_image.jpg", conf=False, line_width=2)
"""
if not filename:
filename = f"results_{Path(self.path).name}"
@@ -623,7 +623,7 @@ class Results(SimpleClass):
number of detections per class. For classification tasks, it includes the top 5 class probabilities.
Examples:
- >>> results = model('path/to/image.jpg')
+ >>> results = model("path/to/image.jpg")
>>> for result in results:
... print(result.verbose())
2 persons, 1 car, 3 traffic lights,
@@ -660,7 +660,7 @@ class Results(SimpleClass):
Examples:
>>> from ultralytics import YOLO
- >>> model = YOLO('yolov8n.pt')
+ >>> model = YOLO("yolov8n.pt")
>>> results = model("path/to/image.jpg")
>>> for result in results:
... result.save_txt("output.txt")
@@ -757,7 +757,7 @@ class Results(SimpleClass):
task type (classification or detection) and available information (boxes, masks, keypoints).
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> summary = results[0].summary()
>>> print(summary)
"""
@@ -919,7 +919,7 @@ class Boxes(BaseTensor):
coordinates in [x1, y1, x2, y2] format, where n is the number of boxes.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> boxes = results[0].boxes
>>> xyxy = boxes.xyxy
>>> print(xyxy)
@@ -953,7 +953,7 @@ class Boxes(BaseTensor):
The shape is (N,), where N is the number of boxes.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> boxes = results[0].boxes
>>> class_ids = boxes.cls
>>> print(class_ids) # tensor([0., 2., 1.])
@@ -970,7 +970,7 @@ class Boxes(BaseTensor):
otherwise None. Shape is (N,) where N is the number of boxes.
Examples:
- >>> results = model.track('path/to/video.mp4')
+ >>> results = model.track("path/to/video.mp4")
>>> for result in results:
... boxes = result.boxes
... if boxes.is_track:
@@ -992,8 +992,8 @@ class Boxes(BaseTensor):
Convert bounding boxes from [x1, y1, x2, y2] format to [x, y, width, height] format.
Returns:
- (torch.Tensor | numpy.ndarray): Boxes in [x, y, width, height] format, where x, y are the coordinates of
- the top-left corner of the bounding box, width, height are the dimensions of the bounding box and the
+ (torch.Tensor | numpy.ndarray): Boxes in [x_center, y_center, width, height] format, where x_center, y_center are the coordinates of
+ the center point of the bounding box, width, height are the dimensions of the bounding box and the
shape of the returned tensor is (N, 4), where N is the number of boxes.
Examples:
@@ -1116,7 +1116,7 @@ class Masks(BaseTensor):
mask contour.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> masks = results[0].masks
>>> normalized_coords = masks.xyn
>>> print(normalized_coords[0]) # Normalized coordinates of the first mask
@@ -1141,7 +1141,7 @@ class Masks(BaseTensor):
number of points in the segment.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> masks = results[0].masks
>>> xy_coords = masks.xy
>>> print(len(xy_coords)) # Number of masks
@@ -1223,7 +1223,7 @@ class Keypoints(BaseTensor):
the number of detections and K is the number of keypoints per detection.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> keypoints = results[0].keypoints
>>> xy = keypoints.xy
>>> print(xy.shape) # (N, K, 2)
@@ -1388,7 +1388,7 @@ class Probs(BaseTensor):
(torch.Tensor | numpy.ndarray): A tensor containing the confidence score of the top 1 class.
Examples:
- >>> results = model('image.jpg') # classify an image
+ >>> results = model("image.jpg") # classify an image
>>> probs = results[0].probs # get classification probabilities
>>> top1_confidence = probs.top1conf # get confidence of top 1 class
>>> print(f"Top 1 class confidence: {top1_confidence.item():.4f}")
@@ -1410,7 +1410,7 @@ class Probs(BaseTensor):
top 5 predicted classes, sorted in descending order of probability.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> probs = results[0].probs
>>> top5_conf = probs.top5conf
>>> print(top5_conf) # Prints confidence scores for top 5 classes
@@ -1497,7 +1497,7 @@ class OBB(BaseTensor):
[x_center, y_center, width, height, rotation]. The shape is (N, 5) where N is the number of boxes.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> obb = results[0].obb
>>> xywhr = obb.xywhr
>>> print(xywhr.shape)
@@ -1518,7 +1518,7 @@ class OBB(BaseTensor):
for N detections, where each score is in the range [0, 1].
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> obb_result = results[0].obb
>>> confidence_scores = obb_result.conf
>>> print(confidence_scores)
@@ -1535,7 +1535,7 @@ class OBB(BaseTensor):
bounding box. The shape is (N,), where N is the number of boxes.
Examples:
- >>> results = model('image.jpg')
+ >>> results = model("image.jpg")
>>> result = results[0]
>>> obb = result.obb
>>> class_values = obb.cls
@@ -1553,7 +1553,7 @@ class OBB(BaseTensor):
oriented bounding box. Returns None if tracking IDs are not available.
Examples:
- >>> results = model('image.jpg', tracker=True) # Run inference with tracking
+ >>> results = model("image.jpg", tracker=True) # Run inference with tracking
>>> for result in results:
... if result.obb is not None:
... track_ids = result.obb.id
@@ -1620,8 +1620,8 @@ class OBB(BaseTensor):
Examples:
>>> import torch
>>> from ultralytics import YOLO
- >>> model = YOLO('yolov8n-obb.pt')
- >>> results = model('path/to/image.jpg')
+ >>> model = YOLO("yolov8n-obb.pt")
+ >>> results = model("path/to/image.jpg")
>>> for result in results:
... obb = result.obb
... if obb is not None:
diff --git a/ultralytics/engine/trainer.py b/ultralytics/engine/trainer.py
index 6ebe753665..3d2515acbd 100644
--- a/ultralytics/engine/trainer.py
+++ b/ultralytics/engine/trainer.py
@@ -56,8 +56,6 @@ from ultralytics.utils.torch_utils import (
class BaseTrainer:
"""
- BaseTrainer.
-
A base class for creating trainers.
Attributes:
@@ -478,12 +476,16 @@ class BaseTrainer:
torch.cuda.empty_cache()
self.run_callbacks("teardown")
+ def read_results_csv(self):
+ """Read results.csv into a dict using pandas."""
+ import pandas as pd # scope for faster 'import ultralytics'
+
+ return {k.strip(): v for k, v in pd.read_csv(self.csv).to_dict(orient="list").items()}
+
def save_model(self):
"""Save model training checkpoints with additional metadata."""
import io
- import pandas as pd # scope for faster 'import ultralytics'
-
# Serialize ckpt to a byte buffer once (faster than repeated torch.save() calls)
buffer = io.BytesIO()
torch.save(
@@ -496,7 +498,7 @@ class BaseTrainer:
"optimizer": convert_optimizer_state_dict_to_fp16(deepcopy(self.optimizer.state_dict())),
"train_args": vars(self.args), # save as dict
"train_metrics": {**self.metrics, **{"fitness": self.fitness}},
- "train_results": {k.strip(): v for k, v in pd.read_csv(self.csv).to_dict(orient="list").items()},
+ "train_results": self.read_results_csv(),
"date": datetime.now().isoformat(),
"version": __version__,
"license": "AGPL-3.0 (https://ultralytics.com/license)",
@@ -646,6 +648,9 @@ class BaseTrainer:
if f.exists():
strip_optimizer(f) # strip optimizers
if f is self.best:
+ if self.last.is_file(): # update best.pt train_metrics from last.pt
+ k = "train_results"
+ torch.save({**torch.load(self.best), **{k: torch.load(self.last)[k]}}, self.best)
LOGGER.info(f"\nValidating {f}...")
self.validator.args.plots = self.args.plots
self.metrics = self.validator(model=f)
diff --git a/ultralytics/engine/tuner.py b/ultralytics/engine/tuner.py
index 7fc1897d3c..8cc1fccc33 100644
--- a/ultralytics/engine/tuner.py
+++ b/ultralytics/engine/tuner.py
@@ -12,8 +12,8 @@ Example:
```python
from ultralytics import YOLO
- model = YOLO('yolov8n.pt')
- model.tune(data='coco8.yaml', epochs=10, iterations=300, optimizer='AdamW', plots=False, save=False, val=False)
+ model = YOLO("yolov8n.pt")
+ model.tune(data="coco8.yaml", epochs=10, iterations=300, optimizer="AdamW", plots=False, save=False, val=False)
```
"""
@@ -54,15 +54,15 @@ class Tuner:
```python
from ultralytics import YOLO
- model = YOLO('yolov8n.pt')
- model.tune(data='coco8.yaml', epochs=10, iterations=300, optimizer='AdamW', plots=False, save=False, val=False)
+ model = YOLO("yolov8n.pt")
+ model.tune(data="coco8.yaml", epochs=10, iterations=300, optimizer="AdamW", plots=False, save=False, val=False)
```
Tune with custom search space.
```python
from ultralytics import YOLO
- model = YOLO('yolov8n.pt')
+ model = YOLO("yolov8n.pt")
model.tune(space={key1: val1, key2: val2}) # custom search space dictionary
```
"""
diff --git a/ultralytics/hub/__init__.py b/ultralytics/hub/__init__.py
index 0e42662e64..d8d7b4a274 100644
--- a/ultralytics/hub/__init__.py
+++ b/ultralytics/hub/__init__.py
@@ -136,11 +136,11 @@ def check_dataset(path: str, task: str) -> None:
```python
from ultralytics.hub import check_dataset
- check_dataset('path/to/coco8.zip', task='detect') # detect dataset
- check_dataset('path/to/coco8-seg.zip', task='segment') # segment dataset
- check_dataset('path/to/coco8-pose.zip', task='pose') # pose dataset
- check_dataset('path/to/dota8.zip', task='obb') # OBB dataset
- check_dataset('path/to/imagenet10.zip', task='classify') # classification dataset
+ check_dataset("path/to/coco8.zip", task="detect") # detect dataset
+ check_dataset("path/to/coco8-seg.zip", task="segment") # segment dataset
+ check_dataset("path/to/coco8-pose.zip", task="pose") # pose dataset
+ check_dataset("path/to/dota8.zip", task="obb") # OBB dataset
+ check_dataset("path/to/imagenet10.zip", task="classify") # classification dataset
```
"""
HUBDatasetStats(path=path, task=task).get_json()
diff --git a/ultralytics/hub/session.py b/ultralytics/hub/session.py
index 1423f5f46c..75608ddad8 100644
--- a/ultralytics/hub/session.py
+++ b/ultralytics/hub/session.py
@@ -1,5 +1,6 @@
# Ultralytics YOLO 🚀, AGPL-3.0 license
+import shutil
import threading
import time
from http import HTTPStatus
@@ -275,7 +276,7 @@ class HUBTrainingSession:
# if request related to metrics upload and exceed retries
if response is None and kwargs.get("metrics"):
- self.metrics_upload_failed_queue.update(kwargs.get("metrics", None))
+ self.metrics_upload_failed_queue.update(kwargs.get("metrics"))
return response
@@ -344,23 +345,34 @@ class HUBTrainingSession:
map (float): Mean average precision of the model.
final (bool): Indicates if the model is the final model after training.
"""
- if Path(weights).is_file():
- progress_total = Path(weights).stat().st_size if final else None # Only show progress if final
- self.request_queue(
- self.model.upload_model,
- epoch=epoch,
- weights=weights,
- is_best=is_best,
- map=map,
- final=final,
- retry=10,
- timeout=3600,
- thread=not final,
- progress_total=progress_total,
- stream_response=True,
- )
- else:
- LOGGER.warning(f"{PREFIX}WARNING ⚠️ Model upload issue. Missing model {weights}.")
+ weights = Path(weights)
+ if not weights.is_file():
+ last = weights.with_name("last" + weights.suffix)
+ if final and last.is_file():
+ LOGGER.warning(
+ f"{PREFIX} WARNING ⚠️ Model 'best.pt' not found, copying 'last.pt' to 'best.pt' and uploading. "
+ "This often happens when resuming training in transient environments like Google Colab. "
+ "For more reliable training, consider using Ultralytics HUB Cloud. "
+ "Learn more at https://docs.ultralytics.com/hub/cloud-training."
+ )
+ shutil.copy(last, weights) # copy last.pt to best.pt
+ else:
+ LOGGER.warning(f"{PREFIX} WARNING ⚠️ Model upload issue. Missing model {weights}.")
+ return
+
+ self.request_queue(
+ self.model.upload_model,
+ epoch=epoch,
+ weights=str(weights),
+ is_best=is_best,
+ map=map,
+ final=final,
+ retry=10,
+ timeout=3600,
+ thread=not final,
+ progress_total=weights.stat().st_size if final else None, # only show progress if final
+ stream_response=True,
+ )
@staticmethod
def _show_upload_progress(content_length: int, response: requests.Response) -> None:
diff --git a/ultralytics/models/fastsam/model.py b/ultralytics/models/fastsam/model.py
index e6f0457cd1..eb1749a4ac 100644
--- a/ultralytics/models/fastsam/model.py
+++ b/ultralytics/models/fastsam/model.py
@@ -16,8 +16,8 @@ class FastSAM(Model):
```python
from ultralytics import FastSAM
- model = FastSAM('last.pt')
- results = model.predict('ultralytics/assets/bus.jpg')
+ model = FastSAM("last.pt")
+ results = model.predict("ultralytics/assets/bus.jpg")
```
"""
diff --git a/ultralytics/models/fastsam/predict.py b/ultralytics/models/fastsam/predict.py
index 2a15c3f39f..8095239e3c 100644
--- a/ultralytics/models/fastsam/predict.py
+++ b/ultralytics/models/fastsam/predict.py
@@ -92,8 +92,8 @@ class FastSAMPredictor(SegmentationPredictor):
if labels.sum() == 0 # all negative points
else torch.zeros(len(result), dtype=torch.bool, device=self.device)
)
- for p, l in zip(points, labels):
- point_idx[torch.nonzero(masks[:, p[1], p[0]], as_tuple=True)[0]] = True if l else False
+ for point, label in zip(points, labels):
+ point_idx[torch.nonzero(masks[:, point[1], point[0]], as_tuple=True)[0]] = True if label else False
idx |= point_idx
if texts is not None:
if isinstance(texts, str):
diff --git a/ultralytics/models/nas/model.py b/ultralytics/models/nas/model.py
index 90446c585e..bc0ccc5942 100644
--- a/ultralytics/models/nas/model.py
+++ b/ultralytics/models/nas/model.py
@@ -6,8 +6,8 @@ Example:
```python
from ultralytics import NAS
- model = NAS('yolo_nas_s')
- results = model.predict('ultralytics/assets/bus.jpg')
+ model = NAS("yolo_nas_s")
+ results = model.predict("ultralytics/assets/bus.jpg")
```
"""
@@ -34,8 +34,8 @@ class NAS(Model):
```python
from ultralytics import NAS
- model = NAS('yolo_nas_s')
- results = model.predict('ultralytics/assets/bus.jpg')
+ model = NAS("yolo_nas_s")
+ results = model.predict("ultralytics/assets/bus.jpg")
```
Attributes:
diff --git a/ultralytics/models/nas/predict.py b/ultralytics/models/nas/predict.py
index e824da6e61..c36a384f2d 100644
--- a/ultralytics/models/nas/predict.py
+++ b/ultralytics/models/nas/predict.py
@@ -22,7 +22,7 @@ class NASPredictor(BasePredictor):
```python
from ultralytics import NAS
- model = NAS('yolo_nas_s')
+ model = NAS("yolo_nas_s")
predictor = model.predictor
# Assumes that raw_preds, img, orig_imgs are available
results = predictor.postprocess(raw_preds, img, orig_imgs)
diff --git a/ultralytics/models/nas/val.py b/ultralytics/models/nas/val.py
index 995f3c335d..7de446d42b 100644
--- a/ultralytics/models/nas/val.py
+++ b/ultralytics/models/nas/val.py
@@ -24,7 +24,7 @@ class NASValidator(DetectionValidator):
```python
from ultralytics import NAS
- model = NAS('yolo_nas_s')
+ model = NAS("yolo_nas_s")
validator = model.validator
# Assumes that raw_preds are available
final_preds = validator.postprocess(raw_preds)
diff --git a/ultralytics/models/rtdetr/predict.py b/ultralytics/models/rtdetr/predict.py
index fa7c57ee4b..492254356d 100644
--- a/ultralytics/models/rtdetr/predict.py
+++ b/ultralytics/models/rtdetr/predict.py
@@ -21,7 +21,7 @@ class RTDETRPredictor(BasePredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.rtdetr import RTDETRPredictor
- args = dict(model='rtdetr-l.pt', source=ASSETS)
+ args = dict(model="rtdetr-l.pt", source=ASSETS)
predictor = RTDETRPredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/rtdetr/train.py b/ultralytics/models/rtdetr/train.py
index 973af649fd..cb11a72794 100644
--- a/ultralytics/models/rtdetr/train.py
+++ b/ultralytics/models/rtdetr/train.py
@@ -25,7 +25,7 @@ class RTDETRTrainer(DetectionTrainer):
```python
from ultralytics.models.rtdetr.train import RTDETRTrainer
- args = dict(model='rtdetr-l.yaml', data='coco8.yaml', imgsz=640, epochs=3)
+ args = dict(model="rtdetr-l.yaml", data="coco8.yaml", imgsz=640, epochs=3)
trainer = RTDETRTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/rtdetr/val.py b/ultralytics/models/rtdetr/val.py
index d4d939fede..6ecc1d2c8c 100644
--- a/ultralytics/models/rtdetr/val.py
+++ b/ultralytics/models/rtdetr/val.py
@@ -62,7 +62,7 @@ class RTDETRValidator(DetectionValidator):
```python
from ultralytics.models.rtdetr import RTDETRValidator
- args = dict(model='rtdetr-l.pt', data='coco8.yaml')
+ args = dict(model="rtdetr-l.pt", data="coco8.yaml")
validator = RTDETRValidator(args=args)
validator()
```
diff --git a/ultralytics/models/sam/model.py b/ultralytics/models/sam/model.py
index 30d8644bb2..126e672a57 100644
--- a/ultralytics/models/sam/model.py
+++ b/ultralytics/models/sam/model.py
@@ -41,8 +41,8 @@ class SAM(Model):
info: Logs information about the SAM model.
Examples:
- >>> sam = SAM('sam_b.pt')
- >>> results = sam.predict('image.jpg', points=[[500, 375]])
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam.predict("image.jpg", points=[[500, 375]])
>>> for r in results:
>>> print(f"Detected {len(r.masks)} masks")
"""
@@ -58,7 +58,7 @@ class SAM(Model):
NotImplementedError: If the model file extension is not .pt or .pth.
Examples:
- >>> sam = SAM('sam_b.pt')
+ >>> sam = SAM("sam_b.pt")
>>> print(sam.is_sam2)
"""
if model and Path(model).suffix not in {".pt", ".pth"}:
@@ -78,8 +78,8 @@ class SAM(Model):
task (str | None): Task name. If provided, it specifies the particular task the model is being loaded for.
Examples:
- >>> sam = SAM('sam_b.pt')
- >>> sam._load('path/to/custom_weights.pt')
+ >>> sam = SAM("sam_b.pt")
+ >>> sam._load("path/to/custom_weights.pt")
"""
self.model = build_sam(weights)
@@ -100,8 +100,8 @@ class SAM(Model):
(List): The model predictions.
Examples:
- >>> sam = SAM('sam_b.pt')
- >>> results = sam.predict('image.jpg', points=[[500, 375]])
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam.predict("image.jpg", points=[[500, 375]])
>>> for r in results:
... print(f"Detected {len(r.masks)} masks")
"""
@@ -130,8 +130,8 @@ class SAM(Model):
(List): The model predictions, typically containing segmentation masks and other relevant information.
Examples:
- >>> sam = SAM('sam_b.pt')
- >>> results = sam('image.jpg', points=[[500, 375]])
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam("image.jpg", points=[[500, 375]])
>>> print(f"Detected {len(results[0].masks)} masks")
"""
return self.predict(source, stream, bboxes, points, labels, **kwargs)
@@ -151,7 +151,7 @@ class SAM(Model):
(Tuple): A tuple containing the model's information (string representations of the model).
Examples:
- >>> sam = SAM('sam_b.pt')
+ >>> sam = SAM("sam_b.pt")
>>> info = sam.info()
>>> print(info[0]) # Print summary information
"""
@@ -167,7 +167,7 @@ class SAM(Model):
class. For SAM2 models, it maps to SAM2Predictor, otherwise to the standard Predictor.
Examples:
- >>> sam = SAM('sam_b.pt')
+ >>> sam = SAM("sam_b.pt")
>>> task_map = sam.task_map
>>> print(task_map)
{'segment': }
diff --git a/ultralytics/models/sam/modules/decoders.py b/ultralytics/models/sam/modules/decoders.py
index 5b172bdd26..cd4cc0c18c 100644
--- a/ultralytics/models/sam/modules/decoders.py
+++ b/ultralytics/models/sam/modules/decoders.py
@@ -32,8 +32,9 @@ class MaskDecoder(nn.Module):
Examples:
>>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
- >>> masks, iou_pred = decoder(image_embeddings, image_pe, sparse_prompt_embeddings,
- ... dense_prompt_embeddings, multimask_output=True)
+ >>> masks, iou_pred = decoder(
+ ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, multimask_output=True
+ ... )
>>> print(f"Predicted masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
"""
@@ -213,7 +214,8 @@ class SAM2MaskDecoder(nn.Module):
>>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
>>> decoder = SAM2MaskDecoder(256, transformer)
>>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
- ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
+ ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
+ ... )
"""
def __init__(
@@ -345,7 +347,8 @@ class SAM2MaskDecoder(nn.Module):
>>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
>>> decoder = SAM2MaskDecoder(256, transformer)
>>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
- ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
+ ... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
+ ... )
"""
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
image_embeddings=image_embeddings,
diff --git a/ultralytics/models/sam/modules/sam.py b/ultralytics/models/sam/modules/sam.py
index 27509575be..d3191366fb 100644
--- a/ultralytics/models/sam/modules/sam.py
+++ b/ultralytics/models/sam/modules/sam.py
@@ -417,7 +417,15 @@ class SAM2Model(torch.nn.Module):
>>> point_inputs = {"point_coords": torch.rand(1, 2, 2), "point_labels": torch.tensor([[1, 0]])}
>>> mask_inputs = torch.rand(1, 1, 512, 512)
>>> results = model._forward_sam_heads(backbone_features, point_inputs, mask_inputs)
- >>> low_res_multimasks, high_res_multimasks, ious, low_res_masks, high_res_masks, obj_ptr, object_score_logits = results
+ >>> (
+ ... low_res_multimasks,
+ ... high_res_multimasks,
+ ... ious,
+ ... low_res_masks,
+ ... high_res_masks,
+ ... obj_ptr,
+ ... object_score_logits,
+ ... ) = results
"""
B = backbone_features.size(0)
device = backbone_features.device
diff --git a/ultralytics/models/sam/modules/tiny_encoder.py b/ultralytics/models/sam/modules/tiny_encoder.py
index 0aca78ed6d..6ce32824c9 100644
--- a/ultralytics/models/sam/modules/tiny_encoder.py
+++ b/ultralytics/models/sam/modules/tiny_encoder.py
@@ -716,7 +716,7 @@ class BasicLayer(nn.Module):
Examples:
>>> layer = BasicLayer(dim=96, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
- >>> x = torch.randn(1, 56*56, 96)
+ >>> x = torch.randn(1, 56 * 56, 96)
>>> output = layer(x)
>>> print(output.shape)
"""
diff --git a/ultralytics/models/sam/modules/utils.py b/ultralytics/models/sam/modules/utils.py
index debc62e8e5..8bfb13760d 100644
--- a/ultralytics/models/sam/modules/utils.py
+++ b/ultralytics/models/sam/modules/utils.py
@@ -22,7 +22,7 @@ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num
Examples:
>>> frame_idx = 5
- >>> cond_frame_outputs = {1: 'a', 3: 'b', 7: 'c', 9: 'd'}
+ >>> cond_frame_outputs = {1: "a", 3: "b", 7: "c", 9: "d"}
>>> max_cond_frame_num = 2
>>> selected, unselected = select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num)
>>> print(selected)
diff --git a/ultralytics/models/sam/predict.py b/ultralytics/models/sam/predict.py
index 034133514c..1118f82b1c 100644
--- a/ultralytics/models/sam/predict.py
+++ b/ultralytics/models/sam/predict.py
@@ -69,8 +69,8 @@ class Predictor(BasePredictor):
Examples:
>>> predictor = Predictor()
- >>> predictor.setup_model(model_path='sam_model.pt')
- >>> predictor.set_image('image.jpg')
+ >>> predictor.setup_model(model_path="sam_model.pt")
+ >>> predictor.set_image("image.jpg")
>>> masks, scores, boxes = predictor.generate()
>>> results = predictor.postprocess((masks, scores, boxes), im, orig_img)
"""
@@ -90,8 +90,8 @@ class Predictor(BasePredictor):
Examples:
>>> predictor = Predictor(cfg=DEFAULT_CFG)
- >>> predictor = Predictor(overrides={'imgsz': 640})
- >>> predictor = Predictor(_callbacks={'on_predict_start': custom_callback})
+ >>> predictor = Predictor(overrides={"imgsz": 640})
+ >>> predictor = Predictor(_callbacks={"on_predict_start": custom_callback})
"""
if overrides is None:
overrides = {}
@@ -188,8 +188,8 @@ class Predictor(BasePredictor):
Examples:
>>> predictor = Predictor()
- >>> predictor.setup_model(model_path='sam_model.pt')
- >>> predictor.set_image('image.jpg')
+ >>> predictor.setup_model(model_path="sam_model.pt")
+ >>> predictor.set_image("image.jpg")
>>> masks, scores, logits = predictor.inference(im, bboxes=[[0, 0, 100, 100]])
"""
# Override prompts if any stored in self.prompts
@@ -475,8 +475,8 @@ class Predictor(BasePredictor):
Examples:
>>> predictor = Predictor()
- >>> predictor.setup_source('path/to/images')
- >>> predictor.setup_source('video.mp4')
+ >>> predictor.setup_source("path/to/images")
+ >>> predictor.setup_source("video.mp4")
>>> predictor.setup_source(None) # Uses default source if available
Notes:
@@ -504,8 +504,8 @@ class Predictor(BasePredictor):
Examples:
>>> predictor = Predictor()
- >>> predictor.set_image('path/to/image.jpg')
- >>> predictor.set_image(cv2.imread('path/to/image.jpg'))
+ >>> predictor.set_image("path/to/image.jpg")
+ >>> predictor.set_image(cv2.imread("path/to/image.jpg"))
Notes:
- This method should be called before performing inference on a new image.
diff --git a/ultralytics/models/yolo/classify/predict.py b/ultralytics/models/yolo/classify/predict.py
index 1ca42fe8ed..266075c6c1 100644
--- a/ultralytics/models/yolo/classify/predict.py
+++ b/ultralytics/models/yolo/classify/predict.py
@@ -21,7 +21,7 @@ class ClassificationPredictor(BasePredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.yolo.classify import ClassificationPredictor
- args = dict(model='yolov8n-cls.pt', source=ASSETS)
+ args = dict(model="yolov8n-cls.pt", source=ASSETS)
predictor = ClassificationPredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/yolo/classify/train.py b/ultralytics/models/yolo/classify/train.py
index 931112a307..a1e465d73f 100644
--- a/ultralytics/models/yolo/classify/train.py
+++ b/ultralytics/models/yolo/classify/train.py
@@ -22,7 +22,7 @@ class ClassificationTrainer(BaseTrainer):
```python
from ultralytics.models.yolo.classify import ClassificationTrainer
- args = dict(model='yolov8n-cls.pt', data='imagenet10', epochs=3)
+ args = dict(model="yolov8n-cls.pt", data="imagenet10", epochs=3)
trainer = ClassificationTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/yolo/classify/val.py b/ultralytics/models/yolo/classify/val.py
index 98d5f78858..e54f04118a 100644
--- a/ultralytics/models/yolo/classify/val.py
+++ b/ultralytics/models/yolo/classify/val.py
@@ -20,7 +20,7 @@ class ClassificationValidator(BaseValidator):
```python
from ultralytics.models.yolo.classify import ClassificationValidator
- args = dict(model='yolov8n-cls.pt', data='imagenet10')
+ args = dict(model="yolov8n-cls.pt", data="imagenet10")
validator = ClassificationValidator(args=args)
validator()
```
diff --git a/ultralytics/models/yolo/detect/predict.py b/ultralytics/models/yolo/detect/predict.py
index 9842928db2..7a1799f2a5 100644
--- a/ultralytics/models/yolo/detect/predict.py
+++ b/ultralytics/models/yolo/detect/predict.py
@@ -14,7 +14,7 @@ class DetectionPredictor(BasePredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.yolo.detect import DetectionPredictor
- args = dict(model='yolov8n.pt', source=ASSETS)
+ args = dict(model="yolov8n.pt", source=ASSETS)
predictor = DetectionPredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/yolo/detect/train.py b/ultralytics/models/yolo/detect/train.py
index 27d172b2e2..5be24c946e 100644
--- a/ultralytics/models/yolo/detect/train.py
+++ b/ultralytics/models/yolo/detect/train.py
@@ -24,7 +24,7 @@ class DetectionTrainer(BaseTrainer):
```python
from ultralytics.models.yolo.detect import DetectionTrainer
- args = dict(model='yolov8n.pt', data='coco8.yaml', epochs=3)
+ args = dict(model="yolov8n.pt", data="coco8.yaml", epochs=3)
trainer = DetectionTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/yolo/detect/val.py b/ultralytics/models/yolo/detect/val.py
index 640d486997..0823f75144 100644
--- a/ultralytics/models/yolo/detect/val.py
+++ b/ultralytics/models/yolo/detect/val.py
@@ -22,7 +22,7 @@ class DetectionValidator(BaseValidator):
```python
from ultralytics.models.yolo.detect import DetectionValidator
- args = dict(model='yolov8n.pt', data='coco8.yaml')
+ args = dict(model="yolov8n.pt", data="coco8.yaml")
validator = DetectionValidator(args=args)
validator()
```
diff --git a/ultralytics/models/yolo/obb/predict.py b/ultralytics/models/yolo/obb/predict.py
index bb8d4d3f13..19308cb6c4 100644
--- a/ultralytics/models/yolo/obb/predict.py
+++ b/ultralytics/models/yolo/obb/predict.py
@@ -16,7 +16,7 @@ class OBBPredictor(DetectionPredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.yolo.obb import OBBPredictor
- args = dict(model='yolov8n-obb.pt', source=ASSETS)
+ args = dict(model="yolov8n-obb.pt", source=ASSETS)
predictor = OBBPredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/yolo/obb/train.py b/ultralytics/models/yolo/obb/train.py
index 40a35a99e7..18def21974 100644
--- a/ultralytics/models/yolo/obb/train.py
+++ b/ultralytics/models/yolo/obb/train.py
@@ -15,7 +15,7 @@ class OBBTrainer(yolo.detect.DetectionTrainer):
```python
from ultralytics.models.yolo.obb import OBBTrainer
- args = dict(model='yolov8n-obb.pt', data='dota8.yaml', epochs=3)
+ args = dict(model="yolov8n-obb.pt", data="dota8.yaml", epochs=3)
trainer = OBBTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/yolo/obb/val.py b/ultralytics/models/yolo/obb/val.py
index 4b335f6a34..b4048af4c6 100644
--- a/ultralytics/models/yolo/obb/val.py
+++ b/ultralytics/models/yolo/obb/val.py
@@ -18,9 +18,9 @@ class OBBValidator(DetectionValidator):
```python
from ultralytics.models.yolo.obb import OBBValidator
- args = dict(model='yolov8n-obb.pt', data='dota8.yaml')
+ args = dict(model="yolov8n-obb.pt", data="dota8.yaml")
validator = OBBValidator(args=args)
- validator(model=args['model'])
+ validator(model=args["model"])
```
"""
diff --git a/ultralytics/models/yolo/pose/predict.py b/ultralytics/models/yolo/pose/predict.py
index 911c424fbb..c9d0a23a6f 100644
--- a/ultralytics/models/yolo/pose/predict.py
+++ b/ultralytics/models/yolo/pose/predict.py
@@ -14,7 +14,7 @@ class PosePredictor(DetectionPredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.yolo.pose import PosePredictor
- args = dict(model='yolov8n-pose.pt', source=ASSETS)
+ args = dict(model="yolov8n-pose.pt", source=ASSETS)
predictor = PosePredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/yolo/pose/train.py b/ultralytics/models/yolo/pose/train.py
index f5229e5081..e52f449cf8 100644
--- a/ultralytics/models/yolo/pose/train.py
+++ b/ultralytics/models/yolo/pose/train.py
@@ -16,7 +16,7 @@ class PoseTrainer(yolo.detect.DetectionTrainer):
```python
from ultralytics.models.yolo.pose import PoseTrainer
- args = dict(model='yolov8n-pose.pt', data='coco8-pose.yaml', epochs=3)
+ args = dict(model="yolov8n-pose.pt", data="coco8-pose.yaml", epochs=3)
trainer = PoseTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/yolo/pose/val.py b/ultralytics/models/yolo/pose/val.py
index ae0c6eeb28..cba42a6ea8 100644
--- a/ultralytics/models/yolo/pose/val.py
+++ b/ultralytics/models/yolo/pose/val.py
@@ -20,7 +20,7 @@ class PoseValidator(DetectionValidator):
```python
from ultralytics.models.yolo.pose import PoseValidator
- args = dict(model='yolov8n-pose.pt', data='coco8-pose.yaml')
+ args = dict(model="yolov8n-pose.pt", data="coco8-pose.yaml")
validator = PoseValidator(args=args)
validator()
```
diff --git a/ultralytics/models/yolo/segment/predict.py b/ultralytics/models/yolo/segment/predict.py
index d007eeea44..736e03ebe4 100644
--- a/ultralytics/models/yolo/segment/predict.py
+++ b/ultralytics/models/yolo/segment/predict.py
@@ -14,7 +14,7 @@ class SegmentationPredictor(DetectionPredictor):
from ultralytics.utils import ASSETS
from ultralytics.models.yolo.segment import SegmentationPredictor
- args = dict(model='yolov8n-seg.pt', source=ASSETS)
+ args = dict(model="yolov8n-seg.pt", source=ASSETS)
predictor = SegmentationPredictor(overrides=args)
predictor.predict_cli()
```
diff --git a/ultralytics/models/yolo/segment/train.py b/ultralytics/models/yolo/segment/train.py
index 126baf20c0..f5b25ed611 100644
--- a/ultralytics/models/yolo/segment/train.py
+++ b/ultralytics/models/yolo/segment/train.py
@@ -16,7 +16,7 @@ class SegmentationTrainer(yolo.detect.DetectionTrainer):
```python
from ultralytics.models.yolo.segment import SegmentationTrainer
- args = dict(model='yolov8n-seg.pt', data='coco8-seg.yaml', epochs=3)
+ args = dict(model="yolov8n-seg.pt", data="coco8-seg.yaml", epochs=3)
trainer = SegmentationTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/models/yolo/segment/val.py b/ultralytics/models/yolo/segment/val.py
index edd1a18565..36ccd9c220 100644
--- a/ultralytics/models/yolo/segment/val.py
+++ b/ultralytics/models/yolo/segment/val.py
@@ -22,7 +22,7 @@ class SegmentationValidator(DetectionValidator):
```python
from ultralytics.models.yolo.segment import SegmentationValidator
- args = dict(model='yolov8n-seg.pt', data='coco8-seg.yaml')
+ args = dict(model="yolov8n-seg.pt", data="coco8-seg.yaml")
validator = SegmentationValidator(args=args)
validator()
```
diff --git a/ultralytics/models/yolo/world/train.py b/ultralytics/models/yolo/world/train.py
index 12d9b43c44..5fffd0974c 100644
--- a/ultralytics/models/yolo/world/train.py
+++ b/ultralytics/models/yolo/world/train.py
@@ -29,7 +29,7 @@ class WorldTrainer(yolo.detect.DetectionTrainer):
```python
from ultralytics.models.yolo.world import WorldModel
- args = dict(model='yolov8s-world.pt', data='coco8.yaml', epochs=3)
+ args = dict(model="yolov8s-world.pt", data="coco8.yaml", epochs=3)
trainer = WorldTrainer(overrides=args)
trainer.train()
```
diff --git a/ultralytics/nn/modules/__init__.py b/ultralytics/nn/modules/__init__.py
index 561f4e772b..2071a2895a 100644
--- a/ultralytics/nn/modules/__init__.py
+++ b/ultralytics/nn/modules/__init__.py
@@ -11,9 +11,9 @@ Example:
x = torch.ones(1, 128, 40, 40)
m = Conv(128, 128)
- f = f'{m._get_name()}.onnx'
+ f = f"{m._get_name()}.onnx"
torch.onnx.export(m, x, f)
- os.system(f'onnxslim {f} {f} && open {f}') # pip install onnxslim
+ os.system(f"onnxslim {f} {f} && open {f}") # pip install onnxslim
```
"""
diff --git a/ultralytics/nn/tasks.py b/ultralytics/nn/tasks.py
index f6feed23bd..17a3722a46 100644
--- a/ultralytics/nn/tasks.py
+++ b/ultralytics/nn/tasks.py
@@ -713,7 +713,7 @@ def temporary_modules(modules=None, attributes=None):
Example:
```python
- with temporary_modules({'old.module': 'new.module'}, {'old.module.attribute': 'new.module.attribute'}):
+ with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}):
import old.module # this will now import new.module
from old.module import attribute # this will now import new.module.attribute
```
diff --git a/ultralytics/solutions/__init__.py b/ultralytics/solutions/__init__.py
index 9b8c25f991..4446c1826e 100644
--- a/ultralytics/solutions/__init__.py
+++ b/ultralytics/solutions/__init__.py
@@ -20,4 +20,5 @@ __all__ = (
"QueueManager",
"SpeedEstimator",
"Analytics",
+ "inference",
)
diff --git a/ultralytics/trackers/byte_tracker.py b/ultralytics/trackers/byte_tracker.py
index 6fd39466cf..31637de920 100644
--- a/ultralytics/trackers/byte_tracker.py
+++ b/ultralytics/trackers/byte_tracker.py
@@ -42,7 +42,7 @@ class STrack(BaseTrack):
Examples:
Initialize and activate a new track
- >>> track = STrack(xywh=[100, 200, 50, 80, 0], score=0.9, cls='person')
+ >>> track = STrack(xywh=[100, 200, 50, 80, 0], score=0.9, cls="person")
>>> track.activate(kalman_filter=KalmanFilterXYAH(), frame_id=1)
"""
@@ -61,7 +61,7 @@ class STrack(BaseTrack):
Examples:
>>> xywh = [100.0, 150.0, 50.0, 75.0, 1]
>>> score = 0.9
- >>> cls = 'person'
+ >>> cls = "person"
>>> track = STrack(xywh, score, cls)
"""
super().__init__()
diff --git a/ultralytics/trackers/utils/gmc.py b/ultralytics/trackers/utils/gmc.py
index 9b98de653d..3619057fa7 100644
--- a/ultralytics/trackers/utils/gmc.py
+++ b/ultralytics/trackers/utils/gmc.py
@@ -33,7 +33,7 @@ class GMC:
Examples:
Create a GMC object and apply it to a frame
- >>> gmc = GMC(method='sparseOptFlow', downscale=2)
+ >>> gmc = GMC(method="sparseOptFlow", downscale=2)
>>> frame = np.array([[1, 2, 3], [4, 5, 6]])
>>> processed_frame = gmc.apply(frame)
>>> print(processed_frame)
@@ -51,7 +51,7 @@ class GMC:
Examples:
Initialize a GMC object with the 'sparseOptFlow' method and a downscale factor of 2
- >>> gmc = GMC(method='sparseOptFlow', downscale=2)
+ >>> gmc = GMC(method="sparseOptFlow", downscale=2)
"""
super().__init__()
@@ -101,7 +101,7 @@ class GMC:
(np.ndarray): Processed frame with applied object detection.
Examples:
- >>> gmc = GMC(method='sparseOptFlow')
+ >>> gmc = GMC(method="sparseOptFlow")
>>> raw_frame = np.random.rand(480, 640, 3)
>>> processed_frame = gmc.apply(raw_frame)
>>> print(processed_frame.shape)
@@ -127,7 +127,7 @@ class GMC:
(np.ndarray): The processed frame with the applied ECC transformation.
Examples:
- >>> gmc = GMC(method='ecc')
+ >>> gmc = GMC(method="ecc")
>>> processed_frame = gmc.applyEcc(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
>>> print(processed_frame)
[[1. 0. 0.]
@@ -173,7 +173,7 @@ class GMC:
(np.ndarray): Processed frame.
Examples:
- >>> gmc = GMC(method='orb')
+ >>> gmc = GMC(method="orb")
>>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
>>> processed_frame = gmc.applyFeatures(raw_frame)
>>> print(processed_frame.shape)
diff --git a/ultralytics/trackers/utils/kalman_filter.py b/ultralytics/trackers/utils/kalman_filter.py
index 24b67d4722..d103d0bb11 100644
--- a/ultralytics/trackers/utils/kalman_filter.py
+++ b/ultralytics/trackers/utils/kalman_filter.py
@@ -268,7 +268,7 @@ class KalmanFilterXYAH:
>>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
>>> covariance = np.eye(8)
>>> measurements = np.array([[1, 1, 1, 1], [2, 2, 1, 1]])
- >>> distances = kf.gating_distance(mean, covariance, measurements, only_position=False, metric='maha')
+ >>> distances = kf.gating_distance(mean, covariance, measurements, only_position=False, metric="maha")
"""
mean, covariance = self.project(mean, covariance)
if only_position:
diff --git a/ultralytics/trackers/utils/matching.py b/ultralytics/trackers/utils/matching.py
index e7a60a4542..70e94cb77e 100644
--- a/ultralytics/trackers/utils/matching.py
+++ b/ultralytics/trackers/utils/matching.py
@@ -121,7 +121,7 @@ def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -
Compute the embedding distance between tracks and detections using cosine metric
>>> tracks = [STrack(...), STrack(...)] # List of track objects with embedding features
>>> detections = [BaseTrack(...), BaseTrack(...)] # List of detection objects with embedding features
- >>> cost_matrix = embedding_distance(tracks, detections, metric='cosine')
+ >>> cost_matrix = embedding_distance(tracks, detections, metric="cosine")
"""
cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py
index f614eea200..b8fc07e1b8 100644
--- a/ultralytics/utils/__init__.py
+++ b/ultralytics/utils/__init__.py
@@ -219,16 +219,19 @@ def plt_settings(rcparams=None, backend="Agg"):
def wrapper(*args, **kwargs):
"""Sets rc parameters and backend, calls the original function, and restores the settings."""
original_backend = plt.get_backend()
- if backend.lower() != original_backend.lower():
+ switch = backend.lower() != original_backend.lower()
+ if switch:
plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
plt.switch_backend(backend)
- with plt.rc_context(rcparams):
- result = func(*args, **kwargs)
-
- if backend != original_backend:
- plt.close("all")
- plt.switch_backend(original_backend)
+ # Plot with backend and always revert to original backend
+ try:
+ with plt.rc_context(rcparams):
+ result = func(*args, **kwargs)
+ finally:
+ if switch:
+ plt.close("all")
+ plt.switch_backend(original_backend)
return result
return wrapper
@@ -710,7 +713,7 @@ def colorstr(*input):
In the second form, 'blue' and 'bold' will be applied by default.
Args:
- *input (str): A sequence of strings where the first n-1 strings are color and style arguments,
+ *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments,
and the last string is the one to be colored.
Supported Colors and Styles:
@@ -762,8 +765,8 @@ def remove_colorstr(input_string):
(str): A new string with all ANSI escape codes removed.
Examples:
- >>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))
- >>> 'hello world'
+ >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
+ >>> "hello world"
"""
ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
return ansi_escape.sub("", input_string)
@@ -777,12 +780,12 @@ class TryExcept(contextlib.ContextDecorator):
As a decorator:
>>> @TryExcept(msg="Error occurred in func", verbose=True)
>>> def func():
- >>> # Function logic here
+ >>> # Function logic here
>>> pass
As a context manager:
>>> with TryExcept(msg="Error occurred in block", verbose=True):
- >>> # Code block here
+ >>> # Code block here
>>> pass
"""
@@ -813,7 +816,7 @@ class Retry(contextlib.ContextDecorator):
Example usage as a decorator:
>>> @Retry(times=3, delay=2)
>>> def test_func():
- >>> # Replace with function logic that may raise exceptions
+ >>> # Replace with function logic that may raise exceptions
>>> return True
"""
diff --git a/ultralytics/utils/benchmarks.py b/ultralytics/utils/benchmarks.py
index c36163e99e..41e62b7b15 100644
--- a/ultralytics/utils/benchmarks.py
+++ b/ultralytics/utils/benchmarks.py
@@ -71,7 +71,7 @@ def benchmark(
```python
from ultralytics.utils.benchmarks import benchmark
- benchmark(model='yolov8n.pt', imgsz=640)
+ benchmark(model="yolov8n.pt", imgsz=640)
```
"""
import pandas as pd # scope for faster 'import ultralytics'
@@ -302,7 +302,7 @@ class ProfileModels:
```python
from ultralytics.utils.benchmarks import ProfileModels
- ProfileModels(['yolov8n.yaml', 'yolov8s.yaml'], imgsz=640).profile()
+ ProfileModels(["yolov8n.yaml", "yolov8s.yaml"], imgsz=640).profile()
```
"""
diff --git a/ultralytics/utils/checks.py b/ultralytics/utils/checks.py
index b9bcef3f6d..bf6746f225 100644
--- a/ultralytics/utils/checks.py
+++ b/ultralytics/utils/checks.py
@@ -23,6 +23,7 @@ from ultralytics.utils import (
ASSETS,
AUTOINSTALL,
IS_COLAB,
+ IS_GIT_DIR,
IS_JUPYTER,
IS_KAGGLE,
IS_PIP_PACKAGE,
@@ -61,7 +62,7 @@ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
```python
from ultralytics.utils.checks import parse_requirements
- parse_requirements(package='ultralytics')
+ parse_requirements(package="ultralytics")
```
"""
@@ -196,16 +197,16 @@ def check_version(
Example:
```python
# Check if current version is exactly 22.04
- check_version(current='22.04', required='==22.04')
+ check_version(current="22.04", required="==22.04")
# Check if current version is greater than or equal to 22.04
- check_version(current='22.10', required='22.04') # assumes '>=' inequality if none passed
+ check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed
# Check if current version is less than or equal to 22.04
- check_version(current='22.04', required='<=22.04')
+ check_version(current="22.04", required="<=22.04")
# Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
- check_version(current='21.10', required='>20.04,<22.04')
+ check_version(current="21.10", required=">20.04,<22.04")
```
"""
if not current: # if current is '' or None
@@ -352,13 +353,13 @@ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=()
from ultralytics.utils.checks import check_requirements
# Check a requirements.txt file
- check_requirements('path/to/requirements.txt')
+ check_requirements("path/to/requirements.txt")
# Check a single package
- check_requirements('ultralytics>=8.0.0')
+ check_requirements("ultralytics>=8.0.0")
# Check multiple packages
- check_requirements(['numpy', 'ultralytics>=8.0.0'])
+ check_requirements(["numpy", "ultralytics>=8.0.0"])
```
"""
@@ -582,10 +583,9 @@ def check_yolo(verbose=True, device=""):
def collect_system_info():
"""Collect and print relevant system information including OS, Python, RAM, CPU, and CUDA."""
-
import psutil
- from ultralytics.utils import ENVIRONMENT, IS_GIT_DIR
+ from ultralytics.utils import ENVIRONMENT # scope to avoid circular import
from ultralytics.utils.torch_utils import get_cpu_info
ram_info = psutil.virtual_memory().total / (1024**3) # Convert bytes to GB
@@ -634,7 +634,7 @@ def check_amp(model):
from ultralytics import YOLO
from ultralytics.utils.checks import check_amp
- model = YOLO('yolov8n.pt').model.cuda()
+ model = YOLO("yolov8n.pt").model.cuda()
check_amp(model)
```
diff --git a/ultralytics/utils/downloads.py b/ultralytics/utils/downloads.py
index de9f63687a..42e2c3ebf1 100644
--- a/ultralytics/utils/downloads.py
+++ b/ultralytics/utils/downloads.py
@@ -75,7 +75,7 @@ def delete_dsstore(path, files_to_delete=(".DS_Store", "__MACOSX")):
```python
from ultralytics.utils.downloads import delete_dsstore
- delete_dsstore('path/to/dir')
+ delete_dsstore("path/to/dir")
```
Note:
@@ -107,7 +107,7 @@ def zip_directory(directory, compress=True, exclude=(".DS_Store", "__MACOSX"), p
```python
from ultralytics.utils.downloads import zip_directory
- file = zip_directory('path/to/dir')
+ file = zip_directory("path/to/dir")
```
"""
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
@@ -153,7 +153,7 @@ def unzip_file(file, path=None, exclude=(".DS_Store", "__MACOSX"), exist_ok=Fals
```python
from ultralytics.utils.downloads import unzip_file
- dir = unzip_file('path/to/file.zip')
+ dir = unzip_file("path/to/file.zip")
```
"""
from zipfile import BadZipFile, ZipFile, is_zipfile
@@ -392,7 +392,7 @@ def get_github_assets(repo="ultralytics/assets", version="latest", retry=False):
Example:
```python
- tag, assets = get_github_assets(repo='ultralytics/assets', version='latest')
+ tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
```
"""
@@ -425,7 +425,7 @@ def attempt_download_asset(file, repo="ultralytics/assets", release="v8.2.0", **
Example:
```python
- file_path = attempt_download_asset('yolov8n.pt', repo='ultralytics/assets', release='latest')
+ file_path = attempt_download_asset("yolov8n.pt", repo="ultralytics/assets", release="latest")
```
"""
from ultralytics.utils import SETTINGS # scoped for circular import
@@ -480,7 +480,7 @@ def download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=
Example:
```python
- download('https://ultralytics.com/assets/example.zip', dir='path/to/dir', unzip=True)
+ download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
```
"""
dir = Path(dir)
diff --git a/ultralytics/utils/files.py b/ultralytics/utils/files.py
index e710c903e5..dd6d5b01df 100644
--- a/ultralytics/utils/files.py
+++ b/ultralytics/utils/files.py
@@ -28,13 +28,13 @@ class WorkingDirectory(contextlib.ContextDecorator):
Examples:
Using as a context manager:
>>> with WorkingDirectory('/path/to/new/dir'):
- >>> # Perform operations in the new directory
+ >>> # Perform operations in the new directory
>>> pass
Using as a decorator:
>>> @WorkingDirectory('/path/to/new/dir')
>>> def some_function():
- >>> # Perform operations in the new directory
+ >>> # Perform operations in the new directory
>>> pass
"""
@@ -69,7 +69,7 @@ def spaces_in_path(path):
Use the context manager to handle paths with spaces:
>>> from ultralytics.utils.files import spaces_in_path
>>> with spaces_in_path('/path/with spaces') as new_path:
- >>> # Your code here
+ >>> # Your code here
"""
# If path has spaces, replace them with underscores
diff --git a/ultralytics/utils/instance.py b/ultralytics/utils/instance.py
index 24bd7b72cb..1e9b912466 100644
--- a/ultralytics/utils/instance.py
+++ b/ultralytics/utils/instance.py
@@ -199,7 +199,7 @@ class Instances:
instances = Instances(
bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
- keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]])
+ keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]),
)
```
diff --git a/ultralytics/utils/metrics.py b/ultralytics/utils/metrics.py
index 80c2f66083..78c77c7261 100644
--- a/ultralytics/utils/metrics.py
+++ b/ultralytics/utils/metrics.py
@@ -445,7 +445,7 @@ def smooth(y, f=0.05):
@plt_settings()
-def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names=(), on_plot=None):
+def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names={}, on_plot=None):
"""Plots a precision-recall curve."""
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
py = np.stack(py, axis=1)
@@ -470,7 +470,7 @@ def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names=(), on_plot=N
@plt_settings()
-def plot_mc_curve(px, py, save_dir=Path("mc_curve.png"), names=(), xlabel="Confidence", ylabel="Metric", on_plot=None):
+def plot_mc_curve(px, py, save_dir=Path("mc_curve.png"), names={}, xlabel="Confidence", ylabel="Metric", on_plot=None):
"""Plots a metric-confidence curve."""
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
@@ -528,7 +528,7 @@ def compute_ap(recall, precision):
def ap_per_class(
- tp, conf, pred_cls, target_cls, plot=False, on_plot=None, save_dir=Path(), names=(), eps=1e-16, prefix=""
+ tp, conf, pred_cls, target_cls, plot=False, on_plot=None, save_dir=Path(), names={}, eps=1e-16, prefix=""
):
"""
Computes the average precision per class for object detection evaluation.
@@ -541,7 +541,7 @@ def ap_per_class(
plot (bool, optional): Whether to plot PR curves or not. Defaults to False.
on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.
save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.
- names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.
+ names (dict, optional): Dict of class names to plot PR curves. Defaults to an empty tuple.
eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.
prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.
@@ -799,13 +799,13 @@ class DetMetrics(SimpleClass):
save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.
plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.
on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
- names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.
+ names (dict of str): A dict of strings that represents the names of the classes. Defaults to an empty tuple.
Attributes:
save_dir (Path): A path to the directory where the output plots will be saved.
plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.
on_plot (func): An optional callback to pass plots path and data when they are rendered.
- names (tuple of str): A tuple of strings that represents the names of the classes.
+ names (dict of str): A dict of strings that represents the names of the classes.
box (Metric): An instance of the Metric class for storing the results of the detection metrics.
speed (dict): A dictionary for storing the execution time of different parts of the detection process.
@@ -822,7 +822,7 @@ class DetMetrics(SimpleClass):
curves_results: TODO
"""
- def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
+ def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names={}) -> None:
"""Initialize a DetMetrics instance with a save directory, plot flag, callback function, and class names."""
self.save_dir = save_dir
self.plot = plot
diff --git a/ultralytics/utils/plotting.py b/ultralytics/utils/plotting.py
index aaca19dc31..b3d52e9d9b 100644
--- a/ultralytics/utils/plotting.py
+++ b/ultralytics/utils/plotting.py
@@ -902,8 +902,8 @@ def save_one_box(xyxy, im, file=Path("im.jpg"), gain=1.02, pad=10, square=False,
from ultralytics.utils.plotting import save_one_box
xyxy = [50, 50, 150, 150]
- im = cv2.imread('image.jpg')
- cropped_im = save_one_box(xyxy, im, file='cropped.jpg', square=True)
+ im = cv2.imread("image.jpg")
+ cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True)
```
"""
@@ -1109,7 +1109,7 @@ def plot_results(file="path/to/results.csv", dir="", segment=False, pose=False,
```python
from ultralytics.utils.plotting import plot_results
- plot_results('path/to/results.csv', segment=True)
+ plot_results("path/to/results.csv", segment=True)
```
"""
import pandas as pd # scope for faster 'import ultralytics'
@@ -1195,7 +1195,7 @@ def plot_tune_results(csv_file="tune_results.csv"):
csv_file (str, optional): Path to the CSV file containing the tuning results. Defaults to 'tune_results.csv'.
Examples:
- >>> plot_tune_results('path/to/tune_results.csv')
+ >>> plot_tune_results("path/to/tune_results.csv")
"""
import pandas as pd # scope for faster 'import ultralytics'
diff --git a/ultralytics/utils/torch_utils.py b/ultralytics/utils/torch_utils.py
index fd24403d5a..7cfdb576c5 100644
--- a/ultralytics/utils/torch_utils.py
+++ b/ultralytics/utils/torch_utils.py
@@ -137,10 +137,10 @@ def select_device(device="", batch=0, newline=False, verbose=True):
devices when using multiple GPUs.
Examples:
- >>> select_device('cuda:0')
+ >>> select_device("cuda:0")
device(type='cuda', index=0)
- >>> select_device('cpu')
+ >>> select_device("cpu")
device(type='cpu')
Note:
@@ -331,11 +331,13 @@ def model_info_for_loggers(trainer):
Example:
YOLOv8n info for loggers
```python
- results = {'model/parameters': 3151904,
- 'model/GFLOPs': 8.746,
- 'model/speed_ONNX(ms)': 41.244,
- 'model/speed_TensorRT(ms)': 3.211,
- 'model/speed_PyTorch(ms)': 18.755}
+ results = {
+ "model/parameters": 3151904,
+ "model/GFLOPs": 8.746,
+ "model/speed_ONNX(ms)": 41.244,
+ "model/speed_TensorRT(ms)": 3.211,
+ "model/speed_PyTorch(ms)": 18.755,
+ }
```
"""
if trainer.args.profile: # profile ONNX and TensorRT times
@@ -542,7 +544,7 @@ def strip_optimizer(f: Union[str, Path] = "best.pt", s: str = "") -> None:
from pathlib import Path
from ultralytics.utils.torch_utils import strip_optimizer
- for f in Path('path/to/model/checkpoints').rglob('*.pt'):
+ for f in Path("path/to/model/checkpoints").rglob("*.pt"):
strip_optimizer(f)
```
diff --git a/ultralytics/utils/tuner.py b/ultralytics/utils/tuner.py
index 1bde002c8a..94deea2a7b 100644
--- a/ultralytics/utils/tuner.py
+++ b/ultralytics/utils/tuner.py
@@ -28,10 +28,10 @@ def run_ray_tune(
from ultralytics import YOLO
# Load a YOLOv8n model
- model = YOLO('yolov8n.pt')
+ model = YOLO("yolov8n.pt")
# Start tuning hyperparameters for YOLOv8n training on the COCO8 dataset
- result_grid = model.tune(data='coco8.yaml', use_ray=True)
+ result_grid = model.tune(data="coco8.yaml", use_ray=True)
```
"""