| |
| """ |
| General utils |
| """ |
|
|
| import glob |
| import logging |
| import math |
| import os |
| import platform |
| import random |
| import re |
| import shutil |
| import time |
| import urllib |
| from pathlib import Path |
|
|
| import cv2 |
| import numpy as np |
| import pandas as pd |
| import torch |
| import torchvision |
|
|
| from .metrics import box_iou |
|
|
| |
| FILE = Path(__file__).resolve() |
| ROOT = FILE.parents[1] |
| NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) |
| VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' |
|
|
| torch.set_printoptions(linewidth=320, precision=5, profile='long') |
| np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) |
| pd.options.display.max_columns = 10 |
| cv2.setNumThreads(0) |
| os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) |
|
|
|
|
| def set_logging(name=None, verbose=VERBOSE): |
| |
| rank = int(os.getenv('RANK', -1)) |
| logging.basicConfig(format="%(message)s", level=logging.INFO if (verbose and rank in (-1, 0)) else logging.WARNING) |
| return logging.getLogger(name) |
|
|
|
|
| LOGGER = set_logging('yolov5') |
|
|
| def try_except(func): |
| |
| def handler(*args, **kwargs): |
| try: |
| func(*args, **kwargs) |
| except Exception as e: |
| print(e) |
|
|
| return handler |
|
|
|
|
| def methods(instance): |
| |
| return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")] |
|
|
|
|
| def print_args(name, opt): |
| |
| LOGGER.info(colorstr(f'{name}: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) |
|
|
|
|
| def init_seeds(seed=0): |
| |
| |
| import torch.backends.cudnn as cudnn |
| random.seed(seed) |
| np.random.seed(seed) |
| torch.manual_seed(seed) |
| cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False) |
|
|
|
|
| def intersect_dicts(da, db, exclude=()): |
| |
| return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} |
|
|
|
|
| def get_latest_run(search_dir='.'): |
| |
| last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True) |
| return max(last_list, key=os.path.getctime) if last_list else '' |
|
|
|
|
| def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'): |
| |
| env = os.getenv(env_var) |
| if env: |
| path = Path(env) |
| else: |
| cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} |
| path = Path.home() / cfg.get(platform.system(), '') |
| path = (path if is_writeable(path) else Path('/tmp')) / dir |
| path.mkdir(exist_ok=True) |
| return path |
|
|
|
|
| def is_writeable(dir, test=False): |
| |
| if test: |
| file = Path(dir) / 'tmp.txt' |
| try: |
| with open(file, 'w'): |
| pass |
| file.unlink() |
| return True |
| except OSError: |
| return False |
| else: |
| return os.access(dir, os.R_OK) |
|
|
|
|
| def is_ascii(s=''): |
| |
| s = str(s) |
| return len(s.encode().decode('ascii', 'ignore')) == len(s) |
|
|
|
|
| def is_chinese(s='人工智能'): |
| |
| return re.search('[\u4e00-\u9fff]', s) |
|
|
|
|
| def emojis(str=''): |
| |
| return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str |
|
|
|
|
| def file_size(path): |
| |
| path = Path(path) |
| if path.is_file(): |
| return path.stat().st_size / 1E6 |
| elif path.is_dir(): |
| return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / 1E6 |
| else: |
| return 0.0 |
|
|
|
|
| def check_python(minimum='3.6.2'): |
| |
| check_version(platform.python_version(), minimum, name='Python ', hard=True) |
|
|
|
|
| def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False): |
| |
| return True |
|
|
|
|
| def check_img_size(imgsz, s=32, floor=0): |
| |
| if isinstance(imgsz, int): |
| new_size = max(make_divisible(imgsz, int(s)), floor) |
| else: |
| new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz] |
| if new_size != imgsz: |
| LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}') |
| return new_size |
|
|
|
|
| def url2file(url): |
| |
| url = str(Path(url)).replace(':/', '://') |
| file = Path(urllib.parse.unquote(url)).name.split('?')[0] |
| return file |
|
|
|
|
| def make_divisible(x, divisor): |
| |
| if isinstance(divisor, torch.Tensor): |
| divisor = int(divisor.max()) |
| return math.ceil(x / divisor) * divisor |
|
|
|
|
| def clean_str(s): |
| |
| return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) |
|
|
|
|
| def one_cycle(y1=0.0, y2=1.0, steps=100): |
| |
| return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 |
|
|
|
|
| def colorstr(*input): |
| |
| *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) |
| colors = {'black': '\033[30m', |
| 'red': '\033[31m', |
| 'green': '\033[32m', |
| 'yellow': '\033[33m', |
| 'blue': '\033[34m', |
| 'magenta': '\033[35m', |
| 'cyan': '\033[36m', |
| 'white': '\033[37m', |
| 'bright_black': '\033[90m', |
| 'bright_red': '\033[91m', |
| 'bright_green': '\033[92m', |
| 'bright_yellow': '\033[93m', |
| 'bright_blue': '\033[94m', |
| 'bright_magenta': '\033[95m', |
| 'bright_cyan': '\033[96m', |
| 'bright_white': '\033[97m', |
| 'end': '\033[0m', |
| 'bold': '\033[1m', |
| 'underline': '\033[4m'} |
| return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] |
|
|
|
|
| def labels_to_class_weights(labels, nc=80): |
| |
| if labels[0] is None: |
| return torch.Tensor() |
|
|
| labels = np.concatenate(labels, 0) |
| classes = labels[:, 0].astype(np.int) |
| weights = np.bincount(classes, minlength=nc) |
|
|
| |
| |
| |
|
|
| weights[weights == 0] = 1 |
| weights = 1 / weights |
| weights /= weights.sum() |
| return torch.from_numpy(weights) |
|
|
|
|
| def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): |
| |
| class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) |
| image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) |
| |
| return image_weights |
|
|
|
|
| def xyxy2xywh(x): |
| |
| y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) |
| y[:, 0] = (x[:, 0] + x[:, 2]) / 2 |
| y[:, 1] = (x[:, 1] + x[:, 3]) / 2 |
| y[:, 2] = x[:, 2] - x[:, 0] |
| y[:, 3] = x[:, 3] - x[:, 1] |
| return y |
|
|
|
|
| def xywh2xyxy(x): |
| |
| y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) |
| y[:, 0] = x[:, 0] - x[:, 2] / 2 |
| y[:, 1] = x[:, 1] - x[:, 3] / 2 |
| y[:, 2] = x[:, 0] + x[:, 2] / 2 |
| y[:, 3] = x[:, 1] + x[:, 3] / 2 |
| return y |
|
|
|
|
| def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): |
| |
| y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) |
| y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw |
| y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh |
| y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw |
| y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh |
| return y |
|
|
|
|
| def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0): |
| |
| if clip: |
| clip_coords(x, (h - eps, w - eps)) |
| y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) |
| y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w |
| y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h |
| y[:, 2] = (x[:, 2] - x[:, 0]) / w |
| y[:, 3] = (x[:, 3] - x[:, 1]) / h |
| return y |
|
|
|
|
| def xyn2xy(x, w=640, h=640, padw=0, padh=0): |
| |
| y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) |
| y[:, 0] = w * x[:, 0] + padw |
| y[:, 1] = h * x[:, 1] + padh |
| return y |
|
|
|
|
| def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): |
| |
| if ratio_pad is None: |
| gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) |
| pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 |
| else: |
| gain = ratio_pad[0][0] |
| pad = ratio_pad[1] |
|
|
| coords[:, [0, 2]] -= pad[0] |
| coords[:, [1, 3]] -= pad[1] |
| coords[:, :4] /= gain |
| clip_coords(coords, img0_shape) |
| return coords |
|
|
|
|
| def clip_coords(boxes, shape): |
| |
| if isinstance(boxes, torch.Tensor): |
| boxes[:, 0].clamp_(0, shape[1]) |
| boxes[:, 1].clamp_(0, shape[0]) |
| boxes[:, 2].clamp_(0, shape[1]) |
| boxes[:, 3].clamp_(0, shape[0]) |
| else: |
| boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) |
| boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) |
|
|
|
|
| def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, |
| labels=(), max_det=300): |
| """Runs Non-Maximum Suppression (NMS) on inference results |
| |
| Returns: |
| list of detections, on (n,6) tensor per image [xyxy, conf, cls] |
| """ |
|
|
| nc = prediction.shape[2] - 5 |
| xc = prediction[..., 4] > conf_thres |
|
|
| |
| assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' |
| assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' |
|
|
| |
| min_wh, max_wh = 2, 7680 |
| max_nms = 40000 |
| time_limit = 10.0 |
| redundant = True |
| multi_label = False |
| merge = False |
|
|
| t = time.time() |
| output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] |
| for xi, x in enumerate(prediction): |
| |
| |
| x = x[xc[xi]] |
|
|
| |
| if labels and len(labels[xi]): |
| l = labels[xi] |
| v = torch.zeros((len(l), nc + 5), device=x.device) |
| v[:, :4] = l[:, 1:5] |
| v[:, 4] = 1.0 |
| v[range(len(l)), l[:, 0].long() + 5] = 1.0 |
| x = torch.cat((x, v), 0) |
|
|
| |
| if not x.shape[0]: |
| continue |
|
|
| |
| x[:, 5:] *= x[:, 4:5] |
|
|
| |
| box = xywh2xyxy(x[:, :4]) |
|
|
| |
| if multi_label: |
| i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T |
| x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) |
| else: |
| conf, j = x[:, 5:].max(1, keepdim=True) |
| x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] |
|
|
| |
| if classes is not None: |
| x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] |
|
|
| |
| |
| |
|
|
| |
| n = x.shape[0] |
| if not n: |
| continue |
| elif n > max_nms: |
| x = x[x[:, 4].argsort(descending=True)[:max_nms]] |
|
|
| |
| c = x[:, 5:6] * (0 if agnostic else max_wh) |
| boxes, scores = x[:, :4] + c, x[:, 4] |
| i = torchvision.ops.nms(boxes, scores, iou_thres) |
| if i.shape[0] > max_det: |
| i = i[:max_det] |
| if merge and (1 < n < 3E3): |
| |
| iou = box_iou(boxes[i], boxes) > iou_thres |
| weights = iou * scores[None] |
| x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) |
| if redundant: |
| i = i[iou.sum(1) > 1] |
|
|
| output[xi] = x[i] |
| if (time.time() - t) > time_limit: |
| LOGGER.warning(f'WARNING: NMS time limit {time_limit}s exceeded') |
| break |
|
|
| return output |
|
|
|
|
| def increment_path(path, exist_ok=False, sep='', mkdir=False): |
| |
| path = Path(path) |
| if path.exists() and not exist_ok: |
| path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '') |
| dirs = glob.glob(f"{path}{sep}*") |
| matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] |
| i = [int(m.groups()[0]) for m in matches if m] |
| n = max(i) + 1 if i else 2 |
| path = Path(f"{path}{sep}{n}{suffix}") |
| if mkdir: |
| path.mkdir(parents=True, exist_ok=True) |
| return path |
|
|
|
|
| |
| NCOLS = shutil.get_terminal_size().columns |
|
|