You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

491 lines
21KB

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