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

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

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

Comments

Loading...