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.

414 rindas
17KB

  1. # Plotting utils
  2. import glob
  3. import math
  4. import os
  5. import random
  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 sns
  14. import torch
  15. import yaml
  16. from PIL import Image, ImageDraw
  17. from scipy.signal import butter, filtfilt
  18. from utils.general import xywh2xyxy, xyxy2xywh
  19. from utils.metrics import fitness
  20. # Settings
  21. matplotlib.rc('font', **{'size': 11})
  22. matplotlib.use('Agg') # for writing to files only
  23. def color_list():
  24. # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
  25. def hex2rgb(h):
  26. return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
  27. return [hex2rgb(h) for h in plt.rcParams['axes.prop_cycle'].by_key()['color']]
  28. def hist2d(x, y, n=100):
  29. # 2d histogram used in labels.png and evolve.png
  30. xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
  31. hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
  32. xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
  33. yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
  34. return np.log(hist[xidx, yidx])
  35. def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
  36. # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
  37. def butter_lowpass(cutoff, fs, order):
  38. nyq = 0.5 * fs
  39. normal_cutoff = cutoff / nyq
  40. return butter(order, normal_cutoff, btype='low', analog=False)
  41. b, a = butter_lowpass(cutoff, fs, order=order)
  42. return filtfilt(b, a, data) # forward-backward filter
  43. def plot_one_box(x, img, color=None, label=None, line_thickness=None):
  44. # Plots one bounding box on image img
  45. tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
  46. color = color or [random.randint(0, 255) for _ in range(3)]
  47. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  48. cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
  49. if label:
  50. tf = max(tl - 1, 1) # font thickness
  51. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  52. c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
  53. cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
  54. cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
  55. def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
  56. # Compares the two methods for width-height anchor multiplication
  57. # https://github.com/ultralytics/yolov3/issues/168
  58. x = np.arange(-4.0, 4.0, .1)
  59. ya = np.exp(x)
  60. yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
  61. fig = plt.figure(figsize=(6, 3), tight_layout=True)
  62. plt.plot(x, ya, '.-', label='YOLOv3')
  63. plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
  64. plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
  65. plt.xlim(left=-4, right=4)
  66. plt.ylim(bottom=0, top=6)
  67. plt.xlabel('input')
  68. plt.ylabel('output')
  69. plt.grid()
  70. plt.legend()
  71. fig.savefig('comparison.png', dpi=200)
  72. def output_to_target(output):
  73. # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
  74. targets = []
  75. for i, o in enumerate(output):
  76. for *box, conf, cls in o.cpu().numpy():
  77. targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
  78. return np.array(targets)
  79. def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
  80. # Plot image grid with labels
  81. if isinstance(images, torch.Tensor):
  82. images = images.cpu().float().numpy()
  83. if isinstance(targets, torch.Tensor):
  84. targets = targets.cpu().numpy()
  85. # un-normalise
  86. if np.max(images[0]) <= 1:
  87. images *= 255
  88. tl = 3 # line thickness
  89. tf = max(tl - 1, 1) # font thickness
  90. bs, _, h, w = images.shape # batch size, _, height, width
  91. bs = min(bs, max_subplots) # limit plot images
  92. ns = np.ceil(bs ** 0.5) # number of subplots (square)
  93. # Check if we should resize
  94. scale_factor = max_size / max(h, w)
  95. if scale_factor < 1:
  96. h = math.ceil(scale_factor * h)
  97. w = math.ceil(scale_factor * w)
  98. colors = color_list() # list of colors
  99. mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
  100. for i, img in enumerate(images):
  101. if i == max_subplots: # if last batch has fewer images than we expect
  102. break
  103. block_x = int(w * (i // ns))
  104. block_y = int(h * (i % ns))
  105. img = img.transpose(1, 2, 0)
  106. if scale_factor < 1:
  107. img = cv2.resize(img, (w, h))
  108. mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
  109. if len(targets) > 0:
  110. image_targets = targets[targets[:, 0] == i]
  111. boxes = xywh2xyxy(image_targets[:, 2:6]).T
  112. classes = image_targets[:, 1].astype('int')
  113. labels = image_targets.shape[1] == 6 # labels if no conf column
  114. conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
  115. if boxes.shape[1]:
  116. if boxes.max() <= 1.01: # if normalized with tolerance 0.01
  117. boxes[[0, 2]] *= w # scale to pixels
  118. boxes[[1, 3]] *= h
  119. elif scale_factor < 1: # absolute coords need scale if image scales
  120. boxes *= scale_factor
  121. boxes[[0, 2]] += block_x
  122. boxes[[1, 3]] += block_y
  123. for j, box in enumerate(boxes.T):
  124. cls = int(classes[j])
  125. color = colors[cls % len(colors)]
  126. cls = names[cls] if names else cls
  127. if labels or conf[j] > 0.25: # 0.25 conf thresh
  128. label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
  129. plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
  130. # Draw image filename labels
  131. if paths:
  132. label = Path(paths[i]).name[:40] # trim to 40 char
  133. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  134. cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
  135. lineType=cv2.LINE_AA)
  136. # Image border
  137. cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
  138. if fname:
  139. r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
  140. mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
  141. # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
  142. Image.fromarray(mosaic).save(fname) # PIL save
  143. return mosaic
  144. def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
  145. # Plot LR simulating training for full epochs
  146. optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
  147. y = []
  148. for _ in range(epochs):
  149. scheduler.step()
  150. y.append(optimizer.param_groups[0]['lr'])
  151. plt.plot(y, '.-', label='LR')
  152. plt.xlabel('epoch')
  153. plt.ylabel('LR')
  154. plt.grid()
  155. plt.xlim(0, epochs)
  156. plt.ylim(0)
  157. plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
  158. plt.close()
  159. def plot_test_txt(): # from utils.plots import *; plot_test()
  160. # Plot test.txt histograms
  161. x = np.loadtxt('test.txt', dtype=np.float32)
  162. box = xyxy2xywh(x[:, :4])
  163. cx, cy = box[:, 0], box[:, 1]
  164. fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
  165. ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
  166. ax.set_aspect('equal')
  167. plt.savefig('hist2d.png', dpi=300)
  168. fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
  169. ax[0].hist(cx, bins=600)
  170. ax[1].hist(cy, bins=600)
  171. plt.savefig('hist1d.png', dpi=200)
  172. def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
  173. # Plot targets.txt histograms
  174. x = np.loadtxt('targets.txt', dtype=np.float32).T
  175. s = ['x targets', 'y targets', 'width targets', 'height targets']
  176. fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
  177. ax = ax.ravel()
  178. for i in range(4):
  179. ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
  180. ax[i].legend()
  181. ax[i].set_title(s[i])
  182. plt.savefig('targets.jpg', dpi=200)
  183. def plot_study_txt(path='study/', x=None): # from utils.plots import *; plot_study_txt()
  184. # Plot study.txt generated by test.py
  185. fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
  186. ax = ax.ravel()
  187. fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
  188. for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']]:
  189. y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
  190. x = np.arange(y.shape[1]) if x is None else np.array(x)
  191. s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
  192. for i in range(7):
  193. ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
  194. ax[i].set_title(s[i])
  195. j = y[3].argmax() + 1
  196. ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8,
  197. label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
  198. ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
  199. 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
  200. ax2.grid()
  201. ax2.set_yticks(np.arange(30, 60, 5))
  202. ax2.set_xlim(0, 30)
  203. ax2.set_ylim(29, 51)
  204. ax2.set_xlabel('GPU Speed (ms/img)')
  205. ax2.set_ylabel('COCO AP val')
  206. ax2.legend(loc='lower right')
  207. plt.savefig('test_study.png', dpi=300)
  208. def plot_labels(labels, save_dir=Path(''), loggers=None):
  209. # plot dataset labels
  210. print('Plotting labels... ')
  211. c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
  212. nc = int(c.max() + 1) # number of classes
  213. colors = color_list()
  214. x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
  215. # seaborn correlogram
  216. sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
  217. plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
  218. plt.close()
  219. # matplotlib labels
  220. matplotlib.use('svg') # faster
  221. ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
  222. ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
  223. ax[0].set_xlabel('classes')
  224. sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
  225. sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
  226. # rectangles
  227. labels[:, 1:3] = 0.5 # center
  228. labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
  229. img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
  230. for cls, *box in labels[:1000]:
  231. ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
  232. ax[1].imshow(img)
  233. ax[1].axis('off')
  234. for a in [0, 1, 2, 3]:
  235. for s in ['top', 'right', 'left', 'bottom']:
  236. ax[a].spines[s].set_visible(False)
  237. plt.savefig(save_dir / 'labels.jpg', dpi=200)
  238. matplotlib.use('Agg')
  239. plt.close()
  240. # loggers
  241. for k, v in loggers.items() or {}:
  242. if k == 'wandb' and v:
  243. v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]})
  244. def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
  245. # Plot hyperparameter evolution results in evolve.txt
  246. with open(yaml_file) as f:
  247. hyp = yaml.load(f, Loader=yaml.FullLoader)
  248. x = np.loadtxt('evolve.txt', ndmin=2)
  249. f = fitness(x)
  250. # weights = (f - f.min()) ** 2 # for weighted results
  251. plt.figure(figsize=(10, 12), tight_layout=True)
  252. matplotlib.rc('font', **{'size': 8})
  253. for i, (k, v) in enumerate(hyp.items()):
  254. y = x[:, i + 7]
  255. # mu = (y * weights).sum() / weights.sum() # best weighted result
  256. mu = y[f.argmax()] # best single result
  257. plt.subplot(6, 5, i + 1)
  258. plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
  259. plt.plot(mu, f.max(), 'k+', markersize=15)
  260. plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
  261. if i % 5 != 0:
  262. plt.yticks([])
  263. print('%15s: %.3g' % (k, mu))
  264. plt.savefig('evolve.png', dpi=200)
  265. print('\nPlot saved as evolve.png')
  266. def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
  267. # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
  268. ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
  269. s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
  270. files = list(Path(save_dir).glob('frames*.txt'))
  271. for fi, f in enumerate(files):
  272. try:
  273. results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
  274. n = results.shape[1] # number of rows
  275. x = np.arange(start, min(stop, n) if stop else n)
  276. results = results[:, x]
  277. t = (results[0] - results[0].min()) # set t0=0s
  278. results[0] = x
  279. for i, a in enumerate(ax):
  280. if i < len(results):
  281. label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
  282. a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
  283. a.set_title(s[i])
  284. a.set_xlabel('time (s)')
  285. # if fi == len(files) - 1:
  286. # a.set_ylim(bottom=0)
  287. for side in ['top', 'right']:
  288. a.spines[side].set_visible(False)
  289. else:
  290. a.remove()
  291. except Exception as e:
  292. print('Warning: Plotting error for %s; %s' % (f, e))
  293. ax[1].legend()
  294. plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
  295. def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
  296. # Plot training 'results*.txt', overlaying train and val losses
  297. s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
  298. t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
  299. for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
  300. results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
  301. n = results.shape[1] # number of rows
  302. x = range(start, min(stop, n) if stop else n)
  303. fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
  304. ax = ax.ravel()
  305. for i in range(5):
  306. for j in [i, i + 5]:
  307. y = results[j, x]
  308. ax[i].plot(x, y, marker='.', label=s[j])
  309. # y_smooth = butter_lowpass_filtfilt(y)
  310. # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
  311. ax[i].set_title(t[i])
  312. ax[i].legend()
  313. ax[i].set_ylabel(f) if i == 0 else None # add filename
  314. fig.savefig(f.replace('.txt', '.png'), dpi=200)
  315. def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
  316. # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
  317. fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
  318. ax = ax.ravel()
  319. s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
  320. 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
  321. if bucket:
  322. # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
  323. files = ['results%g.txt' % x for x in id]
  324. c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
  325. os.system(c)
  326. else:
  327. files = list(Path(save_dir).glob('results*.txt'))
  328. assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
  329. for fi, f in enumerate(files):
  330. try:
  331. results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
  332. n = results.shape[1] # number of rows
  333. x = range(start, min(stop, n) if stop else n)
  334. for i in range(10):
  335. y = results[i, x]
  336. if i in [0, 1, 2, 5, 6, 7]:
  337. y[y == 0] = np.nan # don't show zero loss values
  338. # y /= y[0] # normalize
  339. label = labels[fi] if len(labels) else f.stem
  340. ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
  341. ax[i].set_title(s[i])
  342. # if i in [5, 6, 7]: # 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('Warning: Plotting error for %s; %s' % (f, e))
  346. ax[1].legend()
  347. fig.savefig(Path(save_dir) / 'results.png', dpi=200)