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.
615 lines
24 KiB
615 lines
24 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
"""
|
||
|
Ultralytics Results, Boxes and Masks classes for handling inference results
|
||
|
|
||
2 years ago
|
Usage: See https://docs.ultralytics.com/modes/predict/
|
||
2 years ago
|
"""
|
||
|
|
||
2 years ago
|
from copy import deepcopy
|
||
2 years ago
|
from functools import lru_cache
|
||
2 years ago
|
from pathlib import Path
|
||
2 years ago
|
|
||
|
import numpy as np
|
||
|
import torch
|
||
|
|
||
1 year ago
|
from ultralytics.data.augment import LetterBox
|
||
|
from ultralytics.utils import LOGGER, SimpleClass, deprecation_warn, ops
|
||
|
from ultralytics.utils.plotting import Annotator, colors, save_one_box
|
||
2 years ago
|
|
||
|
|
||
2 years ago
|
class BaseTensor(SimpleClass):
|
||
|
"""
|
||
2 years ago
|
Base tensor class with additional methods for easy manipulation and device handling.
|
||
2 years ago
|
"""
|
||
|
|
||
2 years ago
|
def __init__(self, data, orig_shape) -> None:
|
||
2 years ago
|
"""Initialize BaseTensor with data and original shape.
|
||
|
|
||
|
Args:
|
||
|
data (torch.Tensor | np.ndarray): Predictions, such as bboxes, masks and keypoints.
|
||
|
orig_shape (tuple): Original shape of image.
|
||
|
"""
|
||
|
assert isinstance(data, (torch.Tensor, np.ndarray))
|
||
2 years ago
|
self.data = data
|
||
2 years ago
|
self.orig_shape = orig_shape
|
||
|
|
||
|
@property
|
||
|
def shape(self):
|
||
2 years ago
|
"""Return the shape of the data tensor."""
|
||
2 years ago
|
return self.data.shape
|
||
|
|
||
|
def cpu(self):
|
||
2 years ago
|
"""Return a copy of the tensor on CPU memory."""
|
||
2 years ago
|
return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape)
|
||
2 years ago
|
|
||
|
def numpy(self):
|
||
2 years ago
|
"""Return a copy of the tensor as a numpy array."""
|
||
2 years ago
|
return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.numpy(), self.orig_shape)
|
||
2 years ago
|
|
||
|
def cuda(self):
|
||
2 years ago
|
"""Return a copy of the tensor on GPU memory."""
|
||
2 years ago
|
return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape)
|
||
2 years ago
|
|
||
|
def to(self, *args, **kwargs):
|
||
2 years ago
|
"""Return a copy of the tensor with the specified device and dtype."""
|
||
2 years ago
|
return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)
|
||
2 years ago
|
|
||
|
def __len__(self): # override len(results)
|
||
2 years ago
|
"""Return the length of the data tensor."""
|
||
2 years ago
|
return len(self.data)
|
||
|
|
||
|
def __getitem__(self, idx):
|
||
2 years ago
|
"""Return a BaseTensor with the specified index of the data tensor."""
|
||
2 years ago
|
return self.__class__(self.data[idx], self.orig_shape)
|
||
|
|
||
|
|
||
2 years ago
|
class Results(SimpleClass):
|
||
2 years ago
|
"""
|
||
2 years ago
|
A class for storing and manipulating inference results.
|
||
2 years ago
|
|
||
2 years ago
|
Args:
|
||
|
orig_img (numpy.ndarray): The original image as a numpy array.
|
||
|
path (str): The path to the image file.
|
||
2 years ago
|
names (dict): A dictionary of class names.
|
||
2 years ago
|
boxes (torch.tensor, optional): A 2D tensor of bounding box coordinates for each detection.
|
||
|
masks (torch.tensor, optional): A 3D tensor of detection masks, where each mask is a binary image.
|
||
|
probs (torch.tensor, optional): A 1D tensor of probabilities of each class for classification task.
|
||
2 years ago
|
keypoints (List[List[float]], optional): A list of detected keypoints for each object.
|
||
|
|
||
2 years ago
|
|
||
2 years ago
|
Attributes:
|
||
|
orig_img (numpy.ndarray): The original image as a numpy array.
|
||
|
orig_shape (tuple): The original image shape in (height, width) format.
|
||
|
boxes (Boxes, optional): A Boxes object containing the detection bounding boxes.
|
||
|
masks (Masks, optional): A Masks object containing the detection masks.
|
||
2 years ago
|
probs (Probs, optional): A Probs object containing probabilities of each class for classification task.
|
||
2 years ago
|
names (dict): A dictionary of class names.
|
||
2 years ago
|
path (str): The path to the image file.
|
||
2 years ago
|
keypoints (Keypoints, optional): A Keypoints object containing detected keypoints for each object.
|
||
2 years ago
|
speed (dict): A dictionary of preprocess, inference and postprocess speeds in milliseconds per image.
|
||
2 years ago
|
_keys (tuple): A tuple of attribute names for non-empty attributes.
|
||
|
"""
|
||
2 years ago
|
|
||
2 years ago
|
def __init__(self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None) -> None:
|
||
2 years ago
|
"""Initialize the Results class."""
|
||
2 years ago
|
self.orig_img = orig_img
|
||
|
self.orig_shape = orig_img.shape[:2]
|
||
2 years ago
|
self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None # native size boxes
|
||
|
self.masks = Masks(masks, self.orig_shape) if masks is not None else None # native size or imgsz masks
|
||
2 years ago
|
self.probs = Probs(probs) if probs is not None else None
|
||
|
self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None
|
||
2 years ago
|
self.speed = {'preprocess': None, 'inference': None, 'postprocess': None} # milliseconds per image
|
||
2 years ago
|
self.names = names
|
||
2 years ago
|
self.path = path
|
||
2 years ago
|
self.save_dir = None
|
||
2 years ago
|
self._keys = ('boxes', 'masks', 'probs', 'keypoints')
|
||
2 years ago
|
|
||
|
def __getitem__(self, idx):
|
||
2 years ago
|
"""Return a Results object for the specified index."""
|
||
2 years ago
|
r = self.new()
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
setattr(r, k, getattr(self, k)[idx])
|
||
2 years ago
|
return r
|
||
|
|
||
2 years ago
|
def update(self, boxes=None, masks=None, probs=None):
|
||
2 years ago
|
"""Update the boxes, masks, and probs attributes of the Results object."""
|
||
2 years ago
|
if boxes is not None:
|
||
|
self.boxes = Boxes(boxes, self.orig_shape)
|
||
|
if masks is not None:
|
||
|
self.masks = Masks(masks, self.orig_shape)
|
||
2 years ago
|
if probs is not None:
|
||
2 years ago
|
self.probs = probs
|
||
|
|
||
2 years ago
|
def cpu(self):
|
||
2 years ago
|
"""Return a copy of the Results object with all tensors on CPU memory."""
|
||
2 years ago
|
r = self.new()
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
setattr(r, k, getattr(self, k).cpu())
|
||
2 years ago
|
return r
|
||
|
|
||
|
def numpy(self):
|
||
2 years ago
|
"""Return a copy of the Results object with all tensors as numpy arrays."""
|
||
2 years ago
|
r = self.new()
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
setattr(r, k, getattr(self, k).numpy())
|
||
2 years ago
|
return r
|
||
|
|
||
|
def cuda(self):
|
||
2 years ago
|
"""Return a copy of the Results object with all tensors on GPU memory."""
|
||
2 years ago
|
r = self.new()
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
setattr(r, k, getattr(self, k).cuda())
|
||
2 years ago
|
return r
|
||
|
|
||
|
def to(self, *args, **kwargs):
|
||
2 years ago
|
"""Return a copy of the Results object with tensors on the specified device and dtype."""
|
||
2 years ago
|
r = self.new()
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
setattr(r, k, getattr(self, k).to(*args, **kwargs))
|
||
2 years ago
|
return r
|
||
|
|
||
|
def __len__(self):
|
||
2 years ago
|
"""Return the number of detections in the Results object."""
|
||
2 years ago
|
for k in self.keys:
|
||
2 years ago
|
return len(getattr(self, k))
|
||
2 years ago
|
|
||
2 years ago
|
def new(self):
|
||
2 years ago
|
"""Return a new Results object with the same image, path, and names."""
|
||
2 years ago
|
return Results(orig_img=self.orig_img, path=self.path, names=self.names)
|
||
|
|
||
2 years ago
|
@property
|
||
|
def keys(self):
|
||
2 years ago
|
"""Return a list of non-empty attribute names."""
|
||
2 years ago
|
return [k for k in self._keys if getattr(self, k) is not None]
|
||
|
|
||
2 years ago
|
def plot(
|
||
|
self,
|
||
|
conf=True,
|
||
|
line_width=None,
|
||
|
font_size=None,
|
||
|
font='Arial.ttf',
|
||
|
pil=False,
|
||
|
img=None,
|
||
1 year ago
|
im_gpu=None,
|
||
2 years ago
|
kpt_line=True,
|
||
2 years ago
|
labels=True,
|
||
|
boxes=True,
|
||
|
masks=True,
|
||
|
probs=True,
|
||
|
**kwargs # deprecated args TODO: remove support in 8.2
|
||
|
):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
conf (bool): Whether to plot the detection confidence score.
|
||
2 years ago
|
line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.
|
||
|
font_size (float, optional): The font size of the text. If None, it is scaled to the image size.
|
||
2 years ago
|
font (str): The font to use for the text.
|
||
|
pil (bool): Whether to return the image as a PIL Image.
|
||
2 years ago
|
img (numpy.ndarray): Plot to another image. if not, plot to original image.
|
||
1 year ago
|
im_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.
|
||
2 years ago
|
kpt_line (bool): Whether to draw lines connecting keypoints.
|
||
2 years ago
|
labels (bool): Whether to plot the label of bounding boxes.
|
||
|
boxes (bool): Whether to plot the bounding boxes.
|
||
|
masks (bool): Whether to plot the masks.
|
||
|
probs (bool): Whether to plot classification probability
|
||
2 years ago
|
|
||
|
Returns:
|
||
2 years ago
|
(numpy.ndarray): A numpy array of the annotated image.
|
||
2 years ago
|
"""
|
||
2 years ago
|
if img is None and isinstance(self.orig_img, torch.Tensor):
|
||
2 years ago
|
img = np.ascontiguousarray(self.orig_img[0].permute(1, 2, 0).cpu().detach().numpy()) * 255
|
||
2 years ago
|
|
||
2 years ago
|
# Deprecation warn TODO: remove in 8.2
|
||
|
if 'show_conf' in kwargs:
|
||
|
deprecation_warn('show_conf', 'conf')
|
||
|
conf = kwargs['show_conf']
|
||
|
assert type(conf) == bool, '`show_conf` should be of boolean type, i.e, show_conf=True/False'
|
||
|
|
||
2 years ago
|
if 'line_thickness' in kwargs:
|
||
2 years ago
|
deprecation_warn('line_thickness', 'line_width')
|
||
|
line_width = kwargs['line_thickness']
|
||
|
assert type(line_width) == int, '`line_width` should be of int type, i.e, line_width=3'
|
||
|
|
||
2 years ago
|
names = self.names
|
||
2 years ago
|
pred_boxes, show_boxes = self.boxes, boxes
|
||
|
pred_masks, show_masks = self.masks, masks
|
||
|
pred_probs, show_probs = self.probs, probs
|
||
1 year ago
|
annotator = Annotator(
|
||
|
deepcopy(self.orig_img if img is None else img),
|
||
|
line_width,
|
||
|
font_size,
|
||
|
font,
|
||
|
pil or (pred_probs is not None and show_probs), # Classify tasks default to pil=True
|
||
|
example=names)
|
||
|
|
||
|
# Plot Segment results
|
||
2 years ago
|
if pred_masks and show_masks:
|
||
1 year ago
|
if im_gpu is None:
|
||
2 years ago
|
img = LetterBox(pred_masks.shape[1:])(image=annotator.result())
|
||
1 year ago
|
im_gpu = torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device).permute(
|
||
2 years ago
|
2, 0, 1).flip(0).contiguous() / 255
|
||
2 years ago
|
idx = pred_boxes.cls if pred_boxes else range(len(pred_masks))
|
||
1 year ago
|
annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=im_gpu)
|
||
2 years ago
|
|
||
1 year ago
|
# Plot Detect results
|
||
2 years ago
|
if pred_boxes and show_boxes:
|
||
|
for d in reversed(pred_boxes):
|
||
|
c, conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())
|
||
2 years ago
|
name = ('' if id is None else f'id:{id} ') + names[c]
|
||
2 years ago
|
label = (f'{name} {conf:.2f}' if conf else name) if labels else None
|
||
2 years ago
|
annotator.box_label(d.xyxy.squeeze(), label, color=colors(c, True))
|
||
|
|
||
1 year ago
|
# Plot Classify results
|
||
2 years ago
|
if pred_probs is not None and show_probs:
|
||
1 year ago
|
text = ',\n'.join(f'{names[j] if names else j} {pred_probs.data[j]:.2f}' for j in pred_probs.top5)
|
||
|
x = round(self.orig_shape[0] * 0.03)
|
||
|
annotator.text([x, x], text, txt_color=(255, 255, 255)) # TODO: allow setting colors
|
||
2 years ago
|
|
||
1 year ago
|
# Plot Pose results
|
||
|
if self.keypoints is not None:
|
||
|
for k in reversed(self.keypoints.data):
|
||
2 years ago
|
annotator.kpts(k, self.orig_shape, kpt_line=kpt_line)
|
||
|
|
||
2 years ago
|
return annotator.result()
|
||
2 years ago
|
|
||
2 years ago
|
def verbose(self):
|
||
|
"""
|
||
2 years ago
|
Return log string for each task.
|
||
2 years ago
|
"""
|
||
|
log_string = ''
|
||
|
probs = self.probs
|
||
|
boxes = self.boxes
|
||
|
if len(self) == 0:
|
||
2 years ago
|
return log_string if probs is not None else f'{log_string}(no detections), '
|
||
2 years ago
|
if probs is not None:
|
||
2 years ago
|
log_string += f"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, "
|
||
2 years ago
|
if boxes:
|
||
|
for c in boxes.cls.unique():
|
||
|
n = (boxes.cls == c).sum() # detections per class
|
||
|
log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
|
||
|
return log_string
|
||
|
|
||
|
def save_txt(self, txt_file, save_conf=False):
|
||
2 years ago
|
"""
|
||
|
Save predictions into txt file.
|
||
2 years ago
|
|
||
|
Args:
|
||
|
txt_file (str): txt file path.
|
||
|
save_conf (bool): save confidence score or not.
|
||
|
"""
|
||
|
boxes = self.boxes
|
||
|
masks = self.masks
|
||
|
probs = self.probs
|
||
|
kpts = self.keypoints
|
||
|
texts = []
|
||
|
if probs is not None:
|
||
2 years ago
|
# Classify
|
||
2 years ago
|
[texts.append(f'{probs.data[j]:.2f} {self.names[j]}') for j in probs.top5]
|
||
2 years ago
|
elif boxes:
|
||
2 years ago
|
# Detect/segment/pose
|
||
2 years ago
|
for j, d in enumerate(boxes):
|
||
|
c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())
|
||
|
line = (c, *d.xywhn.view(-1))
|
||
|
if masks:
|
||
|
seg = masks[j].xyn[0].copy().reshape(-1) # reversed mask.xyn, (n,2) to (n*2)
|
||
|
line = (c, *seg)
|
||
|
if kpts is not None:
|
||
1 year ago
|
kpt = torch.cat((kpts[j].xyn, kpts[j].conf[..., None]), 2) if kpts[j].has_visible else kpts[j].xyn
|
||
|
line += (*kpt.reshape(-1).tolist(), )
|
||
2 years ago
|
line += (conf, ) * save_conf + (() if id is None else (id, ))
|
||
|
texts.append(('%g ' * len(line)).rstrip() % line)
|
||
|
|
||
2 years ago
|
if texts:
|
||
|
with open(txt_file, 'a') as f:
|
||
|
f.writelines(text + '\n' for text in texts)
|
||
2 years ago
|
|
||
|
def save_crop(self, save_dir, file_name=Path('im.jpg')):
|
||
2 years ago
|
"""
|
||
|
Save cropped predictions to `save_dir/cls/file_name.jpg`.
|
||
2 years ago
|
|
||
|
Args:
|
||
|
save_dir (str | pathlib.Path): Save path.
|
||
|
file_name (str | pathlib.Path): File name.
|
||
|
"""
|
||
|
if self.probs is not None:
|
||
2 years ago
|
LOGGER.warning('WARNING ⚠️ Classify task do not support `save_crop`.')
|
||
2 years ago
|
return
|
||
|
if isinstance(save_dir, str):
|
||
|
save_dir = Path(save_dir)
|
||
|
if isinstance(file_name, str):
|
||
|
file_name = Path(file_name)
|
||
|
for d in self.boxes:
|
||
|
save_one_box(d.xyxy,
|
||
|
self.orig_img.copy(),
|
||
|
file=save_dir / self.names[int(d.cls)] / f'{file_name.stem}.jpg',
|
||
|
BGR=True)
|
||
|
|
||
2 years ago
|
def pandas(self):
|
||
|
"""Convert the object to a pandas DataFrame (not yet implemented)."""
|
||
|
LOGGER.warning("WARNING ⚠️ 'Results.pandas' method is not yet implemented.")
|
||
|
|
||
|
def tojson(self, normalize=False):
|
||
|
"""Convert the object to JSON format."""
|
||
2 years ago
|
if self.probs is not None:
|
||
|
LOGGER.warning('Warning: Classify task do not support `tojson` yet.')
|
||
|
return
|
||
|
|
||
2 years ago
|
import json
|
||
|
|
||
|
# Create list of detection dictionaries
|
||
|
results = []
|
||
|
data = self.boxes.data.cpu().tolist()
|
||
|
h, w = self.orig_shape if normalize else (1, 1)
|
||
|
for i, row in enumerate(data):
|
||
|
box = {'x1': row[0] / w, 'y1': row[1] / h, 'x2': row[2] / w, 'y2': row[3] / h}
|
||
|
conf = row[4]
|
||
|
id = int(row[5])
|
||
|
name = self.names[id]
|
||
|
result = {'name': name, 'class': id, 'confidence': conf, 'box': box}
|
||
|
if self.masks:
|
||
|
x, y = self.masks.xy[i][:, 0], self.masks.xy[i][:, 1] # numpy array
|
||
|
result['segments'] = {'x': (x / w).tolist(), 'y': (y / h).tolist()}
|
||
|
if self.keypoints is not None:
|
||
2 years ago
|
x, y, visible = self.keypoints[i].data[0].cpu().unbind(dim=1) # torch Tensor
|
||
2 years ago
|
result['keypoints'] = {'x': (x / w).tolist(), 'y': (y / h).tolist(), 'visible': visible.tolist()}
|
||
|
results.append(result)
|
||
|
|
||
|
# Convert detections to JSON
|
||
|
return json.dumps(results, indent=2)
|
||
|
|
||
2 years ago
|
|
||
2 years ago
|
class Boxes(BaseTensor):
|
||
2 years ago
|
"""
|
||
|
A class for storing and manipulating detection boxes.
|
||
|
|
||
|
Args:
|
||
2 years ago
|
boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes,
|
||
2 years ago
|
with shape (num_boxes, 6). The last two columns should contain confidence and class values.
|
||
|
orig_shape (tuple): Original image size, in the format (height, width).
|
||
|
|
||
|
Attributes:
|
||
2 years ago
|
boxes (torch.Tensor | numpy.ndarray): The detection boxes with shape (num_boxes, 6).
|
||
|
orig_shape (torch.Tensor | numpy.ndarray): Original image size, in the format (height, width).
|
||
2 years ago
|
is_track (bool): True if the boxes also include track IDs, False otherwise.
|
||
2 years ago
|
|
||
|
Properties:
|
||
2 years ago
|
xyxy (torch.Tensor | numpy.ndarray): The boxes in xyxy format.
|
||
|
conf (torch.Tensor | numpy.ndarray): The confidence values of the boxes.
|
||
|
cls (torch.Tensor | numpy.ndarray): The class values of the boxes.
|
||
|
id (torch.Tensor | numpy.ndarray): The track IDs of the boxes (if available).
|
||
|
xywh (torch.Tensor | numpy.ndarray): The boxes in xywh format.
|
||
|
xyxyn (torch.Tensor | numpy.ndarray): The boxes in xyxy format normalized by original image size.
|
||
|
xywhn (torch.Tensor | numpy.ndarray): The boxes in xywh format normalized by original image size.
|
||
2 years ago
|
data (torch.Tensor): The raw bboxes tensor
|
||
2 years ago
|
|
||
|
Methods:
|
||
|
cpu(): Move the object to CPU memory.
|
||
|
numpy(): Convert the object to a numpy array.
|
||
|
cuda(): Move the object to CUDA memory.
|
||
|
to(*args, **kwargs): Move the object to the specified device.
|
||
|
pandas(): Convert the object to a pandas DataFrame (not yet implemented).
|
||
2 years ago
|
"""
|
||
|
|
||
|
def __init__(self, boxes, orig_shape) -> None:
|
||
2 years ago
|
"""Initialize the Boxes class."""
|
||
2 years ago
|
if boxes.ndim == 1:
|
||
|
boxes = boxes[None, :]
|
||
2 years ago
|
n = boxes.shape[-1]
|
||
2 years ago
|
assert n in (6, 7), f'expected `n` in [6, 7], but got {n}' # xyxy, (track_id), conf, cls
|
||
2 years ago
|
super().__init__(boxes, orig_shape)
|
||
2 years ago
|
self.is_track = n == 7
|
||
2 years ago
|
self.orig_shape = orig_shape
|
||
2 years ago
|
|
||
|
@property
|
||
|
def xyxy(self):
|
||
2 years ago
|
"""Return the boxes in xyxy format."""
|
||
2 years ago
|
return self.data[:, :4]
|
||
2 years ago
|
|
||
|
@property
|
||
|
def conf(self):
|
||
2 years ago
|
"""Return the confidence values of the boxes."""
|
||
2 years ago
|
return self.data[:, -2]
|
||
2 years ago
|
|
||
|
@property
|
||
|
def cls(self):
|
||
2 years ago
|
"""Return the class values of the boxes."""
|
||
2 years ago
|
return self.data[:, -1]
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
def id(self):
|
||
2 years ago
|
"""Return the track IDs of the boxes (if available)."""
|
||
2 years ago
|
return self.data[:, -3] if self.is_track else None
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
@lru_cache(maxsize=2) # maxsize 1 should suffice
|
||
|
def xywh(self):
|
||
2 years ago
|
"""Return the boxes in xywh format."""
|
||
2 years ago
|
return ops.xyxy2xywh(self.xyxy)
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=2)
|
||
|
def xyxyn(self):
|
||
2 years ago
|
"""Return the boxes in xyxy format normalized by original image size."""
|
||
2 years ago
|
xyxy = self.xyxy.clone() if isinstance(self.xyxy, torch.Tensor) else np.copy(self.xyxy)
|
||
|
xyxy[..., [0, 2]] /= self.orig_shape[1]
|
||
|
xyxy[..., [1, 3]] /= self.orig_shape[0]
|
||
|
return xyxy
|
||
2 years ago
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=2)
|
||
|
def xywhn(self):
|
||
2 years ago
|
"""Return the boxes in xywh format normalized by original image size."""
|
||
2 years ago
|
xywh = ops.xyxy2xywh(self.xyxy)
|
||
|
xywh[..., [0, 2]] /= self.orig_shape[1]
|
||
|
xywh[..., [1, 3]] /= self.orig_shape[0]
|
||
|
return xywh
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
2 years ago
|
def boxes(self):
|
||
2 years ago
|
"""Return the raw bboxes tensor (deprecated)."""
|
||
2 years ago
|
LOGGER.warning("WARNING ⚠️ 'Boxes.boxes' is deprecated. Use 'Boxes.data' instead.")
|
||
|
return self.data
|
||
2 years ago
|
|
||
2 years ago
|
|
||
2 years ago
|
class Masks(BaseTensor):
|
||
2 years ago
|
"""
|
||
|
A class for storing and manipulating detection masks.
|
||
|
|
||
|
Args:
|
||
2 years ago
|
masks (torch.Tensor | np.ndarray): A tensor containing the detection masks, with shape (num_masks, height, width).
|
||
2 years ago
|
orig_shape (tuple): Original image size, in the format (height, width).
|
||
|
|
||
|
Attributes:
|
||
2 years ago
|
masks (torch.Tensor | np.ndarray): A tensor containing the detection masks, with shape (num_masks, height, width).
|
||
2 years ago
|
orig_shape (tuple): Original image size, in the format (height, width).
|
||
|
|
||
|
Properties:
|
||
2 years ago
|
xy (list): A list of segments (pixels) which includes x, y segments of each detection.
|
||
|
xyn (list): A list of segments (normalized) which includes x, y segments of each detection.
|
||
2 years ago
|
|
||
|
Methods:
|
||
|
cpu(): Returns a copy of the masks tensor on CPU memory.
|
||
|
numpy(): Returns a copy of the masks tensor as a numpy array.
|
||
|
cuda(): Returns a copy of the masks tensor on GPU memory.
|
||
|
to(): Returns a copy of the masks tensor with the specified device and dtype.
|
||
2 years ago
|
"""
|
||
|
|
||
|
def __init__(self, masks, orig_shape) -> None:
|
||
2 years ago
|
"""Initialize the Masks class."""
|
||
2 years ago
|
if masks.ndim == 2:
|
||
|
masks = masks[None, :]
|
||
2 years ago
|
super().__init__(masks, orig_shape)
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
2 years ago
|
def segments(self):
|
||
2 years ago
|
"""Return segments (deprecated; normalized)."""
|
||
2 years ago
|
LOGGER.warning("WARNING ⚠️ 'Masks.segments' is deprecated. Use 'Masks.xyn' for segments (normalized) and "
|
||
|
"'Masks.xy' for segments (pixels) instead.")
|
||
|
return self.xyn
|
||
|
|
||
2 years ago
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
2 years ago
|
def xyn(self):
|
||
2 years ago
|
"""Return segments (normalized)."""
|
||
2 years ago
|
return [
|
||
2 years ago
|
ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True)
|
||
|
for x in ops.masks2segments(self.data)]
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def xy(self):
|
||
2 years ago
|
"""Return segments (pixels)."""
|
||
2 years ago
|
return [
|
||
2 years ago
|
ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False)
|
||
|
for x in ops.masks2segments(self.data)]
|
||
2 years ago
|
|
||
2 years ago
|
@property
|
||
2 years ago
|
def masks(self):
|
||
2 years ago
|
"""Return the raw masks tensor (deprecated)."""
|
||
2 years ago
|
LOGGER.warning("WARNING ⚠️ 'Masks.masks' is deprecated. Use 'Masks.data' instead.")
|
||
|
return self.data
|
||
2 years ago
|
|
||
|
def pandas(self):
|
||
|
"""Convert the object to a pandas DataFrame (not yet implemented)."""
|
||
|
LOGGER.warning("WARNING ⚠️ 'Masks.pandas' method is not yet implemented.")
|
||
2 years ago
|
|
||
|
|
||
|
class Keypoints(BaseTensor):
|
||
|
"""
|
||
|
A class for storing and manipulating detection keypoints.
|
||
|
|
||
|
Args:
|
||
|
keypoints (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_dets, num_kpts, 2/3).
|
||
|
orig_shape (tuple): Original image size, in the format (height, width).
|
||
|
|
||
|
Attributes:
|
||
|
keypoints (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_dets, num_kpts, 2/3).
|
||
|
orig_shape (tuple): Original image size, in the format (height, width).
|
||
|
|
||
|
Properties:
|
||
|
xy (list): A list of keypoints (pixels) which includes x, y keypoints of each detection.
|
||
|
xyn (list): A list of keypoints (normalized) which includes x, y keypoints of each detection.
|
||
|
|
||
|
Methods:
|
||
|
cpu(): Returns a copy of the keypoints tensor on CPU memory.
|
||
|
numpy(): Returns a copy of the keypoints tensor as a numpy array.
|
||
|
cuda(): Returns a copy of the keypoints tensor on GPU memory.
|
||
|
to(): Returns a copy of the keypoints tensor with the specified device and dtype.
|
||
|
"""
|
||
|
|
||
|
def __init__(self, keypoints, orig_shape) -> None:
|
||
|
if keypoints.ndim == 2:
|
||
|
keypoints = keypoints[None, :]
|
||
|
super().__init__(keypoints, orig_shape)
|
||
|
self.has_visible = self.data.shape[-1] == 3
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def xy(self):
|
||
|
return self.data[..., :2]
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def xyn(self):
|
||
|
xy = self.xy.clone() if isinstance(self.xy, torch.Tensor) else np.copy(self.xy)
|
||
|
xy[..., 0] /= self.orig_shape[1]
|
||
|
xy[..., 1] /= self.orig_shape[0]
|
||
|
return xy
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def conf(self):
|
||
2 years ago
|
return self.data[..., 2] if self.has_visible else None
|
||
2 years ago
|
|
||
|
|
||
|
class Probs(BaseTensor):
|
||
|
"""
|
||
|
A class for storing and manipulating classify predictions.
|
||
|
|
||
|
Args:
|
||
|
probs (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_class, ).
|
||
|
|
||
|
Attributes:
|
||
|
probs (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_class).
|
||
|
|
||
|
Properties:
|
||
|
top5 (list[int]): Top 1 indice.
|
||
|
top1 (int): Top 5 indices.
|
||
|
|
||
|
Methods:
|
||
|
cpu(): Returns a copy of the probs tensor on CPU memory.
|
||
|
numpy(): Returns a copy of the probs tensor as a numpy array.
|
||
|
cuda(): Returns a copy of the probs tensor on GPU memory.
|
||
|
to(): Returns a copy of the probs tensor with the specified device and dtype.
|
||
|
"""
|
||
|
|
||
|
def __init__(self, probs, orig_shape=None) -> None:
|
||
|
super().__init__(probs, orig_shape)
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def top5(self):
|
||
|
"""Return the indices of top 5."""
|
||
|
return (-self.data).argsort(0)[:5].tolist() # this way works with both torch and numpy.
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def top1(self):
|
||
|
"""Return the indices of top 1."""
|
||
|
return int(self.data.argmax())
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def top5conf(self):
|
||
|
"""Return the confidences of top 5."""
|
||
|
return self.data[self.top5]
|
||
|
|
||
|
@property
|
||
|
@lru_cache(maxsize=1)
|
||
|
def top1conf(self):
|
||
|
"""Return the confidences of top 1."""
|
||
|
return self.data[self.top1]
|