Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

448 lignes
19KB

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