2020-11-14 18:50:32 +08:00
|
|
|
# Plotting utils
|
|
|
|
|
|
|
|
import glob
|
|
|
|
import os
|
|
|
|
from copy import copy
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import cv2
|
2021-07-07 21:41:58 +08:00
|
|
|
import math
|
2020-11-14 18:50:32 +08:00
|
|
|
import matplotlib
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
import numpy as np
|
2020-12-19 10:05:38 +08:00
|
|
|
import pandas as pd
|
2021-06-10 19:51:29 +08:00
|
|
|
import seaborn as sn
|
2020-11-14 18:50:32 +08:00
|
|
|
import torch
|
|
|
|
import yaml
|
2021-02-20 07:20:41 +08:00
|
|
|
from PIL import Image, ImageDraw, ImageFont
|
2020-11-14 18:50:32 +08:00
|
|
|
|
2021-07-09 21:23:02 +08:00
|
|
|
from utils.general import xywh2xyxy, xyxy2xywh
|
2020-11-14 18:50:32 +08:00
|
|
|
from utils.metrics import fitness
|
|
|
|
|
2020-11-16 23:34:07 +08:00
|
|
|
# Settings
|
2020-11-28 19:25:45 +08:00
|
|
|
matplotlib.rc('font', **{'size': 11})
|
2020-12-02 22:53:16 +08:00
|
|
|
matplotlib.use('Agg') # for writing to files only
|
2020-11-16 23:34:07 +08:00
|
|
|
|
2020-11-14 18:50:32 +08:00
|
|
|
|
2021-04-28 22:05:14 +08:00
|
|
|
class Colors:
|
|
|
|
# Ultralytics color palette https://ultralytics.com/
|
|
|
|
def __init__(self):
|
2021-05-12 23:41:11 +08:00
|
|
|
# hex = matplotlib.colors.TABLEAU_COLORS.values()
|
|
|
|
hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
|
|
|
|
'2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
|
|
|
|
self.palette = [self.hex2rgb('#' + c) for c in hex]
|
2021-04-28 22:05:14 +08:00
|
|
|
self.n = len(self.palette)
|
|
|
|
|
|
|
|
def __call__(self, i, bgr=False):
|
|
|
|
c = self.palette[int(i) % self.n]
|
|
|
|
return (c[2], c[1], c[0]) if bgr else c
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def hex2rgb(h): # rgb order (PIL)
|
2020-11-14 18:50:32 +08:00
|
|
|
return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
|
|
|
|
|
2021-04-28 22:05:14 +08:00
|
|
|
|
|
|
|
colors = Colors() # create instance for 'from utils.plots import colors'
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
|
|
|
|
def hist2d(x, y, n=100):
|
|
|
|
# 2d histogram used in labels.png and evolve.png
|
|
|
|
xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
|
|
|
|
hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
|
|
|
|
xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
|
|
|
|
yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
|
|
|
|
return np.log(hist[xidx, yidx])
|
|
|
|
|
|
|
|
|
|
|
|
def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
|
2021-04-30 03:16:23 +08:00
|
|
|
from scipy.signal import butter, filtfilt
|
|
|
|
|
2020-11-14 18:50:32 +08:00
|
|
|
# https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
|
|
|
|
def butter_lowpass(cutoff, fs, order):
|
|
|
|
nyq = 0.5 * fs
|
|
|
|
normal_cutoff = cutoff / nyq
|
|
|
|
return butter(order, normal_cutoff, btype='low', analog=False)
|
|
|
|
|
|
|
|
b, a = butter_lowpass(cutoff, fs, order=order)
|
|
|
|
return filtfilt(b, a, data) # forward-backward filter
|
|
|
|
|
|
|
|
|
2021-05-20 01:47:36 +08:00
|
|
|
def plot_one_box(x, im, color=(128, 128, 128), label=None, line_thickness=3):
|
2021-04-18 19:47:40 +08:00
|
|
|
# Plots one bounding box on image 'im' using OpenCV
|
|
|
|
assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
|
|
|
|
tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
|
2020-11-14 18:50:32 +08:00
|
|
|
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
|
2021-04-18 19:47:40 +08:00
|
|
|
cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
|
2020-11-14 18:50:32 +08:00
|
|
|
if label:
|
|
|
|
tf = max(tl - 1, 1) # font thickness
|
|
|
|
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
|
|
|
|
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
|
2021-04-18 19:47:40 +08:00
|
|
|
cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
|
|
|
|
cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
|
2021-05-20 01:47:36 +08:00
|
|
|
def plot_one_box_PIL(box, im, color=(128, 128, 128), label=None, line_thickness=None):
|
2021-04-18 19:47:40 +08:00
|
|
|
# Plots one bounding box on image 'im' using PIL
|
|
|
|
im = Image.fromarray(im)
|
|
|
|
draw = ImageDraw.Draw(im)
|
|
|
|
line_thickness = line_thickness or max(int(min(im.size) / 200), 2)
|
2021-05-20 01:47:36 +08:00
|
|
|
draw.rectangle(box, width=line_thickness, outline=color) # plot
|
2021-02-20 07:20:41 +08:00
|
|
|
if label:
|
2021-05-20 01:47:36 +08:00
|
|
|
font = ImageFont.truetype("Arial.ttf", size=max(round(max(im.size) / 40), 12))
|
2021-02-20 07:20:41 +08:00
|
|
|
txt_width, txt_height = font.getsize(label)
|
2021-05-20 01:47:36 +08:00
|
|
|
draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=color)
|
2021-02-20 07:20:41 +08:00
|
|
|
draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
|
2021-04-18 19:47:40 +08:00
|
|
|
return np.asarray(im)
|
2021-02-20 07:20:41 +08:00
|
|
|
|
|
|
|
|
2020-11-18 00:29:55 +08:00
|
|
|
def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Compares the two methods for width-height anchor multiplication
|
|
|
|
# https://github.com/ultralytics/yolov3/issues/168
|
|
|
|
x = np.arange(-4.0, 4.0, .1)
|
|
|
|
ya = np.exp(x)
|
|
|
|
yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
|
|
|
|
|
2020-12-02 22:53:16 +08:00
|
|
|
fig = plt.figure(figsize=(6, 3), tight_layout=True)
|
2020-11-14 18:50:32 +08:00
|
|
|
plt.plot(x, ya, '.-', label='YOLOv3')
|
|
|
|
plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
|
|
|
|
plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
|
|
|
|
plt.xlim(left=-4, right=4)
|
|
|
|
plt.ylim(bottom=0, top=6)
|
|
|
|
plt.xlabel('input')
|
|
|
|
plt.ylabel('output')
|
|
|
|
plt.grid()
|
|
|
|
plt.legend()
|
|
|
|
fig.savefig('comparison.png', dpi=200)
|
|
|
|
|
|
|
|
|
2020-11-26 03:33:14 +08:00
|
|
|
def output_to_target(output):
|
2020-11-14 18:50:32 +08:00
|
|
|
# Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
|
|
|
|
targets = []
|
|
|
|
for i, o in enumerate(output):
|
2020-11-26 03:33:14 +08:00
|
|
|
for *box, conf, cls in o.cpu().numpy():
|
|
|
|
targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
|
2020-11-14 18:50:32 +08:00
|
|
|
return np.array(targets)
|
|
|
|
|
|
|
|
|
|
|
|
def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
|
|
|
|
# Plot image grid with labels
|
|
|
|
|
|
|
|
if isinstance(images, torch.Tensor):
|
|
|
|
images = images.cpu().float().numpy()
|
|
|
|
if isinstance(targets, torch.Tensor):
|
|
|
|
targets = targets.cpu().numpy()
|
|
|
|
|
|
|
|
# un-normalise
|
|
|
|
if np.max(images[0]) <= 1:
|
|
|
|
images *= 255
|
|
|
|
|
|
|
|
tl = 3 # line thickness
|
|
|
|
tf = max(tl - 1, 1) # font thickness
|
|
|
|
bs, _, h, w = images.shape # batch size, _, height, width
|
|
|
|
bs = min(bs, max_subplots) # limit plot images
|
|
|
|
ns = np.ceil(bs ** 0.5) # number of subplots (square)
|
|
|
|
|
|
|
|
# Check if we should resize
|
|
|
|
scale_factor = max_size / max(h, w)
|
|
|
|
if scale_factor < 1:
|
|
|
|
h = math.ceil(scale_factor * h)
|
|
|
|
w = math.ceil(scale_factor * w)
|
|
|
|
|
|
|
|
mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
|
|
|
|
for i, img in enumerate(images):
|
|
|
|
if i == max_subplots: # if last batch has fewer images than we expect
|
|
|
|
break
|
|
|
|
|
|
|
|
block_x = int(w * (i // ns))
|
|
|
|
block_y = int(h * (i % ns))
|
|
|
|
|
|
|
|
img = img.transpose(1, 2, 0)
|
|
|
|
if scale_factor < 1:
|
|
|
|
img = cv2.resize(img, (w, h))
|
|
|
|
|
|
|
|
mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
|
|
|
|
if len(targets) > 0:
|
|
|
|
image_targets = targets[targets[:, 0] == i]
|
|
|
|
boxes = xywh2xyxy(image_targets[:, 2:6]).T
|
|
|
|
classes = image_targets[:, 1].astype('int')
|
|
|
|
labels = image_targets.shape[1] == 6 # labels if no conf column
|
|
|
|
conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
|
|
|
|
|
2020-12-01 18:29:59 +08:00
|
|
|
if boxes.shape[1]:
|
2020-12-09 10:44:13 +08:00
|
|
|
if boxes.max() <= 1.01: # if normalized with tolerance 0.01
|
2020-12-01 18:29:59 +08:00
|
|
|
boxes[[0, 2]] *= w # scale to pixels
|
|
|
|
boxes[[1, 3]] *= h
|
2020-12-02 22:53:16 +08:00
|
|
|
elif scale_factor < 1: # absolute coords need scale if image scales
|
2020-12-01 18:29:59 +08:00
|
|
|
boxes *= scale_factor
|
2020-11-14 18:50:32 +08:00
|
|
|
boxes[[0, 2]] += block_x
|
|
|
|
boxes[[1, 3]] += block_y
|
|
|
|
for j, box in enumerate(boxes.T):
|
|
|
|
cls = int(classes[j])
|
2021-04-28 22:05:14 +08:00
|
|
|
color = colors(cls)
|
2020-11-14 18:50:32 +08:00
|
|
|
cls = names[cls] if names else cls
|
2020-11-16 20:35:34 +08:00
|
|
|
if labels or conf[j] > 0.25: # 0.25 conf thresh
|
2020-11-14 18:50:32 +08:00
|
|
|
label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
|
|
|
|
plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
|
|
|
|
|
|
|
|
# Draw image filename labels
|
2020-11-16 20:35:34 +08:00
|
|
|
if paths:
|
|
|
|
label = Path(paths[i]).name[:40] # trim to 40 char
|
2020-11-14 18:50:32 +08:00
|
|
|
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
|
|
|
|
cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
|
|
|
|
lineType=cv2.LINE_AA)
|
|
|
|
|
|
|
|
# Image border
|
|
|
|
cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
|
|
|
|
|
2020-11-16 20:35:34 +08:00
|
|
|
if fname:
|
2020-11-14 18:50:32 +08:00
|
|
|
r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
|
|
|
|
mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
|
|
|
|
# cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
|
|
|
|
Image.fromarray(mosaic).save(fname) # PIL save
|
|
|
|
return mosaic
|
|
|
|
|
|
|
|
|
|
|
|
def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
|
|
|
|
# Plot LR simulating training for full epochs
|
|
|
|
optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
|
|
|
|
y = []
|
|
|
|
for _ in range(epochs):
|
|
|
|
scheduler.step()
|
|
|
|
y.append(optimizer.param_groups[0]['lr'])
|
|
|
|
plt.plot(y, '.-', label='LR')
|
|
|
|
plt.xlabel('epoch')
|
|
|
|
plt.ylabel('LR')
|
|
|
|
plt.grid()
|
|
|
|
plt.xlim(0, epochs)
|
|
|
|
plt.ylim(0)
|
|
|
|
plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
|
2021-01-05 07:49:08 +08:00
|
|
|
plt.close()
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
|
2020-11-18 00:29:55 +08:00
|
|
|
def plot_test_txt(): # from utils.plots import *; plot_test()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Plot test.txt histograms
|
|
|
|
x = np.loadtxt('test.txt', dtype=np.float32)
|
|
|
|
box = xyxy2xywh(x[:, :4])
|
|
|
|
cx, cy = box[:, 0], box[:, 1]
|
|
|
|
|
|
|
|
fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
|
|
|
|
ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
|
|
|
|
ax.set_aspect('equal')
|
|
|
|
plt.savefig('hist2d.png', dpi=300)
|
|
|
|
|
|
|
|
fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
|
|
|
|
ax[0].hist(cx, bins=600)
|
|
|
|
ax[1].hist(cy, bins=600)
|
|
|
|
plt.savefig('hist1d.png', dpi=200)
|
|
|
|
|
|
|
|
|
2020-11-18 00:29:55 +08:00
|
|
|
def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Plot targets.txt histograms
|
|
|
|
x = np.loadtxt('targets.txt', dtype=np.float32).T
|
|
|
|
s = ['x targets', 'y targets', 'width targets', 'height targets']
|
|
|
|
fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
|
|
|
|
ax = ax.ravel()
|
|
|
|
for i in range(4):
|
|
|
|
ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
|
|
|
|
ax[i].legend()
|
|
|
|
ax[i].set_title(s[i])
|
|
|
|
plt.savefig('targets.jpg', dpi=200)
|
|
|
|
|
|
|
|
|
2021-02-01 05:58:49 +08:00
|
|
|
def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Plot study.txt generated by test.py
|
2021-06-09 22:25:17 +08:00
|
|
|
plot2 = False # plot additional results
|
|
|
|
if plot2:
|
|
|
|
ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
|
2021-04-12 01:23:47 +08:00
|
|
|
# for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
|
2021-02-02 05:51:11 +08:00
|
|
|
for f in sorted(Path(path).glob('study*.txt')):
|
2020-11-14 18:50:32 +08:00
|
|
|
y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
|
|
|
|
x = np.arange(y.shape[1]) if x is None else np.array(x)
|
2021-06-09 22:25:17 +08:00
|
|
|
if plot2:
|
|
|
|
s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
|
|
|
|
for i in range(7):
|
|
|
|
ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
|
|
|
|
ax[i].set_title(s[i])
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
j = y[3].argmax() + 1
|
2021-06-09 22:25:17 +08:00
|
|
|
ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
|
2020-11-27 05:18:17 +08:00
|
|
|
label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
|
|
|
|
'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
|
|
|
|
|
2021-02-02 05:51:11 +08:00
|
|
|
ax2.grid(alpha=0.2)
|
|
|
|
ax2.set_yticks(np.arange(20, 60, 5))
|
2021-04-12 01:23:47 +08:00
|
|
|
ax2.set_xlim(0, 57)
|
2021-02-02 05:51:11 +08:00
|
|
|
ax2.set_ylim(30, 55)
|
2020-11-14 18:50:32 +08:00
|
|
|
ax2.set_xlabel('GPU Speed (ms/img)')
|
|
|
|
ax2.set_ylabel('COCO AP val')
|
|
|
|
ax2.legend(loc='lower right')
|
2021-02-02 05:51:11 +08:00
|
|
|
plt.savefig(str(Path(path).name) + '.png', dpi=300)
|
2020-11-14 18:50:32 +08:00
|
|
|
|
|
|
|
|
2021-03-13 14:15:41 +08:00
|
|
|
def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
|
2020-11-14 18:50:32 +08:00
|
|
|
# plot dataset labels
|
2020-12-19 10:05:38 +08:00
|
|
|
print('Plotting labels... ')
|
2020-11-14 18:50:32 +08:00
|
|
|
c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
|
|
|
|
nc = int(c.max() + 1) # number of classes
|
2020-12-19 10:05:38 +08:00
|
|
|
x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
|
2020-11-14 18:50:32 +08:00
|
|
|
|
2020-11-18 19:27:30 +08:00
|
|
|
# seaborn correlogram
|
2021-06-10 19:51:29 +08:00
|
|
|
sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
|
2020-12-19 10:05:38 +08:00
|
|
|
plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
|
|
|
|
plt.close()
|
2020-11-18 19:27:30 +08:00
|
|
|
|
|
|
|
# matplotlib labels
|
2020-12-02 22:53:16 +08:00
|
|
|
matplotlib.use('svg') # faster
|
2020-11-18 19:27:30 +08:00
|
|
|
ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
|
2021-05-17 17:44:22 +08:00
|
|
|
y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
|
2021-06-28 19:18:45 +08:00
|
|
|
# [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
|
2021-03-13 14:15:41 +08:00
|
|
|
ax[0].set_ylabel('instances')
|
|
|
|
if 0 < len(names) < 30:
|
|
|
|
ax[0].set_xticks(range(len(names)))
|
|
|
|
ax[0].set_xticklabels(names, rotation=90, fontsize=10)
|
|
|
|
else:
|
|
|
|
ax[0].set_xlabel('classes')
|
2021-06-10 19:51:29 +08:00
|
|
|
sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
|
|
|
|
sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
|
2020-11-18 07:17:33 +08:00
|
|
|
|
|
|
|
# rectangles
|
|
|
|
labels[:, 1:3] = 0.5 # center
|
|
|
|
labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
|
|
|
|
img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
|
|
|
|
for cls, *box in labels[:1000]:
|
2021-04-28 22:05:14 +08:00
|
|
|
ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
|
2020-11-18 07:17:33 +08:00
|
|
|
ax[1].imshow(img)
|
|
|
|
ax[1].axis('off')
|
|
|
|
|
|
|
|
for a in [0, 1, 2, 3]:
|
|
|
|
for s in ['top', 'right', 'left', 'bottom']:
|
|
|
|
ax[a].spines[s].set_visible(False)
|
2020-12-02 22:53:16 +08:00
|
|
|
|
|
|
|
plt.savefig(save_dir / 'labels.jpg', dpi=200)
|
|
|
|
matplotlib.use('Agg')
|
2020-11-14 18:50:32 +08:00
|
|
|
plt.close()
|
|
|
|
|
2020-11-30 23:44:14 +08:00
|
|
|
# loggers
|
|
|
|
for k, v in loggers.items() or {}:
|
|
|
|
if k == 'wandb' and v:
|
2021-01-27 13:16:01 +08:00
|
|
|
v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
|
2020-11-30 23:44:14 +08:00
|
|
|
|
2020-11-14 18:50:32 +08:00
|
|
|
|
2020-11-18 00:29:55 +08:00
|
|
|
def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Plot hyperparameter evolution results in evolve.txt
|
|
|
|
with open(yaml_file) as f:
|
2021-04-21 20:34:45 +08:00
|
|
|
hyp = yaml.safe_load(f)
|
2020-11-14 18:50:32 +08:00
|
|
|
x = np.loadtxt('evolve.txt', ndmin=2)
|
|
|
|
f = fitness(x)
|
|
|
|
# weights = (f - f.min()) ** 2 # for weighted results
|
|
|
|
plt.figure(figsize=(10, 12), tight_layout=True)
|
|
|
|
matplotlib.rc('font', **{'size': 8})
|
|
|
|
for i, (k, v) in enumerate(hyp.items()):
|
|
|
|
y = x[:, i + 7]
|
|
|
|
# mu = (y * weights).sum() / weights.sum() # best weighted result
|
|
|
|
mu = y[f.argmax()] # best single result
|
|
|
|
plt.subplot(6, 5, i + 1)
|
|
|
|
plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
|
|
|
|
plt.plot(mu, f.max(), 'k+', markersize=15)
|
|
|
|
plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
|
|
|
|
if i % 5 != 0:
|
|
|
|
plt.yticks([])
|
|
|
|
print('%15s: %.3g' % (k, mu))
|
|
|
|
plt.savefig('evolve.png', dpi=200)
|
|
|
|
print('\nPlot saved as evolve.png')
|
|
|
|
|
|
|
|
|
2020-12-16 10:35:47 +08:00
|
|
|
def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
|
2020-12-18 17:19:17 +08:00
|
|
|
# Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
|
|
|
|
ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
|
2020-12-16 10:35:47 +08:00
|
|
|
s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
|
|
|
|
files = list(Path(save_dir).glob('frames*.txt'))
|
|
|
|
for fi, f in enumerate(files):
|
|
|
|
try:
|
|
|
|
results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
|
|
|
|
n = results.shape[1] # number of rows
|
|
|
|
x = np.arange(start, min(stop, n) if stop else n)
|
2020-12-18 17:19:17 +08:00
|
|
|
results = results[:, x]
|
2020-12-16 10:35:47 +08:00
|
|
|
t = (results[0] - results[0].min()) # set t0=0s
|
|
|
|
results[0] = x
|
|
|
|
for i, a in enumerate(ax):
|
|
|
|
if i < len(results):
|
|
|
|
label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
|
2020-12-18 17:19:17 +08:00
|
|
|
a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
|
2020-12-16 10:35:47 +08:00
|
|
|
a.set_title(s[i])
|
|
|
|
a.set_xlabel('time (s)')
|
|
|
|
# if fi == len(files) - 1:
|
2020-12-18 17:19:17 +08:00
|
|
|
# a.set_ylim(bottom=0)
|
2020-12-16 10:35:47 +08:00
|
|
|
for side in ['top', 'right']:
|
|
|
|
a.spines[side].set_visible(False)
|
|
|
|
else:
|
|
|
|
a.remove()
|
|
|
|
except Exception as e:
|
|
|
|
print('Warning: Plotting error for %s; %s' % (f, e))
|
|
|
|
|
|
|
|
ax[1].legend()
|
2020-12-18 17:19:17 +08:00
|
|
|
plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
|
2020-12-16 10:35:47 +08:00
|
|
|
|
|
|
|
|
2020-11-18 00:29:55 +08:00
|
|
|
def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
|
2020-11-14 18:50:32 +08:00
|
|
|
# Plot training 'results*.txt', overlaying train and val losses
|
|
|
|
s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
|
|
|
|
t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
|
|
|
|
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
|
|
|
|
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
|
|
|
|
n = results.shape[1] # number of rows
|
|
|
|
x = range(start, min(stop, n) if stop else n)
|
|
|
|
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
|
|
|
|
ax = ax.ravel()
|
|
|
|
for i in range(5):
|
|
|
|
for j in [i, i + 5]:
|
|
|
|
y = results[j, x]
|
|
|
|
ax[i].plot(x, y, marker='.', label=s[j])
|
|
|
|
# y_smooth = butter_lowpass_filtfilt(y)
|
|
|
|
# ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
|
|
|
|
|
|
|
|
ax[i].set_title(t[i])
|
|
|
|
ax[i].legend()
|
|
|
|
ax[i].set_ylabel(f) if i == 0 else None # add filename
|
|
|
|
fig.savefig(f.replace('.txt', '.png'), dpi=200)
|
|
|
|
|
|
|
|
|
|
|
|
def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
|
2020-11-18 00:29:55 +08:00
|
|
|
# Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
|
2020-12-02 22:53:16 +08:00
|
|
|
fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
|
2020-11-14 18:50:32 +08:00
|
|
|
ax = ax.ravel()
|
|
|
|
s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
|
|
|
|
'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
|
|
|
|
if bucket:
|
|
|
|
# files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
|
|
|
|
files = ['results%g.txt' % x for x in id]
|
|
|
|
c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
|
|
|
|
os.system(c)
|
|
|
|
else:
|
2020-11-18 00:29:55 +08:00
|
|
|
files = list(Path(save_dir).glob('results*.txt'))
|
2020-11-14 18:50:32 +08:00
|
|
|
assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
|
|
|
|
for fi, f in enumerate(files):
|
|
|
|
try:
|
|
|
|
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
|
|
|
|
n = results.shape[1] # number of rows
|
|
|
|
x = range(start, min(stop, n) if stop else n)
|
|
|
|
for i in range(10):
|
|
|
|
y = results[i, x]
|
|
|
|
if i in [0, 1, 2, 5, 6, 7]:
|
|
|
|
y[y == 0] = np.nan # don't show zero loss values
|
|
|
|
# y /= y[0] # normalize
|
2020-11-18 00:29:55 +08:00
|
|
|
label = labels[fi] if len(labels) else f.stem
|
2020-11-27 01:33:28 +08:00
|
|
|
ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
|
2020-11-14 18:50:32 +08:00
|
|
|
ax[i].set_title(s[i])
|
|
|
|
# if i in [5, 6, 7]: # share train and val loss y axes
|
|
|
|
# ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
|
|
|
|
except Exception as e:
|
|
|
|
print('Warning: Plotting error for %s; %s' % (f, e))
|
|
|
|
|
|
|
|
ax[1].legend()
|
|
|
|
fig.savefig(Path(save_dir) / 'results.png', dpi=200)
|
2021-06-28 19:18:45 +08:00
|
|
|
|
|
|
|
|
2021-07-09 21:23:02 +08:00
|
|
|
def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
|
2021-06-28 19:18:45 +08:00
|
|
|
"""
|
2021-06-28 19:48:14 +08:00
|
|
|
x: Features to be visualized
|
2021-06-28 19:18:45 +08:00
|
|
|
module_type: Module type
|
2021-06-28 19:48:14 +08:00
|
|
|
stage: Module stage within model
|
2021-06-28 19:18:45 +08:00
|
|
|
n: Maximum number of feature maps to plot
|
2021-07-07 21:41:58 +08:00
|
|
|
save_dir: Directory to save results
|
2021-06-28 19:18:45 +08:00
|
|
|
"""
|
2021-07-07 21:41:58 +08:00
|
|
|
if 'Detect' not in module_type:
|
|
|
|
batch, channels, height, width = x.shape # batch, channels, height, width
|
|
|
|
if height > 1 and width > 1:
|
|
|
|
f = f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
|
|
|
|
|
2021-07-07 22:23:31 +08:00
|
|
|
blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
|
2021-07-07 21:41:58 +08:00
|
|
|
n = min(n, channels) # number of plots
|
2021-07-09 21:23:02 +08:00
|
|
|
fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
|
|
|
|
ax = ax.ravel()
|
|
|
|
plt.subplots_adjust(wspace=0.05, hspace=0.05)
|
2021-07-07 21:41:58 +08:00
|
|
|
for i in range(n):
|
|
|
|
ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
|
|
|
|
ax[i].axis('off')
|
|
|
|
|
|
|
|
print(f'Saving {save_dir / f}... ({n}/{channels})')
|
2021-07-09 21:23:02 +08:00
|
|
|
plt.savefig(save_dir / f, dpi=300, bbox_inches='tight')
|