Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

plots.py 18 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
  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_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()
  208. # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)
  209. save_dir = Path(file).parent if file else Path(dir)
  210. plot2 = False # plot additional results
  211. if plot2:
  212. ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
  213. fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
  214. # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
  215. for f in sorted(save_dir.glob('study*.txt')):
  216. y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
  217. x = np.arange(y.shape[1]) if x is None else np.array(x)
  218. if plot2:
  219. s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
  220. for i in range(7):
  221. ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
  222. ax[i].set_title(s[i])
  223. j = y[3].argmax() + 1
  224. ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
  225. label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
  226. ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
  227. 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
  228. ax2.grid(alpha=0.2)
  229. ax2.set_yticks(np.arange(20, 60, 5))
  230. ax2.set_xlim(0, 57)
  231. ax2.set_ylim(30, 55)
  232. ax2.set_xlabel('GPU Speed (ms/img)')
  233. ax2.set_ylabel('COCO AP val')
  234. ax2.legend(loc='lower right')
  235. f = save_dir / 'study.png'
  236. print(f'Saving {f}...')
  237. plt.savefig(f, dpi=300)
  238. def plot_labels(labels, names=(), save_dir=Path('')):
  239. # plot dataset labels
  240. print('Plotting labels... ')
  241. c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
  242. nc = int(c.max() + 1) # number of classes
  243. x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
  244. # seaborn correlogram
  245. sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
  246. plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
  247. plt.close()
  248. # matplotlib labels
  249. matplotlib.use('svg') # faster
  250. ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
  251. y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
  252. # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
  253. ax[0].set_ylabel('instances')
  254. if 0 < len(names) < 30:
  255. ax[0].set_xticks(range(len(names)))
  256. ax[0].set_xticklabels(names, rotation=90, fontsize=10)
  257. else:
  258. ax[0].set_xlabel('classes')
  259. sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
  260. sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
  261. # rectangles
  262. labels[:, 1:3] = 0.5 # center
  263. labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
  264. img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
  265. for cls, *box in labels[:1000]:
  266. ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
  267. ax[1].imshow(img)
  268. ax[1].axis('off')
  269. for a in [0, 1, 2, 3]:
  270. for s in ['top', 'right', 'left', 'bottom']:
  271. ax[a].spines[s].set_visible(False)
  272. plt.savefig(save_dir / 'labels.jpg', dpi=200)
  273. matplotlib.use('Agg')
  274. plt.close()
  275. def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
  276. # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
  277. ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
  278. s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
  279. files = list(Path(save_dir).glob('frames*.txt'))
  280. for fi, f in enumerate(files):
  281. try:
  282. results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
  283. n = results.shape[1] # number of rows
  284. x = np.arange(start, min(stop, n) if stop else n)
  285. results = results[:, x]
  286. t = (results[0] - results[0].min()) # set t0=0s
  287. results[0] = x
  288. for i, a in enumerate(ax):
  289. if i < len(results):
  290. label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
  291. a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
  292. a.set_title(s[i])
  293. a.set_xlabel('time (s)')
  294. # if fi == len(files) - 1:
  295. # a.set_ylim(bottom=0)
  296. for side in ['top', 'right']:
  297. a.spines[side].set_visible(False)
  298. else:
  299. a.remove()
  300. except Exception as e:
  301. print('Warning: Plotting error for %s; %s' % (f, e))
  302. ax[1].legend()
  303. plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
  304. def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
  305. # Plot evolve.csv hyp evolution results
  306. evolve_csv = Path(evolve_csv)
  307. data = pd.read_csv(evolve_csv)
  308. keys = [x.strip() for x in data.columns]
  309. x = data.values
  310. f = fitness(x)
  311. j = np.argmax(f) # max fitness index
  312. plt.figure(figsize=(10, 12), tight_layout=True)
  313. matplotlib.rc('font', **{'size': 8})
  314. for i, k in enumerate(keys[7:]):
  315. v = x[:, 7 + i]
  316. mu = v[j] # best single result
  317. plt.subplot(6, 5, i + 1)
  318. plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
  319. plt.plot(mu, f.max(), 'k+', markersize=15)
  320. plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
  321. if i % 5 != 0:
  322. plt.yticks([])
  323. print('%15s: %.3g' % (k, mu))
  324. f = evolve_csv.with_suffix('.png') # filename
  325. plt.savefig(f, dpi=200)
  326. plt.close()
  327. print(f'Saved {f}')
  328. def plot_results(file='path/to/results.csv', dir=''):
  329. # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
  330. save_dir = Path(file).parent if file else Path(dir)
  331. fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
  332. ax = ax.ravel()
  333. files = list(save_dir.glob('results*.csv'))
  334. assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
  335. for fi, f in enumerate(files):
  336. try:
  337. data = pd.read_csv(f)
  338. s = [x.strip() for x in data.columns]
  339. x = data.values[:, 0]
  340. for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
  341. y = data.values[:, j]
  342. # y[y == 0] = np.nan # don't show zero values
  343. ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
  344. ax[i].set_title(s[j], fontsize=12)
  345. # if j in [8, 9, 10]: # share train and val loss y axes
  346. # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
  347. except Exception as e:
  348. print(f'Warning: Plotting error for {f}: {e}')
  349. ax[1].legend()
  350. fig.savefig(save_dir / 'results.png', dpi=200)
  351. plt.close()
  352. def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
  353. """
  354. x: Features to be visualized
  355. module_type: Module type
  356. stage: Module stage within model
  357. n: Maximum number of feature maps to plot
  358. save_dir: Directory to save results
  359. """
  360. if 'Detect' not in module_type:
  361. batch, channels, height, width = x.shape # batch, channels, height, width
  362. if height > 1 and width > 1:
  363. f = f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
  364. blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
  365. n = min(n, channels) # number of plots
  366. fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
  367. ax = ax.ravel()
  368. plt.subplots_adjust(wspace=0.05, hspace=0.05)
  369. for i in range(n):
  370. ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
  371. ax[i].axis('off')
  372. print(f'Saving {save_dir / f}... ({n}/{channels})')
  373. plt.savefig(save_dir / f, dpi=300, bbox_inches='tight')
  374. plt.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...