You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
277 lines
13 KiB
277 lines
13 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
|
||
2 years ago
|
import os
|
||
2 years ago
|
from pathlib import Path
|
||
2 years ago
|
|
||
|
import numpy as np
|
||
|
import torch
|
||
|
|
||
1 year ago
|
from ultralytics.data import build_dataloader, build_yolo_dataset
|
||
|
from ultralytics.engine.validator import BaseValidator
|
||
|
from ultralytics.utils import DEFAULT_CFG, LOGGER, ops
|
||
|
from ultralytics.utils.checks import check_requirements
|
||
|
from ultralytics.utils.metrics import ConfusionMatrix, DetMetrics, box_iou
|
||
|
from ultralytics.utils.plotting import output_to_target, plot_images
|
||
|
from ultralytics.utils.torch_utils import de_parallel
|
||
2 years ago
|
|
||
|
|
||
|
class DetectionValidator(BaseValidator):
|
||
|
|
||
2 years ago
|
def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
|
||
2 years ago
|
"""Initialize detection model with necessary variables and settings."""
|
||
2 years ago
|
super().__init__(dataloader, save_dir, pbar, args, _callbacks)
|
||
2 years ago
|
self.args.task = 'detect'
|
||
2 years ago
|
self.is_coco = False
|
||
|
self.class_map = None
|
||
2 years ago
|
self.metrics = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)
|
||
2 years ago
|
self.iouv = torch.linspace(0.5, 0.95, 10) # iou vector for mAP@0.5:0.95
|
||
2 years ago
|
self.niou = self.iouv.numel()
|
||
2 years ago
|
|
||
|
def preprocess(self, batch):
|
||
2 years ago
|
"""Preprocesses batch of images for YOLO training."""
|
||
2 years ago
|
batch['img'] = batch['img'].to(self.device, non_blocking=True)
|
||
|
batch['img'] = (batch['img'].half() if self.args.half else batch['img'].float()) / 255
|
||
|
for k in ['batch_idx', 'cls', 'bboxes']:
|
||
2 years ago
|
batch[k] = batch[k].to(self.device)
|
||
|
|
||
2 years ago
|
nb = len(batch['img'])
|
||
|
self.lb = [torch.cat([batch['cls'], batch['bboxes']], dim=-1)[batch['batch_idx'] == i]
|
||
2 years ago
|
for i in range(nb)] if self.args.save_hybrid else [] # for autolabelling
|
||
2 years ago
|
|
||
|
return batch
|
||
|
|
||
|
def init_metrics(self, model):
|
||
2 years ago
|
"""Initialize evaluation metrics for YOLO."""
|
||
2 years ago
|
val = self.data.get(self.args.split, '') # validation path
|
||
2 years ago
|
self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt') # is COCO
|
||
2 years ago
|
self.class_map = ops.coco80_to_coco91_class() if self.is_coco else list(range(1000))
|
||
|
self.args.save_json |= self.is_coco and not self.training # run on final val if training COCO
|
||
2 years ago
|
self.names = model.names
|
||
2 years ago
|
self.nc = len(model.names)
|
||
2 years ago
|
self.metrics.names = self.names
|
||
2 years ago
|
self.metrics.plot = self.args.plots
|
||
2 years ago
|
self.confusion_matrix = ConfusionMatrix(nc=self.nc)
|
||
2 years ago
|
self.seen = 0
|
||
|
self.jdict = []
|
||
|
self.stats = []
|
||
2 years ago
|
|
||
|
def get_desc(self):
|
||
2 years ago
|
"""Return a formatted string summarizing class metrics of YOLO model."""
|
||
2 years ago
|
return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')
|
||
2 years ago
|
|
||
|
def postprocess(self, preds):
|
||
2 years ago
|
"""Apply Non-maximum suppression to prediction outputs."""
|
||
2 years ago
|
return ops.non_max_suppression(preds,
|
||
|
self.args.conf,
|
||
|
self.args.iou,
|
||
|
labels=self.lb,
|
||
|
multi_label=True,
|
||
|
agnostic=self.args.single_cls,
|
||
|
max_det=self.args.max_det)
|
||
2 years ago
|
|
||
|
def update_metrics(self, preds, batch):
|
||
2 years ago
|
"""Metrics."""
|
||
2 years ago
|
for si, pred in enumerate(preds):
|
||
2 years ago
|
idx = batch['batch_idx'] == si
|
||
|
cls = batch['cls'][idx]
|
||
|
bbox = batch['bboxes'][idx]
|
||
2 years ago
|
nl, npr = cls.shape[0], pred.shape[0] # number of labels, predictions
|
||
2 years ago
|
shape = batch['ori_shape'][si]
|
||
2 years ago
|
correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
|
||
|
self.seen += 1
|
||
|
|
||
|
if npr == 0:
|
||
|
if nl:
|
||
2 years ago
|
self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))
|
||
2 years ago
|
if self.args.plots:
|
||
2 years ago
|
self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))
|
||
2 years ago
|
continue
|
||
|
|
||
|
# Predictions
|
||
|
if self.args.single_cls:
|
||
|
pred[:, 5] = 0
|
||
|
predn = pred.clone()
|
||
2 years ago
|
ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,
|
||
|
ratio_pad=batch['ratio_pad'][si]) # native-space pred
|
||
2 years ago
|
|
||
|
# Evaluate
|
||
|
if nl:
|
||
2 years ago
|
height, width = batch['img'].shape[2:]
|
||
2 years ago
|
tbox = ops.xywh2xyxy(bbox) * torch.tensor(
|
||
|
(width, height, width, height), device=self.device) # target boxes
|
||
2 years ago
|
ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,
|
||
|
ratio_pad=batch['ratio_pad'][si]) # native-space labels
|
||
2 years ago
|
labelsn = torch.cat((cls, tbox), 1) # native-space labels
|
||
2 years ago
|
correct_bboxes = self._process_batch(predn, labelsn)
|
||
2 years ago
|
# TODO: maybe remove these `self.` arguments as they already are member variable
|
||
|
if self.args.plots:
|
||
|
self.confusion_matrix.process_batch(predn, labelsn)
|
||
2 years ago
|
self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1))) # (conf, pcls, tcls)
|
||
2 years ago
|
|
||
2 years ago
|
# Save
|
||
|
if self.args.save_json:
|
||
2 years ago
|
self.pred_to_json(predn, batch['im_file'][si])
|
||
2 years ago
|
if self.args.save_txt:
|
||
|
file = self.save_dir / 'labels' / f'{Path(batch["im_file"][si]).stem}.txt'
|
||
|
self.save_one_txt(predn, self.args.save_conf, shape, file)
|
||
2 years ago
|
|
||
2 years ago
|
def finalize_metrics(self, *args, **kwargs):
|
||
2 years ago
|
"""Set final values for metrics speed and confusion matrix."""
|
||
2 years ago
|
self.metrics.speed = self.speed
|
||
2 years ago
|
self.metrics.confusion_matrix = self.confusion_matrix
|
||
2 years ago
|
|
||
2 years ago
|
def get_stats(self):
|
||
2 years ago
|
"""Returns metrics statistics and results dictionary."""
|
||
2 years ago
|
stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats)] # to numpy
|
||
|
if len(stats) and stats[0].any():
|
||
2 years ago
|
self.metrics.process(*stats)
|
||
|
self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc) # number of targets per class
|
||
2 years ago
|
return self.metrics.results_dict
|
||
2 years ago
|
|
||
|
def print_results(self):
|
||
2 years ago
|
"""Prints training/validation set metrics per class."""
|
||
2 years ago
|
pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics.keys) # print format
|
||
2 years ago
|
LOGGER.info(pf % ('all', self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))
|
||
2 years ago
|
if self.nt_per_class.sum() == 0:
|
||
2 years ago
|
LOGGER.warning(
|
||
2 years ago
|
f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')
|
||
|
|
||
|
# Print results per class
|
||
2 years ago
|
if self.args.verbose and not self.training and self.nc > 1 and len(self.stats):
|
||
2 years ago
|
for i, c in enumerate(self.metrics.ap_class_index):
|
||
2 years ago
|
LOGGER.info(pf % (self.names[c], self.seen, self.nt_per_class[c], *self.metrics.class_result(i)))
|
||
2 years ago
|
|
||
|
if self.args.plots:
|
||
2 years ago
|
for normalize in True, False:
|
||
2 years ago
|
self.confusion_matrix.plot(save_dir=self.save_dir,
|
||
|
names=self.names.values(),
|
||
|
normalize=normalize,
|
||
|
on_plot=self.on_plot)
|
||
2 years ago
|
|
||
2 years ago
|
def _process_batch(self, detections, labels):
|
||
2 years ago
|
"""
|
||
|
Return correct prediction matrix
|
||
|
Arguments:
|
||
|
detections (array[N, 6]), x1, y1, x2, y2, conf, class
|
||
|
labels (array[M, 5]), class, x1, y1, x2, y2
|
||
|
Returns:
|
||
|
correct (array[N, 10]), for 10 IoU levels
|
||
|
"""
|
||
|
iou = box_iou(labels[:, 1:], detections[:, :4])
|
||
2 years ago
|
correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)
|
||
2 years ago
|
correct_class = labels[:, 0:1] == detections[:, 5]
|
||
2 years ago
|
for i in range(len(self.iouv)):
|
||
|
x = torch.where((iou >= self.iouv[i]) & correct_class) # IoU > threshold and classes match
|
||
2 years ago
|
if x[0].shape[0]:
|
||
|
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),
|
||
|
1).cpu().numpy() # [label, detect, iou]
|
||
|
if x[0].shape[0] > 1:
|
||
|
matches = matches[matches[:, 2].argsort()[::-1]]
|
||
|
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
|
||
|
# matches = matches[matches[:, 2].argsort()[::-1]]
|
||
|
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
|
||
|
correct[matches[:, 1].astype(int), i] = True
|
||
2 years ago
|
return torch.tensor(correct, dtype=torch.bool, device=detections.device)
|
||
2 years ago
|
|
||
2 years ago
|
def build_dataset(self, img_path, mode='val', batch=None):
|
||
|
"""Build YOLO Dataset
|
||
|
|
||
|
Args:
|
||
|
img_path (str): Path to the folder containing images.
|
||
|
mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
|
||
2 years ago
|
batch (int, optional): Size of batches, this is for `rect`. Defaults to None.
|
||
2 years ago
|
"""
|
||
|
gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)
|
||
|
return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)
|
||
|
|
||
2 years ago
|
def get_dataloader(self, dataset_path, batch_size):
|
||
1 year ago
|
"""Construct and return dataloader."""
|
||
2 years ago
|
dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')
|
||
1 year ago
|
return build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1) # return dataloader
|
||
2 years ago
|
|
||
|
def plot_val_samples(self, batch, ni):
|
||
2 years ago
|
"""Plot validation image samples."""
|
||
2 years ago
|
plot_images(batch['img'],
|
||
|
batch['batch_idx'],
|
||
|
batch['cls'].squeeze(-1),
|
||
|
batch['bboxes'],
|
||
|
paths=batch['im_file'],
|
||
|
fname=self.save_dir / f'val_batch{ni}_labels.jpg',
|
||
2 years ago
|
names=self.names,
|
||
|
on_plot=self.on_plot)
|
||
2 years ago
|
|
||
|
def plot_predictions(self, batch, preds, ni):
|
||
2 years ago
|
"""Plots predicted bounding boxes on input images and saves the result."""
|
||
2 years ago
|
plot_images(batch['img'],
|
||
2 years ago
|
*output_to_target(preds, max_det=self.args.max_det),
|
||
2 years ago
|
paths=batch['im_file'],
|
||
2 years ago
|
fname=self.save_dir / f'val_batch{ni}_pred.jpg',
|
||
2 years ago
|
names=self.names,
|
||
|
on_plot=self.on_plot) # pred
|
||
2 years ago
|
|
||
2 years ago
|
def save_one_txt(self, predn, save_conf, shape, file):
|
||
2 years ago
|
"""Save YOLO detections to a txt file in normalized coordinates in a specific format."""
|
||
2 years ago
|
gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
|
||
|
for *xyxy, conf, cls in predn.tolist():
|
||
|
xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
||
|
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
||
|
with open(file, 'a') as f:
|
||
|
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
||
|
|
||
2 years ago
|
def pred_to_json(self, predn, filename):
|
||
2 years ago
|
"""Serialize YOLO predictions to COCO json format."""
|
||
2 years ago
|
stem = Path(filename).stem
|
||
|
image_id = int(stem) if stem.isnumeric() else stem
|
||
|
box = ops.xyxy2xywh(predn[:, :4]) # xywh
|
||
|
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
|
||
|
for p, b in zip(predn.tolist(), box.tolist()):
|
||
|
self.jdict.append({
|
||
|
'image_id': image_id,
|
||
|
'category_id': self.class_map[int(p[5])],
|
||
|
'bbox': [round(x, 3) for x in b],
|
||
|
'score': round(p[4], 5)})
|
||
2 years ago
|
|
||
2 years ago
|
def eval_json(self, stats):
|
||
2 years ago
|
"""Evaluates YOLO output in JSON format and returns performance statistics."""
|
||
2 years ago
|
if self.args.save_json and self.is_coco and len(self.jdict):
|
||
2 years ago
|
anno_json = self.data['path'] / 'annotations/instances_val2017.json' # annotations
|
||
|
pred_json = self.save_dir / 'predictions.json' # predictions
|
||
2 years ago
|
LOGGER.info(f'\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')
|
||
2 years ago
|
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
|
||
2 years ago
|
check_requirements('pycocotools>=2.0.6')
|
||
2 years ago
|
from pycocotools.coco import COCO # noqa
|
||
|
from pycocotools.cocoeval import COCOeval # noqa
|
||
|
|
||
|
for x in anno_json, pred_json:
|
||
2 years ago
|
assert x.is_file(), f'{x} file not found'
|
||
2 years ago
|
anno = COCO(str(anno_json)) # init annotations api
|
||
|
pred = anno.loadRes(str(pred_json)) # init predictions api (must pass string, not Path)
|
||
|
eval = COCOeval(anno, pred, 'bbox')
|
||
|
if self.is_coco:
|
||
|
eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files] # images to eval
|
||
|
eval.evaluate()
|
||
|
eval.accumulate()
|
||
|
eval.summarize()
|
||
2 years ago
|
stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2] # update mAP50-95 and mAP50
|
||
2 years ago
|
except Exception as e:
|
||
2 years ago
|
LOGGER.warning(f'pycocotools unable to run: {e}')
|
||
2 years ago
|
return stats
|
||
2 years ago
|
|
||
2 years ago
|
|
||
2 years ago
|
def val(cfg=DEFAULT_CFG, use_python=False):
|
||
2 years ago
|
"""Validate trained YOLO model on validation dataset."""
|
||
2 years ago
|
model = cfg.model or 'yolov8n.pt'
|
||
|
data = cfg.data or 'coco128.yaml'
|
||
2 years ago
|
|
||
2 years ago
|
args = dict(model=model, data=data)
|
||
2 years ago
|
if use_python:
|
||
|
from ultralytics import YOLO
|
||
|
YOLO(model).val(**args)
|
||
|
else:
|
||
|
validator = DetectionValidator(args=args)
|
||
|
validator(model=args['model'])
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
if __name__ == '__main__':
|
||
2 years ago
|
val()
|