Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

443 rindas
18KB

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