ultralytics 8.0.75 fixes and updates (#1967)

Co-authored-by: Laughing-q <1185102784@qq.com>
Co-authored-by: Jonathan Rayner <jonathan.j.rayner@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Glenn Jocher
2023-04-13 02:04:10 +02:00
committed by GitHub
parent e5cb35edfc
commit 48c4483795
9 changed files with 128 additions and 98 deletions

View File

@ -17,6 +17,7 @@ from types import SimpleNamespace
from typing import Union
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import yaml
@ -116,7 +117,7 @@ class SimpleClass:
attr = []
for a in dir(self):
v = getattr(self, a)
if not callable(v) and not a.startswith('__'):
if not callable(v) and not a.startswith('_'):
if isinstance(v, SimpleClass):
# Display only the module and class name for subclasses
s = f'{a}: {v.__module__}.{v.__class__.__name__} object'
@ -164,6 +165,39 @@ class IterableSimpleNamespace(SimpleNamespace):
return getattr(self, key, default)
def plt_settings(rcparams={'font.size': 11}, backend='Agg'):
"""
Decorator to temporarily set rc parameters and the backend for a plotting function.
Usage:
decorator: @plt_settings({"font.size": 12})
context manager: with plt_settings({"font.size": 12}):
Args:
rcparams (dict): Dictionary of rc parameters to set.
backend (str, optional): Name of the backend to use. Defaults to 'Agg'.
Returns:
callable: Decorated function with temporarily set rc parameters and backend.
"""
def decorator(func):
def wrapper(*args, **kwargs):
original_backend = plt.get_backend()
plt.switch_backend(backend)
with plt.rc_context(rcparams):
result = func(*args, **kwargs)
plt.switch_backend(original_backend)
return result
return wrapper
return decorator
def set_logging(name=LOGGING_NAME, verbose=True):
# sets up logging for the given name
rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings

View File

@ -128,7 +128,8 @@ def check_latest_pypi_version(package_name='ultralytics'):
Returns:
str: The latest version of the package.
"""
response = requests.get(f'https://pypi.org/pypi/{package_name}/json')
requests.packages.urllib3.disable_warnings() # Disable the InsecureRequestWarning
response = requests.get(f'https://pypi.org/pypi/{package_name}/json', verify=False)
if response.status_code == 200:
return response.json()['info']['version']
return None

View File

@ -11,7 +11,7 @@ import numpy as np
import torch
import torch.nn as nn
from ultralytics.yolo.utils import LOGGER, SimpleClass, TryExcept
from ultralytics.yolo.utils import LOGGER, SimpleClass, TryExcept, plt_settings
OKS_SIGMA = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0
@ -234,6 +234,7 @@ class ConfusionMatrix:
return tp[:-1], fp[:-1] # remove background class
@TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')
@plt_settings()
def plot(self, normalize=True, save_dir='', names=()):
import seaborn as sn
@ -277,6 +278,7 @@ def smooth(y, f=0.05):
return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
@plt_settings()
def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
# Precision-recall curve
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
@ -299,6 +301,7 @@ def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
plt.close(fig)
@plt_settings()
def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
# Metric-confidence curve
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)

View File

@ -5,22 +5,18 @@ import math
from pathlib import Path
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from PIL import __version__ as pil_version
from ultralytics.yolo.utils import LOGGER, TryExcept, threaded
from ultralytics.yolo.utils import LOGGER, TryExcept, plt_settings, threaded
from .checks import check_font, check_version, is_ascii
from .files import increment_path
from .ops import clip_boxes, scale_image, xywh2xyxy, xyxy2xywh
matplotlib.rc('font', **{'size': 11})
matplotlib.use('Agg') # for writing to files only
class Colors:
# Ultralytics color palette https://ultralytics.com/
@ -212,6 +208,7 @@ class Annotator:
@TryExcept() # known issue https://github.com/ultralytics/yolov5/issues/5395
@plt_settings()
def plot_labels(boxes, cls, names=(), save_dir=Path('')):
import pandas as pd
import seaborn as sn
@ -228,7 +225,6 @@ def plot_labels(boxes, cls, names=(), save_dir=Path('')):
plt.close()
# matplotlib labels
matplotlib.use('svg') # faster
ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
y = ax[0].hist(cls, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
with contextlib.suppress(Exception): # color histogram bars by class
@ -244,9 +240,9 @@ def plot_labels(boxes, cls, names=(), save_dir=Path('')):
# rectangles
boxes[:, 0:2] = 0.5 # center
boxes = xywh2xyxy(boxes) * 2000
img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
for cls, box in zip(cls[:1000], boxes[:1000]):
boxes = xywh2xyxy(boxes) * 1000
img = Image.fromarray(np.ones((1000, 1000, 3), dtype=np.uint8) * 255)
for cls, box in zip(cls[:500], boxes[:500]):
ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
ax[1].imshow(img)
ax[1].axis('off')
@ -256,7 +252,6 @@ def plot_labels(boxes, cls, names=(), save_dir=Path('')):
ax[a].spines[s].set_visible(False)
plt.savefig(save_dir / 'labels.jpg', dpi=200)
matplotlib.use('Agg')
plt.close()
@ -400,6 +395,7 @@ def plot_images(images,
annotator.im.save(fname) # save
@plt_settings()
def plot_results(file='path/to/results.csv', dir='', segment=False, pose=False):
# Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
import pandas as pd