Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/utils/general.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2General utils3"""45import contextlib6import glob7import logging8import math9import os10import platform11import random12import re13import shutil14import signal15import time16import urllib17from itertools import repeat18from multiprocessing.pool import ThreadPool19from pathlib import Path20from subprocess import check_output21from zipfile import ZipFile2223import cv224import numpy as np25import pandas as pd26import pkg_resources as pkg27import torch28import torchvision29import yaml3031from utils.downloads import gsutil_getsize32from utils.metrics import box_iou, fitness33pi = 3.14159234from utils.nms_rotated import obb_nms3536# Settings37FILE = Path(__file__).resolve()38ROOT = FILE.parents[1] # YOLOv5 root directory39NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads4041torch.set_printoptions(linewidth=320, precision=5, profile='long')42np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=543pd.options.display.max_columns = 1044cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)45os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads464748def set_logging(name=None, verbose=True):49# Sets level and returns logger50for h in logging.root.handlers:51logging.root.removeHandler(h) # remove all handlers associated with the root logger object52rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings53logging.basicConfig(format="%(message)s", level=logging.INFO if (verbose and rank in (-1, 0)) else logging.WARNING)54return logging.getLogger(name)555657LOGGER = set_logging(__name__) # define globally (used in train.py, val.py, detect.py, etc.)585960class Profile(contextlib.ContextDecorator):61# Usage: @Profile() decorator or 'with Profile():' context manager62def __enter__(self):63self.start = time.time()6465def __exit__(self, type, value, traceback):66print(f'Profile results: {time.time() - self.start:.5f}s')676869class Timeout(contextlib.ContextDecorator):70# Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager71def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):72self.seconds = int(seconds)73self.timeout_message = timeout_msg74self.suppress = bool(suppress_timeout_errors)7576def _timeout_handler(self, signum, frame):77raise TimeoutError(self.timeout_message)7879def __enter__(self):80signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM81signal.alarm(self.seconds) # start countdown for SIGALRM to be raised8283def __exit__(self, exc_type, exc_val, exc_tb):84signal.alarm(0) # Cancel SIGALRM if it's scheduled85if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError86return True878889class WorkingDirectory(contextlib.ContextDecorator):90# Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager91def __init__(self, new_dir):92self.dir = new_dir # new dir93self.cwd = Path.cwd().resolve() # current dir9495def __enter__(self):96os.chdir(self.dir)9798def __exit__(self, exc_type, exc_val, exc_tb):99os.chdir(self.cwd)100101102def try_except(func):103# try-except function. Usage: @try_except decorator104def handler(*args, **kwargs):105try:106func(*args, **kwargs)107except Exception as e:108print(e)109110return handler111112113def methods(instance):114# Get class/instance methods115return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]116117118def print_args(name, opt):119# Print argparser arguments120LOGGER.info(colorstr(f'{name}: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))121122123def init_seeds(seed=0):124# Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html125# cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible126import torch.backends.cudnn as cudnn127random.seed(seed)128np.random.seed(seed)129torch.manual_seed(seed)130cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False)131132133def intersect_dicts(da, db, exclude=()):134# Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values135return {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}136137138def get_latest_run(search_dir='.'):139# Return path to most recent 'last.pt' in /runs (i.e. to --resume from)140last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)141return max(last_list, key=os.path.getctime) if last_list else ''142143144def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):145# Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.146env = os.getenv(env_var)147if env:148path = Path(env) # use environment variable149else:150cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs151path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir152path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable153path.mkdir(exist_ok=True) # make if required154return path155156157def is_writeable(dir, test=False):158# Return True if directory has write permissions, test opening a file with write permissions if test=True159if test: # method 1160file = Path(dir) / 'tmp.txt'161try:162with open(file, 'w'): # open file with write permissions163pass164file.unlink() # remove file165return True166except OSError:167return False168else: # method 2169return os.access(dir, os.R_OK) # possible issues on Windows170171172def is_docker():173# Is environment a Docker container?174return Path('/workspace').exists() # or Path('/.dockerenv').exists()175176177def is_colab():178# Is environment a Google Colab instance?179try:180import google.colab181return True182except ImportError:183return False184185186def is_pip():187# Is file in a pip package?188return 'site-packages' in Path(__file__).resolve().parts189190191def is_ascii(s=''):192# Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)193s = str(s) # convert list, tuple, None, etc. to str194return len(s.encode().decode('ascii', 'ignore')) == len(s)195196197def is_chinese(s='人工智能'):198# Is string composed of any Chinese characters?199return re.search('[\u4e00-\u9fff]', s)200201202def emojis(str=''):203# Return platform-dependent emoji-safe version of string204return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str205206207def file_size(path):208# Return file/dir size (MB)209path = Path(path)210if path.is_file():211return path.stat().st_size / 1E6212elif path.is_dir():213return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / 1E6214else:215return 0.0216217218def check_online():219# Check internet connectivity220import socket221try:222socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility223return True224except OSError:225return False226227228@try_except229@WorkingDirectory(ROOT)230def check_git_status():231# Recommend 'git pull' if code is out of date232msg = ', for updates see https://github.com/ultralytics/yolov5'233print(colorstr('github: '), end='')234assert Path('.git').exists(), 'skipping check (not a git repository)' + msg235assert not is_docker(), 'skipping check (Docker image)' + msg236assert check_online(), 'skipping check (offline)' + msg237238cmd = 'git fetch && git config --get remote.origin.url'239url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git') # git fetch240branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out241n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind242if n > 0:243s = f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update."244else:245s = f'up to date with {url} ✅'246print(emojis(s)) # emoji-safe247248249def check_python(minimum='3.6.2'):250# Check current python version vs. required python version251check_version(platform.python_version(), minimum, name='Python ', hard=True)252253254def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):255# Check version vs. required version256current, minimum = (pkg.parse_version(x) for x in (current, minimum))257result = (current == minimum) if pinned else (current >= minimum) # bool258s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string259if hard:260assert result, s # assert min requirements met261if verbose and not result:262LOGGER.warning(s)263return result264265266@try_except267def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True):268# Check installed dependencies meet requirements (pass *.txt file or list of packages)269prefix = colorstr('red', 'bold', 'requirements:')270check_python() # check python version271if isinstance(requirements, (str, Path)): # requirements.txt file272file = Path(requirements)273assert file.exists(), f"{prefix} {file.resolve()} not found, check failed."274with file.open() as f:275requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]276else: # list or tuple of packages277requirements = [x for x in requirements if x not in exclude]278279n = 0 # number of packages updates280for r in requirements:281try:282pkg.require(r)283except Exception as e: # DistributionNotFound or VersionConflict if requirements not met284s = f"{prefix} {r} not found and is required by YOLOv5"285if install:286print(f"{s}, attempting auto-update...")287try:288assert check_online(), f"'pip install {r}' skipped (offline)"289print(check_output(f"pip install '{r}'", shell=True).decode())290n += 1291except Exception as e:292print(f'{prefix} {e}')293else:294print(f'{s}. Please install and rerun your command.')295296if n: # if packages updated297source = file.resolve() if 'file' in locals() else requirements298s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \299f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"300print(emojis(s))301302303def check_img_size(imgsz, s=32, floor=0):304# Verify image size is a multiple of stride s in each dimension305if isinstance(imgsz, int): # integer i.e. img_size=640306new_size = max(make_divisible(imgsz, int(s)), floor)307else: # list i.e. img_size=[640, 480]308new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]309if new_size != imgsz:310print(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')311return new_size312313314def check_imshow():315# Check if environment supports image displays316try:317assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'318assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'319cv2.imshow('test', np.zeros((1, 1, 3)))320cv2.waitKey(1)321cv2.destroyAllWindows()322cv2.waitKey(1)323return True324except Exception as e:325print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')326return False327328329def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):330# Check file(s) for acceptable suffix331if file and suffix:332if isinstance(suffix, str):333suffix = [suffix]334for f in file if isinstance(file, (list, tuple)) else [file]:335s = Path(f).suffix.lower() # file suffix336if len(s):337assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}"338339340def check_yaml(file, suffix=('.yaml', '.yml')):341# Search/download YAML file (if necessary) and return path, checking suffix342return check_file(file, suffix)343344345def check_file(file, suffix=''):346# Search/download file (if necessary) and return path347check_suffix(file, suffix) # optional348file = str(file) # convert to str()349if Path(file).is_file() or file == '': # exists350return file351elif file.startswith(('http:/', 'https:/')): # download352url = str(Path(file)).replace(':/', '://') # Pathlib turns :// -> :/353file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth354if Path(file).is_file():355print(f'Found {url} locally at {file}') # file already exists356else:357print(f'Downloading {url} to {file}...')358torch.hub.download_url_to_file(url, file)359assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check360return file361else: # search362files = []363for d in 'data', 'models', 'utils': # search directories364files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file365assert len(files), f'File not found: {file}' # assert file was found366assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique367return files[0] # return file368369370def check_dataset(data, autodownload=True):371# Download and/or unzip dataset if not found locally372# Usage: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128_with_yaml.zip373374# Download (optional)375extract_dir = ''376if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip377download(data, dir='../datasets', unzip=True, delete=False, curl=False, threads=1)378data = next((Path('../datasets') / Path(data).stem).rglob('*.yaml'))379extract_dir, autodownload = data.parent, False380381# Read yaml (optional)382if isinstance(data, (str, Path)):383with open(data, errors='ignore') as f:384data = yaml.safe_load(f) # dictionary385386# Parse yaml387path = extract_dir or Path(data.get('path') or '') # optional 'path' default to '.'388for k in 'train', 'val', 'test':389if data.get(k): # prepend path390data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]]391392assert 'nc' in data, "Dataset 'nc' key missing."393if 'names' not in data:394data['names'] = [f'class{i}' for i in range(data['nc'])] # assign class names if missing395train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))396if val:397val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path398if not all(x.exists() for x in val):399print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])400if s and autodownload: # download script401root = path.parent if 'path' in data else '..' # unzip directory i.e. '../'402if s.startswith('http') and s.endswith('.zip'): # URL403f = Path(s).name # filename404print(f'Downloading {s} to {f}...')405torch.hub.download_url_to_file(s, f)406Path(root).mkdir(parents=True, exist_ok=True) # create root407ZipFile(f).extractall(path=root) # unzip408Path(f).unlink() # remove zip409r = None # success410elif s.startswith('bash '): # bash script411print(f'Running {s} ...')412r = os.system(s)413else: # python script414r = exec(s, {'yaml': data}) # return None415print(f"Dataset autodownload {f'success, saved to {root}' if r in (0, None) else 'failure'}\n")416else:417raise Exception('Dataset not found.')418419return data # dictionary420421422def url2file(url):423# Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt424url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/425file = Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth426return file427428429def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1):430# Multi-threaded file download and unzip function, used in data.yaml for autodownload431def download_one(url, dir):432# Download 1 file433f = dir / Path(url).name # filename434if Path(url).is_file(): # exists in current path435Path(url).rename(f) # move to dir436elif not f.exists():437print(f'Downloading {url} to {f}...')438if curl:439os.system(f"curl -L '{url}' -o '{f}' --retry 9 -C -") # curl download, retry and resume on fail440else:441torch.hub.download_url_to_file(url, f, progress=True) # torch download442if unzip and f.suffix in ('.zip', '.gz'):443print(f'Unzipping {f}...')444if f.suffix == '.zip':445ZipFile(f).extractall(path=dir) # unzip446elif f.suffix == '.gz':447os.system(f'tar xfz {f} --directory {f.parent}') # unzip448if delete:449f.unlink() # remove zip450451dir = Path(dir)452dir.mkdir(parents=True, exist_ok=True) # make directory453if threads > 1:454pool = ThreadPool(threads)455pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded456pool.close()457pool.join()458else:459for u in [url] if isinstance(url, (str, Path)) else url:460download_one(u, dir)461462463def make_divisible(x, divisor):464# Returns nearest x divisible by divisor465if isinstance(divisor, torch.Tensor):466divisor = int(divisor.max()) # to int467return math.ceil(x / divisor) * divisor468469470def clean_str(s):471# Cleans a string by replacing special characters with underscore _472return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)473474475def one_cycle(y1=0.0, y2=1.0, steps=100):476# lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf477return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1478479480def colorstr(*input):481# Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')482*args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string483colors = {'black': '\033[30m', # basic colors484'red': '\033[31m',485'green': '\033[32m',486'yellow': '\033[33m',487'blue': '\033[34m',488'magenta': '\033[35m',489'cyan': '\033[36m',490'white': '\033[37m',491'bright_black': '\033[90m', # bright colors492'bright_red': '\033[91m',493'bright_green': '\033[92m',494'bright_yellow': '\033[93m',495'bright_blue': '\033[94m',496'bright_magenta': '\033[95m',497'bright_cyan': '\033[96m',498'bright_white': '\033[97m',499'end': '\033[0m', # misc500'bold': '\033[1m',501'underline': '\033[4m'}502return ''.join(colors[x] for x in args) + f'{string}' + colors['end']503504505def labels_to_class_weights(labels, nc=80):506# Get class weights (inverse frequency) from training labels507if labels[0] is None: # no labels loaded508return torch.Tensor()509510labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO511classes = labels[:, 0].astype(np.int) # labels = [class xywh]512weights = np.bincount(classes, minlength=nc) # occurrences per class513514# Prepend gridpoint count (for uCE training)515# gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image516# weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start517518weights[weights == 0] = 1 # replace empty bins with 1519weights = 1 / weights # number of targets per class520weights /= weights.sum() # normalize521return torch.from_numpy(weights)522523524def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):525# Produces image weights based on class_weights and image contents526class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])527image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)528# index = random.choices(range(n), weights=image_weights, k=1) # weight image sample529return image_weights530531532def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)533# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/534# a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')535# b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')536# x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco537# x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet538x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,53935, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,54064, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]541return x542543544def xyxy2xywh(x):545# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right546y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)547y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center548y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center549y[:, 2] = x[:, 2] - x[:, 0] # width550y[:, 3] = x[:, 3] - x[:, 1] # height551return y552553554def xywh2xyxy(x):555# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right556y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)557y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x558y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y559y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x560y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y561return y562563564def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):565# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right566y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)567y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x568y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y569y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x570y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y571return y572573574def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):575# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right576if clip:577clip_coords(x, (h - eps, w - eps)) # warning: inplace clip578y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)579y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center580y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center581y[:, 2] = (x[:, 2] - x[:, 0]) / w # width582y[:, 3] = (x[:, 3] - x[:, 1]) / h # height583return y584585586def xyn2xy(x, w=640, h=640, padw=0, padh=0):587# Convert normalized segments into pixel segments, shape (n,2)588y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)589y[:, 0] = w * x[:, 0] + padw # top left x590y[:, 1] = h * x[:, 1] + padh # top left y591return y592593594def segment2box(segment, width=640, height=640):595# Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)596x, y = segment.T # segment xy597inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)598x, y, = x[inside], y[inside]599return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy600601602def segments2boxes(segments):603# Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)604boxes = []605for s in segments:606x, y = s.T # segment xy607boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy608return xyxy2xywh(np.array(boxes)) # cls, xywh609610611def resample_segments(segments, n=1000):612# Up-sample an (n,2) segment613for i, s in enumerate(segments):614x = np.linspace(0, len(s) - 1, n)615xp = np.arange(len(s))616segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy617return segments618619620def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):621# Rescale coords (xyxy) from img1_shape to img0_shape622if ratio_pad is None: # calculate from img0_shape623gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new624pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding625else:626gain = ratio_pad[0][0]627pad = ratio_pad[1]628629coords[:, [0, 2]] -= pad[0] # x padding630coords[:, [1, 3]] -= pad[1] # y padding631coords[:, :4] /= gain632clip_coords(coords, img0_shape)633return coords634635def scale_polys(img1_shape, polys, img0_shape, ratio_pad=None):636# ratio_pad: [(h_raw, w_raw), (hw_ratios, wh_paddings)]637# Rescale coords (xyxyxyxy) from img1_shape to img0_shape638if ratio_pad is None: # calculate from img0_shape639gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = resized / raw640pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding641else:642gain = ratio_pad[0][0] # h_ratios643pad = ratio_pad[1] # wh_paddings644645polys[:, [0, 2, 4, 6]] -= pad[0] # x padding646polys[:, [1, 3, 5, 7]] -= pad[1] # y padding647polys[:, :8] /= gain # Rescale poly shape to img0_shape648#clip_polys(polys, img0_shape)649return polys650651def clip_polys(polys, shape):652# Clip bounding xyxyxyxy bounding boxes to image shape (height, width)653if isinstance(polys, torch.Tensor): # faster individually654polys[:, 0].clamp_(0, shape[1]) # x1655polys[:, 1].clamp_(0, shape[0]) # y1656polys[:, 2].clamp_(0, shape[1]) # x2657polys[:, 3].clamp_(0, shape[0]) # y2658polys[:, 4].clamp_(0, shape[1]) # x3659polys[:, 5].clamp_(0, shape[0]) # y3660polys[:, 6].clamp_(0, shape[1]) # x4661polys[:, 7].clamp_(0, shape[0]) # y4662else: # np.array (faster grouped)663polys[:, [0, 2, 4, 6]] = polys[:, [0, 2, 4, 6]].clip(0, shape[1]) # x1, x2, x3, x4664polys[:, [1, 3, 5, 7]] = polys[:, [1, 3, 5, 7]].clip(0, shape[0]) # y1, y2, y3, y4665666def clip_coords(boxes, shape):667# Clip bounding xyxy bounding boxes to image shape (height, width)668if isinstance(boxes, torch.Tensor): # faster individually669boxes[:, 0].clamp_(0, shape[1]) # x1670boxes[:, 1].clamp_(0, shape[0]) # y1671boxes[:, 2].clamp_(0, shape[1]) # x2672boxes[:, 3].clamp_(0, shape[0]) # y2673else: # np.array (faster grouped)674boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2675boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2676677678def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,679labels=(), max_det=300):680"""Runs Non-Maximum Suppression (NMS) on inference results681682Returns:683list of detections, on (n,6) tensor per image [xyxy, conf, cls]684"""685686nc = prediction.shape[2] - 5 # number of classes687xc = prediction[..., 4] > conf_thres # candidates688689# Checks690assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'691assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'692693# Settings694min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height695max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()696time_limit = 10.0 # seconds to quit after697redundant = True # require redundant detections698multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)699merge = False # use merge-NMS700701t = time.time()702output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]703for xi, x in enumerate(prediction): # image index, image inference704# Apply constraints705# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height706x = x[xc[xi]] # confidence707708# Cat apriori labels if autolabelling709if labels and len(labels[xi]):710l = labels[xi]711v = torch.zeros((len(l), nc + 5), device=x.device)712v[:, :4] = l[:, 1:5] # box713v[:, 4] = 1.0 # conf714v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls715x = torch.cat((x, v), 0)716717# If none remain process next image718if not x.shape[0]:719continue720721# Compute conf722x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf723724# Box (center x, center y, width, height) to (x1, y1, x2, y2)725box = xywh2xyxy(x[:, :4])726727# Detections matrix nx6 (xyxy, conf, cls)728if multi_label:729i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T730x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)731else: # best class only732conf, j = x[:, 5:].max(1, keepdim=True)733x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]734735# Filter by class736if classes is not None:737x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]738739# Apply finite constraint740# if not torch.isfinite(x).all():741# x = x[torch.isfinite(x).all(1)]742743# Check shape744n = x.shape[0] # number of boxes745if not n: # no boxes746continue747elif n > max_nms: # excess boxes748x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence749750# Batched NMS751c = x[:, 5:6] * (0 if agnostic else max_wh) # classes752boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores753i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS754if i.shape[0] > max_det: # limit detections755i = i[:max_det]756if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)757# update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)758iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix759weights = iou * scores[None] # box weights760x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes761if redundant:762i = i[iou.sum(1) > 1] # require redundancy763764output[xi] = x[i]765if (time.time() - t) > time_limit:766print(f'WARNING: NMS time limit {time_limit}s exceeded')767break # time limit exceeded768769return output770771def non_max_suppression_obb(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,772labels=(), max_det=1500):773"""Runs Non-Maximum Suppression (NMS) on inference results_obb774Args:775prediction (tensor): (b, n_all_anchors, [cx cy l s obj num_cls theta_cls])776agnostic (bool): True = NMS will be applied between elements of different categories777labels : () or778779Returns:780list of detections, len=batch_size, on (n,7) tensor per image [xylsθ, conf, cls] θ ∈ [-pi/2, pi/2)781"""782783nc = prediction.shape[2] - 5 - 180 # number of classes784xc = prediction[..., 4] > conf_thres # candidates785class_index = nc + 5786787# Checks788assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'789assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'790791# Settings792max_wh = 4096 # min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height793max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()794time_limit = 30.0 # seconds to quit after795# redundant = True # require redundant detections796multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)797798t = time.time()799output = [torch.zeros((0, 7), device=prediction.device)] * prediction.shape[0]800for xi, x in enumerate(prediction): # image index, image inference801# Apply constraints802# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height803x = x[xc[xi]] # confidence, (tensor): (n_conf_thres, [cx cy l s obj num_cls theta_cls])804805# Cat apriori labels if autolabelling806if labels and len(labels[xi]):807l = labels[xi]808v = torch.zeros((len(l), nc + 5), device=x.device)809v[:, :4] = l[:, 1:5] # box810v[:, 4] = 1.0 # conf811v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls812x = torch.cat((x, v), 0)813814# If none remain process next image815if not x.shape[0]:816continue817818# Compute conf819x[:, 5:class_index] *= x[:, 4:5] # conf = obj_conf * cls_conf820821_, theta_pred = torch.max(x[:, class_index:], 1, keepdim=True) # [n_conf_thres, 1] θ ∈ int[0, 179]822theta_pred = (theta_pred - 90) / 180 * pi # [n_conf_thres, 1] θ ∈ [-pi/2, pi/2)823824# Detections matrix nx7 (xyls, θ, conf, cls) θ ∈ [-pi/2, pi/2)825if multi_label:826i, j = (x[:, 5:class_index] > conf_thres).nonzero(as_tuple=False).T # ()827x = torch.cat((x[i, :4], theta_pred[i], x[i, j + 5, None], j[:, None].float()), 1)828else: # best class only829conf, j = x[:, 5:class_index].max(1, keepdim=True)830x = torch.cat((x[:, :4], theta_pred, conf, j.float()), 1)[conf.view(-1) > conf_thres]831832# Filter by class833if classes is not None:834x = x[(x[:, 6:7] == torch.tensor(classes, device=x.device)).any(1)]835836# Apply finite constraint837# if not torch.isfinite(x).all():838# x = x[torch.isfinite(x).all(1)]839840# Check shape841n = x.shape[0] # number of boxes842if not n: # no boxes843continue844elif n > max_nms: # excess boxes845x = x[x[:, 5].argsort(descending=True)[:max_nms]] # sort by confidence846847# Batched NMS848c = x[:, 6:7] * (0 if agnostic else max_wh) # classes849rboxes = x[:, :5].clone()850rboxes[:, :2] = rboxes[:, :2] + c # rboxes (offset by class)851scores = x[:, 5] # scores852_, i = obb_nms(rboxes, scores, iou_thres)853if i.shape[0] > max_det: # limit detections854i = i[:max_det]855856output[xi] = x[i]857if (time.time() - t) > time_limit:858print(f'WARNING: NMS time limit {time_limit}s exceeded')859break # time limit exceeded860861return output862863def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()864# Strip optimizer from 'f' to finalize training, optionally save as 's'865x = torch.load(f, map_location=torch.device('cpu'))866if x.get('ema'):867x['model'] = x['ema'] # replace model with ema868for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates': # keys869x[k] = None870x['epoch'] = -1871x['model'].half() # to FP16872for p in x['model'].parameters():873p.requires_grad = False874torch.save(x, s or f)875mb = os.path.getsize(s or f) / 1E6 # filesize876print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")877878879def print_mutation(results, hyp, save_dir, bucket):880evolve_csv, results_csv, evolve_yaml = save_dir / 'evolve.csv', save_dir / 'results.csv', save_dir / 'hyp_evolve.yaml'881keys = ('metrics/precision', 'metrics/recall', 'metrics/HBBmAP.5', 'metrics/HBBmAP.5:.95',882'val/box_loss', 'val/obj_loss', 'val/cls_loss', 'val/theta_loss') + tuple(hyp.keys()) # [results + hyps]883keys = tuple(x.strip() for x in keys)884vals = results + tuple(hyp.values())885n = len(keys)886887# Download (optional)888if bucket:889url = f'gs://{bucket}/evolve.csv'890if gsutil_getsize(url) > (os.path.getsize(evolve_csv) if os.path.exists(evolve_csv) else 0):891os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local892893# Log to evolve.csv894s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header895with open(evolve_csv, 'a') as f:896f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')897898# Print to screen899print(colorstr('evolve: ') + ', '.join(f'{x.strip():>20s}' for x in keys))900print(colorstr('evolve: ') + ', '.join(f'{x:20.5g}' for x in vals), end='\n\n\n')901902# Save yaml903with open(evolve_yaml, 'w') as f:904data = pd.read_csv(evolve_csv)905data = data.rename(columns=lambda x: x.strip()) # strip keys906i = np.argmax(fitness(data.values[:, :7])) #907f.write('# YOLOv5 Hyperparameter Evolution Results\n' +908f'# Best generation: {i}\n' +909f'# Last generation: {len(data) - 1}\n' +910'# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' +911'# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')912yaml.safe_dump(hyp, f, sort_keys=False)913914if bucket:915os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload916917918def apply_classifier(x, model, img, im0):919# Apply a second stage classifier to YOLO outputs920# Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()921im0 = [im0] if isinstance(im0, np.ndarray) else im0922for i, d in enumerate(x): # per image923if d is not None and len(d):924d = d.clone()925926# Reshape and pad cutouts927b = xyxy2xywh(d[:, :4]) # boxes928b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square929b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad930d[:, :4] = xywh2xyxy(b).long()931932# Rescale boxes from img_size to im0 size933scale_coords(img.shape[2:], d[:, :4], im0[i].shape)934935# Classes936pred_cls1 = d[:, 5].long()937ims = []938for j, a in enumerate(d): # per item939cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]940im = cv2.resize(cutout, (224, 224)) # BGR941# cv2.imwrite('example%i.jpg' % j, cutout)942943im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416944im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32945im /= 255 # 0 - 255 to 0.0 - 1.0946ims.append(im)947948pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction949x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections950951return x952953954def increment_path(path, exist_ok=False, sep='', mkdir=False):955# Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.956path = Path(path) # os-agnostic957if path.exists() and not exist_ok:958path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')959dirs = glob.glob(f"{path}{sep}*") # similar paths960matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]961i = [int(m.groups()[0]) for m in matches if m] # indices962n = max(i) + 1 if i else 2 # increment number963path = Path(f"{path}{sep}{n}{suffix}") # increment path964if mkdir:965path.mkdir(parents=True, exist_ok=True) # make directory966return path967968969# Variables970NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm971972973