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

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

Comments

Loading...