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.
263 lines
13 KiB
263 lines
13 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
|
||
2 years ago
|
from multiprocessing.pool import ThreadPool
|
||
|
from pathlib import Path
|
||
2 years ago
|
|
||
|
import numpy as np
|
||
|
import torch
|
||
|
import torch.nn.functional as F
|
||
|
|
||
1 year ago
|
from ultralytics.models.yolo.detect import DetectionValidator
|
||
|
from ultralytics.utils import DEFAULT_CFG, LOGGER, NUM_THREADS, ops
|
||
|
from ultralytics.utils.checks import check_requirements
|
||
|
from ultralytics.utils.metrics import SegmentMetrics, box_iou, mask_iou
|
||
|
from ultralytics.utils.plotting import output_to_target, plot_images
|
||
2 years ago
|
|
||
2 years ago
|
|
||
|
class SegmentationValidator(DetectionValidator):
|
||
2 years ago
|
|
||
2 years ago
|
def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
|
||
2 years ago
|
"""Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics."""
|
||
2 years ago
|
super().__init__(dataloader, save_dir, pbar, args, _callbacks)
|
||
2 years ago
|
self.args.task = 'segment'
|
||
2 years ago
|
self.metrics = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)
|
||
2 years ago
|
|
||
2 years ago
|
def preprocess(self, batch):
|
||
2 years ago
|
"""Preprocesses batch by converting masks to float and sending to device."""
|
||
2 years ago
|
batch = super().preprocess(batch)
|
||
2 years ago
|
batch['masks'] = batch['masks'].to(self.device).float()
|
||
2 years ago
|
return batch
|
||
|
|
||
|
def init_metrics(self, model):
|
||
2 years ago
|
"""Initialize metrics and select mask processing function based on save_json flag."""
|
||
2 years ago
|
super().init_metrics(model)
|
||
2 years ago
|
self.plot_masks = []
|
||
2 years ago
|
if self.args.save_json:
|
||
2 years ago
|
check_requirements('pycocotools>=2.0.6')
|
||
2 years ago
|
self.process = ops.process_mask_upsample # more accurate
|
||
|
else:
|
||
|
self.process = ops.process_mask # faster
|
||
2 years ago
|
|
||
|
def get_desc(self):
|
||
2 years ago
|
"""Return a formatted description of evaluation metrics."""
|
||
2 years ago
|
return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',
|
||
|
'R', 'mAP50', 'mAP50-95)')
|
||
2 years ago
|
|
||
2 years ago
|
def postprocess(self, preds):
|
||
2 years ago
|
"""Postprocesses YOLO predictions and returns output detections with proto."""
|
||
2 years ago
|
p = ops.non_max_suppression(preds[0],
|
||
2 years ago
|
self.args.conf,
|
||
|
self.args.iou,
|
||
2 years ago
|
labels=self.lb,
|
||
|
multi_label=True,
|
||
|
agnostic=self.args.single_cls,
|
||
|
max_det=self.args.max_det,
|
||
2 years ago
|
nc=self.nc)
|
||
|
proto = preds[1][-1] if len(preds[1]) == 3 else preds[1] # second output is len 3 if pt, but only 1 if exported
|
||
|
return p, proto
|
||
2 years ago
|
|
||
|
def update_metrics(self, preds, batch):
|
||
2 years ago
|
"""Metrics."""
|
||
2 years ago
|
for si, (pred, proto) in enumerate(zip(preds[0], preds[1])):
|
||
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_masks = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
|
||
|
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, correct_masks, *torch.zeros(
|
||
2 years ago
|
(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
|
||
|
|
||
|
# Masks
|
||
2 years ago
|
midx = [si] if self.args.overlap_mask else idx
|
||
2 years ago
|
gt_masks = batch['masks'][midx]
|
||
|
pred_masks = self.process(proto, pred[:, 6:], pred[:, :4], shape=batch['img'][si].shape[1:])
|
||
2 years ago
|
|
||
|
# 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
|
||
|
correct_masks = self._process_batch(predn,
|
||
|
labelsn,
|
||
|
pred_masks,
|
||
|
gt_masks,
|
||
|
overlap=self.args.overlap_mask,
|
||
|
masks=True)
|
||
2 years ago
|
if self.args.plots:
|
||
|
self.confusion_matrix.process_batch(predn, labelsn)
|
||
2 years ago
|
|
||
|
# Append correct_masks, correct_boxes, pconf, pcls, tcls
|
||
2 years ago
|
self.stats.append((correct_bboxes, correct_masks, pred[:, 4], pred[:, 5], cls.squeeze(-1)))
|
||
2 years ago
|
|
||
|
pred_masks = torch.as_tensor(pred_masks, dtype=torch.uint8)
|
||
2 years ago
|
if self.args.plots and self.batch_i < 3:
|
||
2 years ago
|
self.plot_masks.append(pred_masks[:15].cpu()) # filter top 15 to plot
|
||
2 years ago
|
|
||
2 years ago
|
# Save
|
||
2 years ago
|
if self.args.save_json:
|
||
2 years ago
|
pred_masks = ops.scale_image(pred_masks.permute(1, 2, 0).contiguous().cpu().numpy(),
|
||
2 years ago
|
shape,
|
||
2 years ago
|
ratio_pad=batch['ratio_pad'][si])
|
||
|
self.pred_to_json(predn, batch['im_file'][si], pred_masks)
|
||
2 years ago
|
# if self.args.save_txt:
|
||
|
# save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')
|
||
2 years ago
|
|
||
2 years ago
|
def finalize_metrics(self, *args, **kwargs):
|
||
2 years ago
|
"""Sets speed and confusion matrix for evaluation metrics."""
|
||
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 _process_batch(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):
|
||
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
|
||
|
"""
|
||
|
if masks:
|
||
|
if overlap:
|
||
|
nl = len(labels)
|
||
|
index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1
|
||
|
gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640)
|
||
|
gt_masks = torch.where(gt_masks == index, 1.0, 0.0)
|
||
|
if gt_masks.shape[1:] != pred_masks.shape[1:]:
|
||
2 years ago
|
gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]
|
||
2 years ago
|
gt_masks = gt_masks.gt_(0.5)
|
||
|
iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))
|
||
|
else: # boxes
|
||
|
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
|
|
||
|
def plot_val_samples(self, batch, ni):
|
||
2 years ago
|
"""Plots validation samples with bounding box labels."""
|
||
2 years ago
|
plot_images(batch['img'],
|
||
|
batch['batch_idx'],
|
||
|
batch['cls'].squeeze(-1),
|
||
|
batch['bboxes'],
|
||
|
batch['masks'],
|
||
|
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 batch predictions with masks and bounding boxes."""
|
||
2 years ago
|
plot_images(
|
||
|
batch['img'],
|
||
|
*output_to_target(preds[0], max_det=15), # not set to self.args.max_det due to slow plotting speed
|
||
|
torch.cat(self.plot_masks, dim=0) if len(self.plot_masks) else self.plot_masks,
|
||
|
paths=batch['im_file'],
|
||
|
fname=self.save_dir / f'val_batch{ni}_pred.jpg',
|
||
|
names=self.names,
|
||
|
on_plot=self.on_plot) # pred
|
||
2 years ago
|
self.plot_masks.clear()
|
||
2 years ago
|
|
||
2 years ago
|
def pred_to_json(self, predn, filename, pred_masks):
|
||
2 years ago
|
"""Save one JSON result."""
|
||
2 years ago
|
# Example result = {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
|
||
|
from pycocotools.mask import encode # noqa
|
||
2 years ago
|
|
||
|
def single_encode(x):
|
||
2 years ago
|
"""Encode predicted masks as RLE and append results to jdict."""
|
||
2 years ago
|
rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]
|
||
|
rle['counts'] = rle['counts'].decode('utf-8')
|
||
2 years ago
|
return rle
|
||
|
|
||
|
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
|
||
|
pred_masks = np.transpose(pred_masks, (2, 0, 1))
|
||
|
with ThreadPool(NUM_THREADS) as pool:
|
||
|
rles = pool.map(single_encode, pred_masks)
|
||
|
for i, (p, b) in enumerate(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),
|
||
|
'segmentation': rles[i]})
|
||
|
|
||
|
def eval_json(self, stats):
|
||
2 years ago
|
"""Return COCO-style object detection evaluation metrics."""
|
||
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
|
||
|
check_requirements('pycocotools>=2.0.6')
|
||
|
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)
|
||
|
for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):
|
||
|
if self.is_coco:
|
||
2 years ago
|
eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files] # im to eval
|
||
2 years ago
|
eval.evaluate()
|
||
|
eval.accumulate()
|
||
|
eval.summarize()
|
||
|
idx = i * 4 + 2
|
||
2 years ago
|
stats[self.metrics.keys[idx + 1]], stats[
|
||
|
self.metrics.keys[idx]] = 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
|
def val(cfg=DEFAULT_CFG, use_python=False):
|
||
2 years ago
|
"""Validate trained YOLO model on validation data."""
|
||
2 years ago
|
model = cfg.model or 'yolov8n-seg.pt'
|
||
|
data = cfg.data or 'coco128-seg.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 = SegmentationValidator(args=args)
|
||
|
validator(model=args['model'])
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
if __name__ == '__main__':
|
||
2 years ago
|
val()
|