Reference for ultralytics/models/yolo/segment/val.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/yolo/segment/val.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.yolo.segment.val.SegmentationValidator
Bases: DetectionValidator
A class extending the DetectionValidator class for validation based on a segmentation model.
This validator handles the evaluation of segmentation models, processing both bounding box and mask predictions to compute metrics such as mAP for both detection and segmentation tasks.
Attributes:
Name | Type | Description |
---|---|---|
plot_masks |
List
|
List to store masks for plotting. |
process |
callable
|
Function to process masks based on save_json and save_txt flags. |
args |
namespace
|
Arguments for the validator. |
metrics |
SegmentMetrics
|
Metrics calculator for segmentation tasks. |
stats |
Dict
|
Dictionary to store statistics during validation. |
Examples:
>>> from ultralytics.models.yolo.segment import SegmentationValidator
>>> args = dict(model="yolo11n-seg.pt", data="coco8-seg.yaml")
>>> validator = SegmentationValidator(args=args)
>>> validator()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataloader
|
DataLoader
|
Dataloader to use for validation. |
None
|
save_dir
|
Path
|
Directory to save results. |
None
|
pbar
|
Any
|
Progress bar for displaying progress. |
None
|
args
|
namespace
|
Arguments for the validator. |
None
|
_callbacks
|
List
|
List of callback functions. |
None
|
Source code in ultralytics/models/yolo/segment/val.py
_prepare_batch
Prepare a batch for training or inference by processing images and targets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
si
|
int
|
Batch index. |
required |
batch
|
Dict
|
Batch data containing images and targets. |
required |
Returns:
Type | Description |
---|---|
Dict
|
Prepared batch with processed images and targets. |
Source code in ultralytics/models/yolo/segment/val.py
_prepare_pred
Prepare predictions for evaluation by processing bounding boxes and masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pred
|
Tensor
|
Raw predictions from the model. |
required |
pbatch
|
Dict
|
Prepared batch data. |
required |
proto
|
Tensor
|
Prototype masks for segmentation. |
required |
Returns:
Name | Type | Description |
---|---|---|
predn |
Tensor
|
Processed bounding box predictions. |
pred_masks |
Tensor
|
Processed mask predictions. |
Source code in ultralytics/models/yolo/segment/val.py
_process_batch
_process_batch(
detections,
gt_bboxes,
gt_cls,
pred_masks=None,
gt_masks=None,
overlap=False,
masks=False,
)
Compute correct prediction matrix for a batch based on bounding boxes and optional masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detections
|
Tensor
|
Tensor of shape (N, 6) representing detected bounding boxes and associated confidence scores and class indices. Each row is of the format [x1, y1, x2, y2, conf, class]. |
required |
gt_bboxes
|
Tensor
|
Tensor of shape (M, 4) representing ground truth bounding box coordinates. Each row is of the format [x1, y1, x2, y2]. |
required |
gt_cls
|
Tensor
|
Tensor of shape (M,) representing ground truth class indices. |
required |
pred_masks
|
Tensor
|
Tensor representing predicted masks, if available. The shape should match the ground truth masks. |
None
|
gt_masks
|
Tensor
|
Tensor of shape (M, H, W) representing ground truth masks, if available. |
None
|
overlap
|
bool
|
Flag indicating if overlapping masks should be considered. |
False
|
masks
|
bool
|
Flag indicating if the batch contains mask data. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
A correct prediction matrix of shape (N, 10), where 10 represents different IoU levels. |
Note
- If
masks
is True, the function computes IoU between predicted and ground truth masks. - If
overlap
is True andmasks
is True, overlapping masks are taken into account when computing IoU.
Examples:
>>> detections = torch.tensor([[25, 30, 200, 300, 0.8, 1], [50, 60, 180, 290, 0.75, 0]])
>>> gt_bboxes = torch.tensor([[24, 29, 199, 299], [55, 65, 185, 295]])
>>> gt_cls = torch.tensor([1, 0])
>>> correct_preds = validator._process_batch(detections, gt_bboxes, gt_cls)
Source code in ultralytics/models/yolo/segment/val.py
eval_json
Return COCO-style object detection evaluation metrics.
Source code in ultralytics/models/yolo/segment/val.py
finalize_metrics
Set speed and confusion matrix for evaluation metrics.
get_desc
Return a formatted description of evaluation metrics.
Source code in ultralytics/models/yolo/segment/val.py
init_metrics
Initialize metrics and select mask processing function based on save_json flag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to validate. |
required |
Source code in ultralytics/models/yolo/segment/val.py
plot_predictions
Plot batch predictions with masks and bounding boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict
|
Batch data containing images. |
required |
preds
|
List
|
Predictions from the model. |
required |
ni
|
int
|
Batch index. |
required |
Source code in ultralytics/models/yolo/segment/val.py
plot_val_samples
Plot validation samples with bounding box labels and masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict
|
Batch data containing images and targets. |
required |
ni
|
int
|
Batch index. |
required |
Source code in ultralytics/models/yolo/segment/val.py
postprocess
Post-process YOLO predictions and return output detections with proto.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
List
|
Raw predictions from the model. |
required |
Returns:
Name | Type | Description |
---|---|---|
p |
Tensor
|
Processed detection predictions. |
proto |
Tensor
|
Prototype masks for segmentation. |
Source code in ultralytics/models/yolo/segment/val.py
pred_to_json
Save one JSON result for COCO evaluation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predn
|
Tensor
|
Predictions in the format [x1, y1, x2, y2, conf, cls]. |
required |
filename
|
str
|
Image filename. |
required |
pred_masks
|
ndarray
|
Predicted masks. |
required |
Examples:
>>> result = {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
Source code in ultralytics/models/yolo/segment/val.py
preprocess
Preprocess batch by converting masks to float and sending to device.
save_one_txt
Save YOLO detections to a txt file in normalized coordinates in a specific format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predn
|
Tensor
|
Predictions in the format [x1, y1, x2, y2, conf, cls]. |
required |
pred_masks
|
Tensor
|
Predicted masks. |
required |
save_conf
|
bool
|
Whether to save confidence scores. |
required |
shape
|
Tuple
|
Original image shape. |
required |
file
|
Path
|
File path to save the detections. |
required |
Source code in ultralytics/models/yolo/segment/val.py
update_metrics
Update metrics with the current batch predictions and targets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
List
|
Predictions from the model. |
required |
batch
|
Dict
|
Batch data containing images and targets. |
required |