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.

472 lines
20KB

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