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.

plots.py 18KB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Plotting utils
  4. """
  5. import math
  6. from copy import copy
  7. from pathlib import Path
  8. import cv2
  9. import matplotlib
  10. import matplotlib.pyplot as plt
  11. import numpy as np
  12. import pandas as pd
  13. import seaborn as sn
  14. import torch
  15. from PIL import Image, ImageDraw, ImageFont
  16. from utils.general import user_config_dir, is_ascii, xywh2xyxy, xyxy2xywh
  17. from utils.metrics import fitness
  18. # Settings
  19. CONFIG_DIR = user_config_dir() # Ultralytics settings dir
  20. matplotlib.rc('font', **{'size': 11})
  21. matplotlib.use('Agg') # for writing to files only
  22. class Colors:
  23. # Ultralytics color palette https://ultralytics.com/
  24. def __init__(self):
  25. # hex = matplotlib.colors.TABLEAU_COLORS.values()
  26. hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
  27. '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
  28. self.palette = [self.hex2rgb('#' + c) for c in hex]
  29. self.n = len(self.palette)
  30. def __call__(self, i, bgr=False):
  31. c = self.palette[int(i) % self.n]
  32. return (c[2], c[1], c[0]) if bgr else c
  33. @staticmethod
  34. def hex2rgb(h): # rgb order (PIL)
  35. return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
  36. colors = Colors() # create instance for 'from utils.plots import colors'
  37. def check_font(font='Arial.ttf', size=10):
  38. # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary
  39. font = Path(font)
  40. font = font if font.exists() else (CONFIG_DIR / font.name)
  41. try:
  42. return ImageFont.truetype(str(font) if font.exists() else font.name, size)
  43. except Exception as e: # download if missing
  44. url = "https://ultralytics.com/assets/" + font.name
  45. print(f'Downloading {url} to {font}...')
  46. torch.hub.download_url_to_file(url, str(font))
  47. return ImageFont.truetype(str(font), size)
  48. class Annotator:
  49. check_font() # download TTF if necessary
  50. # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
  51. def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=True):
  52. assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
  53. self.pil = pil
  54. if self.pil: # use PIL
  55. self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
  56. self.draw = ImageDraw.Draw(self.im)
  57. self.font = check_font(font, size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
  58. self.fh = self.font.getsize('a')[1] - 3 # font height
  59. else: # use cv2
  60. self.im = im
  61. self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width
  62. def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
  63. # Add one xyxy box to image with label
  64. if self.pil or not is_ascii(label):
  65. self.draw.rectangle(box, width=self.lw, outline=color) # box
  66. if label:
  67. w = self.font.getsize(label)[0] # text width
  68. self.draw.rectangle([box[0], box[1] - self.fh, box[0] + w + 1, box[1] + 1], fill=color)
  69. self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')
  70. else: # cv2
  71. c1, c2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
  72. cv2.rectangle(self.im, c1, c2, color, thickness=self.lw, lineType=cv2.LINE_AA)
  73. if label:
  74. tf = max(self.lw - 1, 1) # font thickness
  75. w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]
  76. c2 = c1[0] + w, c1[1] - h - 3
  77. cv2.rectangle(self.im, c1, c2, color, -1, cv2.LINE_AA) # filled
  78. cv2.putText(self.im, label, (c1[0], c1[1] - 2), 0, self.lw / 3, txt_color, thickness=tf,
  79. lineType=cv2.LINE_AA)
  80. def rectangle(self, xy, fill=None, outline=None, width=1):
  81. # Add rectangle to image (PIL-only)
  82. self.draw.rectangle(xy, fill, outline, width)
  83. def text(self, xy, text, txt_color=(255, 255, 255)):
  84. # Add text to image (PIL-only)
  85. w, h = self.font.getsize(text) # text width, height
  86. self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)
  87. def result(self):
  88. # Return annotated image as array
  89. return np.asarray(self.im)
  90. def hist2d(x, y, n=100):
  91. # 2d histogram used in labels.png and evolve.png
  92. xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
  93. hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
  94. xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
  95. yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
  96. return np.log(hist[xidx, yidx])
  97. def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
  98. from scipy.signal import butter, filtfilt
  99. # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
  100. def butter_lowpass(cutoff, fs, order):
  101. nyq = 0.5 * fs
  102. normal_cutoff = cutoff / nyq
  103. return butter(order, normal_cutoff, btype='low', analog=False)
  104. b, a = butter_lowpass(cutoff, fs, order=order)
  105. return filtfilt(b, a, data) # forward-backward filter
  106. def output_to_target(output):
  107. # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
  108. targets = []
  109. for i, o in enumerate(output):
  110. for *box, conf, cls in o.cpu().numpy():
  111. targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
  112. return np.array(targets)
  113. def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
  114. # Plot image grid with labels
  115. if isinstance(images, torch.Tensor):
  116. images = images.cpu().float().numpy()
  117. if isinstance(targets, torch.Tensor):
  118. targets = targets.cpu().numpy()
  119. if np.max(images[0]) <= 1:
  120. images *= 255.0 # de-normalise (optional)
  121. bs, _, h, w = images.shape # batch size, _, height, width
  122. bs = min(bs, max_subplots) # limit plot images
  123. ns = np.ceil(bs ** 0.5) # number of subplots (square)
  124. # Build Image
  125. mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
  126. for i, im in enumerate(images):
  127. if i == max_subplots: # if last batch has fewer images than we expect
  128. break
  129. x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
  130. im = im.transpose(1, 2, 0)
  131. mosaic[y:y + h, x:x + w, :] = im
  132. # Resize (optional)
  133. scale = max_size / ns / max(h, w)
  134. if scale < 1:
  135. h = math.ceil(scale * h)
  136. w = math.ceil(scale * w)
  137. mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
  138. # Annotate
  139. fs = int((h + w) * ns * 0.01) # font size
  140. annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs)
  141. for i in range(i + 1):
  142. x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
  143. annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
  144. if paths:
  145. annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
  146. if len(targets) > 0:
  147. ti = targets[targets[:, 0] == i] # image targets
  148. boxes = xywh2xyxy(ti[:, 2:6]).T
  149. classes = ti[:, 1].astype('int')
  150. labels = ti.shape[1] == 6 # labels if no conf column
  151. conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
  152. if boxes.shape[1]:
  153. if boxes.max() <= 1.01: # if normalized with tolerance 0.01
  154. boxes[[0, 2]] *= w # scale to pixels
  155. boxes[[1, 3]] *= h
  156. elif scale < 1: # absolute coords need scale if image scales
  157. boxes *= scale
  158. boxes[[0, 2]] += x
  159. boxes[[1, 3]] += y
  160. for j, box in enumerate(boxes.T.tolist()):
  161. cls = classes[j]
  162. color = colors(cls)
  163. cls = names[cls] if names else cls
  164. if labels or conf[j] > 0.25: # 0.25 conf thresh
  165. label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
  166. annotator.box_label(box, label, color=color)
  167. annotator.im.save(fname) # save
  168. def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
  169. # Plot LR simulating training for full epochs
  170. optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
  171. y = []
  172. for _ in range(epochs):
  173. scheduler.step()
  174. y.append(optimizer.param_groups[0]['lr'])
  175. plt.plot(y, '.-', label='LR')
  176. plt.xlabel('epoch')
  177. plt.ylabel('LR')
  178. plt.grid()
  179. plt.xlim(0, epochs)
  180. plt.ylim(0)
  181. plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
  182. plt.close()
  183. def plot_val_txt(): # from utils.plots import *; plot_val()
  184. # Plot val.txt histograms
  185. x = np.loadtxt('val.txt', dtype=np.float32)
  186. box = xyxy2xywh(x[:, :4])
  187. cx, cy = box[:, 0], box[:, 1]
  188. fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
  189. ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
  190. ax.set_aspect('equal')
  191. plt.savefig('hist2d.png', dpi=300)
  192. fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
  193. ax[0].hist(cx, bins=600)
  194. ax[1].hist(cy, bins=600)
  195. plt.savefig('hist1d.png', dpi=200)
  196. def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
  197. # Plot targets.txt histograms
  198. x = np.loadtxt('targets.txt', dtype=np.float32).T
  199. s = ['x targets', 'y targets', 'width targets', 'height targets']
  200. fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
  201. ax = ax.ravel()
  202. for i in range(4):
  203. ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
  204. ax[i].legend()
  205. ax[i].set_title(s[i])
  206. plt.savefig('targets.jpg', dpi=200)
  207. def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
  208. # Plot study.txt generated by val.py
  209. plot2 = False # plot additional results
  210. if plot2:
  211. ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
  212. fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
  213. # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
  214. for f in sorted(Path(path).glob('study*.txt')):
  215. y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
  216. x = np.arange(y.shape[1]) if x is None else np.array(x)
  217. if plot2:
  218. s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
  219. for i in range(7):
  220. ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
  221. ax[i].set_title(s[i])
  222. j = y[3].argmax() + 1
  223. ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
  224. label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
  225. ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
  226. 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
  227. ax2.grid(alpha=0.2)
  228. ax2.set_yticks(np.arange(20, 60, 5))
  229. ax2.set_xlim(0, 57)
  230. ax2.set_ylim(30, 55)
  231. ax2.set_xlabel('GPU Speed (ms/img)')
  232. ax2.set_ylabel('COCO AP val')
  233. ax2.legend(loc='lower right')
  234. plt.savefig(str(Path(path).name) + '.png', dpi=300)
  235. def plot_labels(labels, names=(), save_dir=Path('')):
  236. # plot dataset labels
  237. print('Plotting labels... ')
  238. c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
  239. nc = int(c.max() + 1) # number of classes
  240. x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
  241. # seaborn correlogram
  242. sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
  243. plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
  244. plt.close()
  245. # matplotlib labels
  246. matplotlib.use('svg') # faster
  247. ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
  248. y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
  249. # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
  250. ax[0].set_ylabel('instances')
  251. if 0 < len(names) < 30:
  252. ax[0].set_xticks(range(len(names)))
  253. ax[0].set_xticklabels(names, rotation=90, fontsize=10)
  254. else:
  255. ax[0].set_xlabel('classes')
  256. sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
  257. sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
  258. # rectangles
  259. labels[:, 1:3] = 0.5 # center
  260. labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
  261. img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
  262. for cls, *box in labels[:1000]:
  263. ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
  264. ax[1].imshow(img)
  265. ax[1].axis('off')
  266. for a in [0, 1, 2, 3]:
  267. for s in ['top', 'right', 'left', 'bottom']:
  268. ax[a].spines[s].set_visible(False)
  269. plt.savefig(save_dir / 'labels.jpg', dpi=200)
  270. matplotlib.use('Agg')
  271. plt.close()
  272. def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
  273. # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
  274. ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
  275. s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
  276. files = list(Path(save_dir).glob('frames*.txt'))
  277. for fi, f in enumerate(files):
  278. try:
  279. results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
  280. n = results.shape[1] # number of rows
  281. x = np.arange(start, min(stop, n) if stop else n)
  282. results = results[:, x]
  283. t = (results[0] - results[0].min()) # set t0=0s
  284. results[0] = x
  285. for i, a in enumerate(ax):
  286. if i < len(results):
  287. label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
  288. a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
  289. a.set_title(s[i])
  290. a.set_xlabel('time (s)')
  291. # if fi == len(files) - 1:
  292. # a.set_ylim(bottom=0)
  293. for side in ['top', 'right']:
  294. a.spines[side].set_visible(False)
  295. else:
  296. a.remove()
  297. except Exception as e:
  298. print('Warning: Plotting error for %s; %s' % (f, e))
  299. ax[1].legend()
  300. plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
  301. def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
  302. # Plot evolve.csv hyp evolution results
  303. evolve_csv = Path(evolve_csv)
  304. data = pd.read_csv(evolve_csv)
  305. keys = [x.strip() for x in data.columns]
  306. x = data.values
  307. f = fitness(x)
  308. j = np.argmax(f) # max fitness index
  309. plt.figure(figsize=(10, 12), tight_layout=True)
  310. matplotlib.rc('font', **{'size': 8})
  311. for i, k in enumerate(keys[7:]):
  312. v = x[:, 7 + i]
  313. mu = v[j] # best single result
  314. plt.subplot(6, 5, i + 1)
  315. plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
  316. plt.plot(mu, f.max(), 'k+', markersize=15)
  317. plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
  318. if i % 5 != 0:
  319. plt.yticks([])
  320. print('%15s: %.3g' % (k, mu))
  321. f = evolve_csv.with_suffix('.png') # filename
  322. plt.savefig(f, dpi=200)
  323. plt.close()
  324. print(f'Saved {f}')
  325. def plot_results(file='path/to/results.csv', dir=''):
  326. # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
  327. save_dir = Path(file).parent if file else Path(dir)
  328. fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
  329. ax = ax.ravel()
  330. files = list(save_dir.glob('results*.csv'))
  331. assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
  332. for fi, f in enumerate(files):
  333. try:
  334. data = pd.read_csv(f)
  335. s = [x.strip() for x in data.columns]
  336. x = data.values[:, 0]
  337. for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
  338. y = data.values[:, j]
  339. # y[y == 0] = np.nan # don't show zero values
  340. ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
  341. ax[i].set_title(s[j], fontsize=12)
  342. # if j in [8, 9, 10]: # share train and val loss y axes
  343. # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
  344. except Exception as e:
  345. print(f'Warning: Plotting error for {f}: {e}')
  346. ax[1].legend()
  347. fig.savefig(save_dir / 'results.png', dpi=200)
  348. plt.close()
  349. def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
  350. """
  351. x: Features to be visualized
  352. module_type: Module type
  353. stage: Module stage within model
  354. n: Maximum number of feature maps to plot
  355. save_dir: Directory to save results
  356. """
  357. if 'Detect' not in module_type:
  358. batch, channels, height, width = x.shape # batch, channels, height, width
  359. if height > 1 and width > 1:
  360. f = f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
  361. blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
  362. n = min(n, channels) # number of plots
  363. fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
  364. ax = ax.ravel()
  365. plt.subplots_adjust(wspace=0.05, hspace=0.05)
  366. for i in range(n):
  367. ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
  368. ax[i].axis('off')
  369. print(f'Saving {save_dir / f}... ({n}/{channels})')
  370. plt.savefig(save_dir / f, dpi=300, bbox_inches='tight')
  371. plt.close()