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.

1069 lines
44KB

  1. # Dataset utils and dataloaders
  2. import glob
  3. import logging
  4. import math
  5. import os
  6. import random
  7. import shutil
  8. import time
  9. from itertools import repeat
  10. from multiprocessing.pool import ThreadPool
  11. from pathlib import Path
  12. from threading import Thread
  13. import cv2
  14. import numpy as np
  15. import torch
  16. import torch.nn.functional as F
  17. from PIL import Image, ExifTags
  18. from torch.utils.data import Dataset
  19. from tqdm import tqdm
  20. from utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \
  21. resample_segments, clean_str
  22. from utils.torch_utils import torch_distributed_zero_first
  23. # Parameters
  24. help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
  25. img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
  26. vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
  27. logger = logging.getLogger(__name__)
  28. # Get orientation exif tag
  29. for orientation in ExifTags.TAGS.keys():
  30. if ExifTags.TAGS[orientation] == 'Orientation':
  31. break
  32. def get_hash(files):
  33. # Returns a single hash value of a list of files
  34. return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
  35. def exif_size(img):
  36. # Returns exif-corrected PIL size
  37. s = img.size # (width, height)
  38. try:
  39. rotation = dict(img._getexif().items())[orientation]
  40. if rotation == 6: # rotation 270
  41. s = (s[1], s[0])
  42. elif rotation == 8: # rotation 90
  43. s = (s[1], s[0])
  44. except:
  45. pass
  46. return s
  47. def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
  48. rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):
  49. # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
  50. with torch_distributed_zero_first(rank):
  51. dataset = LoadImagesAndLabels(path, imgsz, batch_size,
  52. augment=augment, # augment images
  53. hyp=hyp, # augmentation hyperparameters
  54. rect=rect, # rectangular training
  55. cache_images=cache,
  56. single_cls=opt.single_cls,
  57. stride=int(stride),
  58. pad=pad,
  59. image_weights=image_weights,
  60. prefix=prefix)
  61. batch_size = min(batch_size, len(dataset))
  62. nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers
  63. sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
  64. loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
  65. # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
  66. dataloader = loader(dataset,
  67. batch_size=batch_size,
  68. num_workers=nw,
  69. sampler=sampler,
  70. pin_memory=True,
  71. collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
  72. return dataloader, dataset
  73. class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
  74. """ Dataloader that reuses workers
  75. Uses same syntax as vanilla DataLoader
  76. """
  77. def __init__(self, *args, **kwargs):
  78. super().__init__(*args, **kwargs)
  79. object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
  80. self.iterator = super().__iter__()
  81. def __len__(self):
  82. return len(self.batch_sampler.sampler)
  83. def __iter__(self):
  84. for i in range(len(self)):
  85. yield next(self.iterator)
  86. class _RepeatSampler(object):
  87. """ Sampler that repeats forever
  88. Args:
  89. sampler (Sampler)
  90. """
  91. def __init__(self, sampler):
  92. self.sampler = sampler
  93. def __iter__(self):
  94. while True:
  95. yield from iter(self.sampler)
  96. class LoadImages: # for inference
  97. def __init__(self, path, img_size=640, stride=32):
  98. p = str(Path(path).absolute()) # os-agnostic absolute path
  99. if '*' in p:
  100. files = sorted(glob.glob(p, recursive=True)) # glob
  101. elif os.path.isdir(p):
  102. files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
  103. elif os.path.isfile(p):
  104. files = [p] # files
  105. else:
  106. raise Exception(f'ERROR: {p} does not exist')
  107. images = [x for x in files if x.split('.')[-1].lower() in img_formats]
  108. videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
  109. ni, nv = len(images), len(videos)
  110. self.img_size = img_size
  111. self.stride = stride
  112. self.files = images + videos
  113. self.nf = ni + nv # number of files
  114. self.video_flag = [False] * ni + [True] * nv
  115. self.mode = 'image'
  116. if any(videos):
  117. self.new_video(videos[0]) # new video
  118. else:
  119. self.cap = None
  120. assert self.nf > 0, f'No images or videos found in {p}. ' \
  121. f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
  122. def __iter__(self):
  123. self.count = 0
  124. return self
  125. def __next__(self):
  126. if self.count == self.nf:
  127. raise StopIteration
  128. path = self.files[self.count]
  129. if self.video_flag[self.count]:
  130. # Read video
  131. self.mode = 'video'
  132. ret_val, img0 = self.cap.read()
  133. if not ret_val:
  134. self.count += 1
  135. self.cap.release()
  136. if self.count == self.nf: # last video
  137. raise StopIteration
  138. else:
  139. path = self.files[self.count]
  140. self.new_video(path)
  141. ret_val, img0 = self.cap.read()
  142. self.frame += 1
  143. print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')
  144. else:
  145. # Read image
  146. self.count += 1
  147. img0 = cv2.imread(path) # BGR
  148. assert img0 is not None, 'Image Not Found ' + path
  149. print(f'image {self.count}/{self.nf} {path}: ', end='')
  150. # Padded resize
  151. img = letterbox(img0, self.img_size, stride=self.stride)[0]
  152. # Convert
  153. img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
  154. img = np.ascontiguousarray(img)
  155. return path, img, img0, self.cap
  156. def new_video(self, path):
  157. self.frame = 0
  158. self.cap = cv2.VideoCapture(path)
  159. self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
  160. def __len__(self):
  161. return self.nf # number of files
  162. class LoadWebcam: # for inference
  163. def __init__(self, pipe='0', img_size=640, stride=32):
  164. self.img_size = img_size
  165. self.stride = stride
  166. if pipe.isnumeric():
  167. pipe = eval(pipe) # local camera
  168. # pipe = 'rtsp://192.168.1.64/1' # IP camera
  169. # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login
  170. # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
  171. self.pipe = pipe
  172. self.cap = cv2.VideoCapture(pipe) # video capture object
  173. self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
  174. def __iter__(self):
  175. self.count = -1
  176. return self
  177. def __next__(self):
  178. self.count += 1
  179. if cv2.waitKey(1) == ord('q'): # q to quit
  180. self.cap.release()
  181. cv2.destroyAllWindows()
  182. raise StopIteration
  183. # Read frame
  184. if self.pipe == 0: # local camera
  185. ret_val, img0 = self.cap.read()
  186. img0 = cv2.flip(img0, 1) # flip left-right
  187. else: # IP camera
  188. n = 0
  189. while True:
  190. n += 1
  191. self.cap.grab()
  192. if n % 30 == 0: # skip frames
  193. ret_val, img0 = self.cap.retrieve()
  194. if ret_val:
  195. break
  196. # Print
  197. assert ret_val, f'Camera Error {self.pipe}'
  198. img_path = 'webcam.jpg'
  199. print(f'webcam {self.count}: ', end='')
  200. # Padded resize
  201. img = letterbox(img0, self.img_size, stride=self.stride)[0]
  202. # Convert
  203. img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
  204. img = np.ascontiguousarray(img)
  205. return img_path, img, img0, None
  206. def __len__(self):
  207. return 0
  208. class LoadStreams: # multiple IP or RTSP cameras
  209. def __init__(self, sources='streams.txt', img_size=640, stride=32):
  210. self.mode = 'stream'
  211. self.img_size = img_size
  212. self.stride = stride
  213. if os.path.isfile(sources):
  214. with open(sources, 'r') as f:
  215. sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
  216. else:
  217. sources = [sources]
  218. n = len(sources)
  219. self.imgs = [None] * n
  220. self.sources = [clean_str(x) for x in sources] # clean source names for later
  221. for i, s in enumerate(sources): # index, source
  222. # Start thread to read frames from video stream
  223. print(f'{i + 1}/{n}: {s}... ', end='')
  224. if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
  225. check_requirements(('pafy', 'youtube_dl'))
  226. import pafy
  227. s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
  228. s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
  229. cap = cv2.VideoCapture(s)
  230. assert cap.isOpened(), f'Failed to open {s}'
  231. w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  232. h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  233. self.fps = (cap.get(cv2.CAP_PROP_FPS) % 100) or 30.0 # assume 30 FPS if cap gets 0 FPS
  234. self.frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
  235. _, self.imgs[i] = cap.read() # guarantee first frame
  236. thread = Thread(target=self.update, args=([i, cap]), daemon=True)
  237. print(f" success ({f'{self.frames} frames ' if self.frames else ''}{w}x{h} at {self.fps:.2f} FPS).")
  238. thread.start()
  239. print('') # newline
  240. # check for common shapes
  241. s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
  242. self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
  243. if not self.rect:
  244. print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
  245. def update(self, index, cap):
  246. # Read next stream frame in a daemon thread
  247. n = 0
  248. while cap.isOpened():
  249. n += 1
  250. # _, self.imgs[index] = cap.read()
  251. cap.grab()
  252. if n == 4: # read every 4th frame
  253. success, im = cap.retrieve()
  254. self.imgs[index] = im if success else self.imgs[index] * 0
  255. n = 0
  256. time.sleep(1 / self.fps) # wait time
  257. def __iter__(self):
  258. self.count = -1
  259. return self
  260. def __next__(self):
  261. self.count += 1
  262. img0 = self.imgs.copy()
  263. if cv2.waitKey(1) == ord('q'): # q to quit
  264. cv2.destroyAllWindows()
  265. raise StopIteration
  266. # Letterbox
  267. img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
  268. # Stack
  269. img = np.stack(img, 0)
  270. # Convert
  271. img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
  272. img = np.ascontiguousarray(img)
  273. return self.sources, img, img0, None
  274. def __len__(self):
  275. return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
  276. def img2label_paths(img_paths):
  277. # Define label paths as a function of image paths
  278. sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
  279. return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths]
  280. class LoadImagesAndLabels(Dataset): # for training/testing
  281. def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
  282. cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
  283. self.img_size = img_size
  284. self.augment = augment
  285. self.hyp = hyp
  286. self.image_weights = image_weights
  287. self.rect = False if image_weights else rect
  288. self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
  289. self.mosaic_border = [-img_size // 2, -img_size // 2]
  290. self.stride = stride
  291. self.path = path
  292. try:
  293. f = [] # image files
  294. for p in path if isinstance(path, list) else [path]:
  295. p = Path(p) # os-agnostic
  296. if p.is_dir(): # dir
  297. f += glob.glob(str(p / '**' / '*.*'), recursive=True)
  298. # f = list(p.rglob('**/*.*')) # pathlib
  299. elif p.is_file(): # file
  300. with open(p, 'r') as t:
  301. t = t.read().strip().splitlines()
  302. parent = str(p.parent) + os.sep
  303. f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
  304. # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
  305. else:
  306. raise Exception(f'{prefix}{p} does not exist')
  307. self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
  308. # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
  309. assert self.img_files, f'{prefix}No images found'
  310. except Exception as e:
  311. raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
  312. # Check cache
  313. self.label_files = img2label_paths(self.img_files) # labels
  314. cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
  315. if cache_path.is_file():
  316. cache, exists = torch.load(cache_path), True # load
  317. if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed
  318. cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
  319. else:
  320. cache, exists = self.cache_labels(cache_path, prefix), False # cache
  321. # Display cache
  322. nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
  323. if exists:
  324. d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
  325. tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
  326. assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
  327. # Read cache
  328. cache.pop('hash') # remove hash
  329. cache.pop('version') # remove version
  330. labels, shapes, self.segments = zip(*cache.values())
  331. self.labels = list(labels)
  332. self.shapes = np.array(shapes, dtype=np.float64)
  333. self.img_files = list(cache.keys()) # update
  334. self.label_files = img2label_paths(cache.keys()) # update
  335. if single_cls:
  336. for x in self.labels:
  337. x[:, 0] = 0
  338. n = len(shapes) # number of images
  339. bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
  340. nb = bi[-1] + 1 # number of batches
  341. self.batch = bi # batch index of image
  342. self.n = n
  343. self.indices = range(n)
  344. # Rectangular Training
  345. if self.rect:
  346. # Sort by aspect ratio
  347. s = self.shapes # wh
  348. ar = s[:, 1] / s[:, 0] # aspect ratio
  349. irect = ar.argsort()
  350. self.img_files = [self.img_files[i] for i in irect]
  351. self.label_files = [self.label_files[i] for i in irect]
  352. self.labels = [self.labels[i] for i in irect]
  353. self.shapes = s[irect] # wh
  354. ar = ar[irect]
  355. # Set training image shapes
  356. shapes = [[1, 1]] * nb
  357. for i in range(nb):
  358. ari = ar[bi == i]
  359. mini, maxi = ari.min(), ari.max()
  360. if maxi < 1:
  361. shapes[i] = [maxi, 1]
  362. elif mini > 1:
  363. shapes[i] = [1, 1 / mini]
  364. self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
  365. # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
  366. self.imgs = [None] * n
  367. if cache_images:
  368. gb = 0 # Gigabytes of cached images
  369. self.img_hw0, self.img_hw = [None] * n, [None] * n
  370. results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) # 8 threads
  371. pbar = tqdm(enumerate(results), total=n)
  372. for i, x in pbar:
  373. self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i)
  374. gb += self.imgs[i].nbytes
  375. pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
  376. pbar.close()
  377. def cache_labels(self, path=Path('./labels.cache'), prefix=''):
  378. # Cache dataset labels, check images and read shapes
  379. x = {} # dict
  380. nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
  381. pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
  382. for i, (im_file, lb_file) in enumerate(pbar):
  383. try:
  384. # verify images
  385. im = Image.open(im_file)
  386. im.verify() # PIL verify
  387. shape = exif_size(im) # image size
  388. segments = [] # instance segments
  389. assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
  390. assert im.format.lower() in img_formats, f'invalid image format {im.format}'
  391. # verify labels
  392. if os.path.isfile(lb_file):
  393. nf += 1 # label found
  394. with open(lb_file, 'r') as f:
  395. l = [x.split() for x in f.read().strip().splitlines()]
  396. if any([len(x) > 8 for x in l]): # is segment
  397. classes = np.array([x[0] for x in l], dtype=np.float32)
  398. segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
  399. l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
  400. l = np.array(l, dtype=np.float32)
  401. if len(l):
  402. assert l.shape[1] == 5, 'labels require 5 columns each'
  403. assert (l >= 0).all(), 'negative labels'
  404. assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
  405. assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
  406. else:
  407. ne += 1 # label empty
  408. l = np.zeros((0, 5), dtype=np.float32)
  409. else:
  410. nm += 1 # label missing
  411. l = np.zeros((0, 5), dtype=np.float32)
  412. x[im_file] = [l, shape, segments]
  413. except Exception as e:
  414. nc += 1
  415. logging.info(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
  416. pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
  417. f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
  418. pbar.close()
  419. if nf == 0:
  420. logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
  421. x['hash'] = get_hash(self.label_files + self.img_files)
  422. x['results'] = nf, nm, ne, nc, i + 1
  423. x['version'] = 0.1 # cache version
  424. try:
  425. torch.save(x, path) # save for next time
  426. logging.info(f'{prefix}New cache created: {path}')
  427. except Exception as e:
  428. logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable
  429. return x
  430. def __len__(self):
  431. return len(self.img_files)
  432. # def __iter__(self):
  433. # self.count = -1
  434. # print('ran dataset iter')
  435. # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
  436. # return self
  437. def __getitem__(self, index):
  438. index = self.indices[index] # linear, shuffled, or image_weights
  439. hyp = self.hyp
  440. mosaic = self.mosaic and random.random() < hyp['mosaic']
  441. if mosaic:
  442. # Load mosaic
  443. img, labels = load_mosaic(self, index)
  444. shapes = None
  445. # MixUp https://arxiv.org/pdf/1710.09412.pdf
  446. if random.random() < hyp['mixup']:
  447. img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))
  448. r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
  449. img = (img * r + img2 * (1 - r)).astype(np.uint8)
  450. labels = np.concatenate((labels, labels2), 0)
  451. else:
  452. # Load image
  453. img, (h0, w0), (h, w) = load_image(self, index)
  454. # Letterbox
  455. shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
  456. img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
  457. shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
  458. labels = self.labels[index].copy()
  459. if labels.size: # normalized xywh to pixel xyxy format
  460. labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
  461. if self.augment:
  462. # Augment imagespace
  463. if not mosaic:
  464. img, labels = random_perspective(img, labels,
  465. degrees=hyp['degrees'],
  466. translate=hyp['translate'],
  467. scale=hyp['scale'],
  468. shear=hyp['shear'],
  469. perspective=hyp['perspective'])
  470. # Augment colorspace
  471. augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
  472. # Apply cutouts
  473. # if random.random() < 0.9:
  474. # labels = cutout(img, labels)
  475. nL = len(labels) # number of labels
  476. if nL:
  477. labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
  478. labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
  479. labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
  480. if self.augment:
  481. # flip up-down
  482. if random.random() < hyp['flipud']:
  483. img = np.flipud(img)
  484. if nL:
  485. labels[:, 2] = 1 - labels[:, 2]
  486. # flip left-right
  487. if random.random() < hyp['fliplr']:
  488. img = np.fliplr(img)
  489. if nL:
  490. labels[:, 1] = 1 - labels[:, 1]
  491. labels_out = torch.zeros((nL, 6))
  492. if nL:
  493. labels_out[:, 1:] = torch.from_numpy(labels)
  494. # Convert
  495. img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
  496. img = np.ascontiguousarray(img)
  497. return torch.from_numpy(img), labels_out, self.img_files[index], shapes
  498. @staticmethod
  499. def collate_fn(batch):
  500. img, label, path, shapes = zip(*batch) # transposed
  501. for i, l in enumerate(label):
  502. l[:, 0] = i # add target image index for build_targets()
  503. return torch.stack(img, 0), torch.cat(label, 0), path, shapes
  504. @staticmethod
  505. def collate_fn4(batch):
  506. img, label, path, shapes = zip(*batch) # transposed
  507. n = len(shapes) // 4
  508. img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
  509. ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
  510. wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
  511. s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
  512. for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
  513. i *= 4
  514. if random.random() < 0.5:
  515. im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
  516. 0].type(img[i].type())
  517. l = label[i]
  518. else:
  519. im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
  520. l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
  521. img4.append(im)
  522. label4.append(l)
  523. for i, l in enumerate(label4):
  524. l[:, 0] = i # add target image index for build_targets()
  525. return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
  526. # Ancillary functions --------------------------------------------------------------------------------------------------
  527. def load_image(self, index):
  528. # loads 1 image from dataset, returns img, original hw, resized hw
  529. img = self.imgs[index]
  530. if img is None: # not cached
  531. path = self.img_files[index]
  532. img = cv2.imread(path) # BGR
  533. assert img is not None, 'Image Not Found ' + path
  534. h0, w0 = img.shape[:2] # orig hw
  535. r = self.img_size / max(h0, w0) # ratio
  536. if r != 1: # if sizes are not equal
  537. img = cv2.resize(img, (int(w0 * r), int(h0 * r)),
  538. interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
  539. return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
  540. else:
  541. return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
  542. def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
  543. r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
  544. hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  545. dtype = img.dtype # uint8
  546. x = np.arange(0, 256, dtype=np.int16)
  547. lut_hue = ((x * r[0]) % 180).astype(dtype)
  548. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  549. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  550. img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
  551. cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
  552. def hist_equalize(img, clahe=True, bgr=False):
  553. # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
  554. yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
  555. if clahe:
  556. c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
  557. yuv[:, :, 0] = c.apply(yuv[:, :, 0])
  558. else:
  559. yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
  560. return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
  561. def load_mosaic(self, index):
  562. # loads images in a 4-mosaic
  563. labels4, segments4 = [], []
  564. s = self.img_size
  565. yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
  566. indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
  567. for i, index in enumerate(indices):
  568. # Load image
  569. img, _, (h, w) = load_image(self, index)
  570. # place img in img4
  571. if i == 0: # top left
  572. img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  573. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  574. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  575. elif i == 1: # top right
  576. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
  577. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  578. elif i == 2: # bottom left
  579. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
  580. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  581. elif i == 3: # bottom right
  582. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
  583. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  584. img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
  585. padw = x1a - x1b
  586. padh = y1a - y1b
  587. # Labels
  588. labels, segments = self.labels[index].copy(), self.segments[index].copy()
  589. if labels.size:
  590. labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
  591. segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
  592. labels4.append(labels)
  593. segments4.extend(segments)
  594. # Concat/clip labels
  595. labels4 = np.concatenate(labels4, 0)
  596. for x in (labels4[:, 1:], *segments4):
  597. np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
  598. # img4, labels4 = replicate(img4, labels4) # replicate
  599. # Augment
  600. img4, labels4 = random_perspective(img4, labels4, segments4,
  601. degrees=self.hyp['degrees'],
  602. translate=self.hyp['translate'],
  603. scale=self.hyp['scale'],
  604. shear=self.hyp['shear'],
  605. perspective=self.hyp['perspective'],
  606. border=self.mosaic_border) # border to remove
  607. return img4, labels4
  608. def load_mosaic9(self, index):
  609. # loads images in a 9-mosaic
  610. labels9, segments9 = [], []
  611. s = self.img_size
  612. indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
  613. for i, index in enumerate(indices):
  614. # Load image
  615. img, _, (h, w) = load_image(self, index)
  616. # place img in img9
  617. if i == 0: # center
  618. img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  619. h0, w0 = h, w
  620. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  621. elif i == 1: # top
  622. c = s, s - h, s + w, s
  623. elif i == 2: # top right
  624. c = s + wp, s - h, s + wp + w, s
  625. elif i == 3: # right
  626. c = s + w0, s, s + w0 + w, s + h
  627. elif i == 4: # bottom right
  628. c = s + w0, s + hp, s + w0 + w, s + hp + h
  629. elif i == 5: # bottom
  630. c = s + w0 - w, s + h0, s + w0, s + h0 + h
  631. elif i == 6: # bottom left
  632. c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
  633. elif i == 7: # left
  634. c = s - w, s + h0 - h, s, s + h0
  635. elif i == 8: # top left
  636. c = s - w, s + h0 - hp - h, s, s + h0 - hp
  637. padx, pady = c[:2]
  638. x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
  639. # Labels
  640. labels, segments = self.labels[index].copy(), self.segments[index].copy()
  641. if labels.size:
  642. labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
  643. segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
  644. labels9.append(labels)
  645. segments9.extend(segments)
  646. # Image
  647. img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
  648. hp, wp = h, w # height, width previous
  649. # Offset
  650. yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
  651. img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
  652. # Concat/clip labels
  653. labels9 = np.concatenate(labels9, 0)
  654. labels9[:, [1, 3]] -= xc
  655. labels9[:, [2, 4]] -= yc
  656. c = np.array([xc, yc]) # centers
  657. segments9 = [x - c for x in segments9]
  658. for x in (labels9[:, 1:], *segments9):
  659. np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
  660. # img9, labels9 = replicate(img9, labels9) # replicate
  661. # Augment
  662. img9, labels9 = random_perspective(img9, labels9, segments9,
  663. degrees=self.hyp['degrees'],
  664. translate=self.hyp['translate'],
  665. scale=self.hyp['scale'],
  666. shear=self.hyp['shear'],
  667. perspective=self.hyp['perspective'],
  668. border=self.mosaic_border) # border to remove
  669. return img9, labels9
  670. def replicate(img, labels):
  671. # Replicate labels
  672. h, w = img.shape[:2]
  673. boxes = labels[:, 1:].astype(int)
  674. x1, y1, x2, y2 = boxes.T
  675. s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
  676. for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
  677. x1b, y1b, x2b, y2b = boxes[i]
  678. bh, bw = y2b - y1b, x2b - x1b
  679. yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
  680. x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
  681. img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
  682. labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
  683. return img, labels
  684. def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
  685. # Resize and pad image while meeting stride-multiple constraints
  686. shape = img.shape[:2] # current shape [height, width]
  687. if isinstance(new_shape, int):
  688. new_shape = (new_shape, new_shape)
  689. # Scale ratio (new / old)
  690. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  691. if not scaleup: # only scale down, do not scale up (for better test mAP)
  692. r = min(r, 1.0)
  693. # Compute padding
  694. ratio = r, r # width, height ratios
  695. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  696. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  697. if auto: # minimum rectangle
  698. dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
  699. elif scaleFill: # stretch
  700. dw, dh = 0.0, 0.0
  701. new_unpad = (new_shape[1], new_shape[0])
  702. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  703. dw /= 2 # divide padding into 2 sides
  704. dh /= 2
  705. if shape[::-1] != new_unpad: # resize
  706. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  707. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  708. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  709. img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
  710. return img, ratio, (dw, dh)
  711. def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
  712. border=(0, 0)):
  713. # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
  714. # targets = [cls, xyxy]
  715. height = img.shape[0] + border[0] * 2 # shape(h,w,c)
  716. width = img.shape[1] + border[1] * 2
  717. # Center
  718. C = np.eye(3)
  719. C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
  720. C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
  721. # Perspective
  722. P = np.eye(3)
  723. P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
  724. P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
  725. # Rotation and Scale
  726. R = np.eye(3)
  727. a = random.uniform(-degrees, degrees)
  728. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  729. s = random.uniform(1 - scale, 1 + scale)
  730. # s = 2 ** random.uniform(-scale, scale)
  731. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  732. # Shear
  733. S = np.eye(3)
  734. S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
  735. S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
  736. # Translation
  737. T = np.eye(3)
  738. T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
  739. T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
  740. # Combined rotation matrix
  741. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  742. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  743. if perspective:
  744. img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
  745. else: # affine
  746. img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
  747. # Visualize
  748. # import matplotlib.pyplot as plt
  749. # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
  750. # ax[0].imshow(img[:, :, ::-1]) # base
  751. # ax[1].imshow(img2[:, :, ::-1]) # warped
  752. # Transform label coordinates
  753. n = len(targets)
  754. if n:
  755. use_segments = any(x.any() for x in segments)
  756. new = np.zeros((n, 4))
  757. if use_segments: # warp segments
  758. segments = resample_segments(segments) # upsample
  759. for i, segment in enumerate(segments):
  760. xy = np.ones((len(segment), 3))
  761. xy[:, :2] = segment
  762. xy = xy @ M.T # transform
  763. xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
  764. # clip
  765. new[i] = segment2box(xy, width, height)
  766. else: # warp boxes
  767. xy = np.ones((n * 4, 3))
  768. xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  769. xy = xy @ M.T # transform
  770. xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  771. # create new boxes
  772. x = xy[:, [0, 2, 4, 6]]
  773. y = xy[:, [1, 3, 5, 7]]
  774. new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
  775. # clip
  776. new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
  777. new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
  778. # filter candidates
  779. i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
  780. targets = targets[i]
  781. targets[:, 1:5] = new[i]
  782. return img, targets
  783. def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
  784. # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
  785. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  786. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  787. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  788. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
  789. def cutout(image, labels):
  790. # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
  791. h, w = image.shape[:2]
  792. def bbox_ioa(box1, box2):
  793. # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
  794. box2 = box2.transpose()
  795. # Get the coordinates of bounding boxes
  796. b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
  797. b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
  798. # Intersection area
  799. inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
  800. (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
  801. # box2 area
  802. box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
  803. # Intersection over box2 area
  804. return inter_area / box2_area
  805. # create random masks
  806. scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
  807. for s in scales:
  808. mask_h = random.randint(1, int(h * s))
  809. mask_w = random.randint(1, int(w * s))
  810. # box
  811. xmin = max(0, random.randint(0, w) - mask_w // 2)
  812. ymin = max(0, random.randint(0, h) - mask_h // 2)
  813. xmax = min(w, xmin + mask_w)
  814. ymax = min(h, ymin + mask_h)
  815. # apply random color mask
  816. image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
  817. # return unobscured labels
  818. if len(labels) and s > 0.03:
  819. box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
  820. ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
  821. labels = labels[ioa < 0.60] # remove >60% obscured labels
  822. return labels
  823. def create_folder(path='./new'):
  824. # Create folder
  825. if os.path.exists(path):
  826. shutil.rmtree(path) # delete output folder
  827. os.makedirs(path) # make new output folder
  828. def flatten_recursive(path='../coco128'):
  829. # Flatten a recursive directory by bringing all files to top level
  830. new_path = Path(path + '_flat')
  831. create_folder(new_path)
  832. for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
  833. shutil.copyfile(file, new_path / Path(file).name)
  834. def extract_boxes(path='../coco128/'): # from utils.datasets import *; extract_boxes('../coco128')
  835. # Convert detection dataset into classification dataset, with one directory per class
  836. path = Path(path) # images dir
  837. shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
  838. files = list(path.rglob('*.*'))
  839. n = len(files) # number of files
  840. for im_file in tqdm(files, total=n):
  841. if im_file.suffix[1:] in img_formats:
  842. # image
  843. im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
  844. h, w = im.shape[:2]
  845. # labels
  846. lb_file = Path(img2label_paths([str(im_file)])[0])
  847. if Path(lb_file).exists():
  848. with open(lb_file, 'r') as f:
  849. lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
  850. for j, x in enumerate(lb):
  851. c = int(x[0]) # class
  852. f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
  853. if not f.parent.is_dir():
  854. f.parent.mkdir(parents=True)
  855. b = x[1:] * [w, h, w, h] # box
  856. # b[2:] = b[2:].max() # rectangle to square
  857. b[2:] = b[2:] * 1.2 + 3 # pad
  858. b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
  859. b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
  860. b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
  861. assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
  862. def autosplit(path='../coco128', weights=(0.9, 0.1, 0.0), annotated_only=False):
  863. """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
  864. Usage: from utils.datasets import *; autosplit('../coco128')
  865. Arguments
  866. path: Path to images directory
  867. weights: Train, val, test weights (list)
  868. annotated_only: Only use images with an annotated txt file
  869. """
  870. path = Path(path) # images dir
  871. files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
  872. n = len(files) # number of files
  873. indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
  874. txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
  875. [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing
  876. print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
  877. for i, img in tqdm(zip(indices, files), total=n):
  878. if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
  879. with open(path / txt[i], 'a') as f:
  880. f.write(str(img) + '\n') # add image to txt file