hank1996 commited on
Commit
07cde38
·
1 Parent(s): 6a1a675

Update utils/datasets.py

Browse files
Files changed (1) hide show
  1. utils/datasets.py +1313 -94
utils/datasets.py CHANGED
@@ -1,100 +1,1319 @@
1
 
2
- import argparse
3
- import sys
4
- import time
5
 
6
- sys.path.append('./') # to run '$ python *.py' files in subdirectories
 
 
 
 
 
 
 
 
 
 
7
 
 
 
8
  import torch
9
- import torch.nn as nn
10
-
11
- import models
12
- from utils.google_utils import attempt_load
13
- from utils.activations import Hardswish, SiLU
14
- from utils.general import set_logging, check_img_size
15
- from utils.torch_utils import select_device
16
-
17
- if __name__ == '__main__':
18
- parser = argparse.ArgumentParser()
19
- parser.add_argument('--weights', type=str, default='./yolor-csp-c.pt', help='weights path')
20
- parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
21
- parser.add_argument('--batch-size', type=int, default=1, help='batch size')
22
- parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes')
23
- parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
24
- parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
25
- opt = parser.parse_args()
26
- opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
27
- print(opt)
28
- set_logging()
29
- t = time.time()
30
-
31
- # Load PyTorch model
32
- device = select_device(opt.device)
33
- model = attempt_load(opt.weights, map_location=device) # load FP32 model
34
- labels = model.names
35
-
36
- # Checks
37
- gs = int(max(model.stride)) # grid size (max stride)
38
- opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
39
-
40
- # Input
41
- img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
42
-
43
- # Update model
44
- for k, m in model.named_modules():
45
- m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
46
- if isinstance(m, models.common.Conv): # assign export-friendly activations
47
- if isinstance(m.act, nn.Hardswish):
48
- m.act = Hardswish()
49
- elif isinstance(m.act, nn.SiLU):
50
- m.act = SiLU()
51
- # elif isinstance(m, models.yolo.Detect):
52
- # m.forward = m.forward_export # assign forward (optional)
53
- model.model[-1].export = not opt.grid # set Detect() layer grid export
54
- y = model(img) # dry run
55
-
56
- # TorchScript export
57
- try:
58
- print('\nStarting TorchScript export with torch %s...' % torch.__version__)
59
- f = opt.weights.replace('.pt', '.torchscript.pt') # filename
60
- ts = torch.jit.trace(model, img, strict=False)
61
- ts.save(f)
62
- print('TorchScript export success, saved as %s' % f)
63
- except Exception as e:
64
- print('TorchScript export failure: %s' % e)
65
-
66
- # ONNX export
67
- try:
68
- import onnx
69
-
70
- print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
71
- f = opt.weights.replace('.pt', '.onnx') # filename
72
- torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
73
- output_names=['classes', 'boxes'] if y is None else ['output'],
74
- dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
75
- 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
76
-
77
- # Checks
78
- onnx_model = onnx.load(f) # load onnx model
79
- onnx.checker.check_model(onnx_model) # check onnx model
80
- # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
81
- print('ONNX export success, saved as %s' % f)
82
- except Exception as e:
83
- print('ONNX export failure: %s' % e)
84
-
85
- # CoreML export
86
  try:
87
- import coremltools as ct
88
-
89
- print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
90
- # convert model from torchscript and apply pixel scaling as per detect.py
91
- model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
92
- f = opt.weights.replace('.pt', '.mlmodel') # filename
93
- model.save(f)
94
- print('CoreML export success, saved as %s' % f)
95
- except Exception as e:
96
- print('CoreML export failure: %s' % e)
97
-
98
- # Finish
99
- print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
 
1
 
 
 
 
2
 
3
+ import glob
4
+ import logging
5
+ import math
6
+ import os
7
+ import random
8
+ import shutil
9
+ import time
10
+ from itertools import repeat
11
+ from multiprocessing.pool import ThreadPool
12
+ from pathlib import Path
13
+ from threading import Thread
14
 
15
+ import cv2
16
+ import numpy as np
17
  import torch
18
+ import torch.nn.functional as F
19
+ from PIL import Image, ExifTags
20
+ from torch.utils.data import Dataset
21
+ from tqdm import tqdm
22
+
23
+ import pickle
24
+ from copy import deepcopy
25
+ #from pycocotools import mask as maskUtils
26
+ from torchvision.utils import save_image
27
+ from torchvision.ops import roi_pool, roi_align, ps_roi_pool, ps_roi_align
28
+
29
+ from utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \
30
+ resample_segments, clean_str
31
+ from utils.torch_utils import torch_distributed_zero_first
32
+
33
+ # Parameters
34
+ help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
35
+ img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
36
+ vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Get orientation exif tag
40
+ for orientation in ExifTags.TAGS.keys():
41
+ if ExifTags.TAGS[orientation] == 'Orientation':
42
+ break
43
+
44
+
45
+ def get_hash(files):
46
+ # Returns a single hash value of a list of files
47
+ return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
48
+
49
+
50
+ def exif_size(img):
51
+ # Returns exif-corrected PIL size
52
+ s = img.size # (width, height)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  try:
54
+ rotation = dict(img._getexif().items())[orientation]
55
+ if rotation == 6: # rotation 270
56
+ s = (s[1], s[0])
57
+ elif rotation == 8: # rotation 90
58
+ s = (s[1], s[0])
59
+ except:
60
+ pass
61
+
62
+ return s
63
+
64
+
65
+ def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
66
+ rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):
67
+ # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
68
+ with torch_distributed_zero_first(rank):
69
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size,
70
+ augment=augment, # augment images
71
+ hyp=hyp, # augmentation hyperparameters
72
+ rect=rect, # rectangular training
73
+ cache_images=cache,
74
+ single_cls=opt.single_cls,
75
+ stride=int(stride),
76
+ pad=pad,
77
+ image_weights=image_weights,
78
+ prefix=prefix)
79
+
80
+ batch_size = min(batch_size, len(dataset))
81
+ nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers
82
+ sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
83
+ loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
84
+ # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
85
+ dataloader = loader(dataset,
86
+ batch_size=batch_size,
87
+ num_workers=nw,
88
+ sampler=sampler,
89
+ pin_memory=True,
90
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
91
+ return dataloader, dataset
92
+
93
+
94
+ class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
95
+ """ Dataloader that reuses workers
96
+ Uses same syntax as vanilla DataLoader
97
+ """
98
+
99
+ def __init__(self, *args, **kwargs):
100
+ super().__init__(*args, **kwargs)
101
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
102
+ self.iterator = super().__iter__()
103
+
104
+ def __len__(self):
105
+ return len(self.batch_sampler.sampler)
106
+
107
+ def __iter__(self):
108
+ for i in range(len(self)):
109
+ yield next(self.iterator)
110
+
111
+
112
+ class _RepeatSampler(object):
113
+ """ Sampler that repeats forever
114
+ Args:
115
+ sampler (Sampler)
116
+ """
117
+
118
+ def __init__(self, sampler):
119
+ self.sampler = sampler
120
+
121
+ def __iter__(self):
122
+ while True:
123
+ yield from iter(self.sampler)
124
+
125
+
126
+ class LoadImages: # for inference
127
+ def __init__(self, path, img_size=640, stride=32):
128
+ p = str(Path(path).absolute()) # os-agnostic absolute path
129
+ if '*' in p:
130
+ files = sorted(glob.glob(p, recursive=True)) # glob
131
+ elif os.path.isdir(p):
132
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
133
+ elif os.path.isfile(p):
134
+ files = [p] # files
135
+ else:
136
+ raise Exception(f'ERROR: {p} does not exist')
137
+
138
+ images = [x for x in files if x.split('.')[-1].lower() in img_formats]
139
+ videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
140
+ ni, nv = len(images), len(videos)
141
+
142
+ self.img_size = img_size
143
+ self.stride = stride
144
+ self.files = images + videos
145
+ self.nf = ni + nv # number of files
146
+ self.video_flag = [False] * ni + [True] * nv
147
+ self.mode = 'image'
148
+ if any(videos):
149
+ self.new_video(videos[0]) # new video
150
+ else:
151
+ self.cap = None
152
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
153
+ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
154
+
155
+ def __iter__(self):
156
+ self.count = 0
157
+ return self
158
+
159
+ def __next__(self):
160
+ if self.count == self.nf:
161
+ raise StopIteration
162
+ path = self.files[self.count]
163
+
164
+ if self.video_flag[self.count]:
165
+ # Read video
166
+ self.mode = 'video'
167
+ ret_val, img0 = self.cap.read()
168
+ if not ret_val:
169
+ self.count += 1
170
+ self.cap.release()
171
+ if self.count == self.nf: # last video
172
+ raise StopIteration
173
+ else:
174
+ path = self.files[self.count]
175
+ self.new_video(path)
176
+ ret_val, img0 = self.cap.read()
177
+
178
+ self.frame += 1
179
+ print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
180
+
181
+ else:
182
+ # Read image
183
+ self.count += 1
184
+ img0 = cv2.imread(path) # BGR
185
+ assert img0 is not None, 'Image Not Found ' + path
186
+ #print(f'image {self.count}/{self.nf} {path}: ', end='')
187
+
188
+ # Padded resize
189
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
190
+
191
+ # Convert
192
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
193
+ img = np.ascontiguousarray(img)
194
+
195
+ return path, img, img0, self.cap
196
+
197
+ def new_video(self, path):
198
+ self.frame = 0
199
+ self.cap = cv2.VideoCapture(path)
200
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
201
+
202
+ def __len__(self):
203
+ return self.nf # number of files
204
+
205
+
206
+ class LoadWebcam: # for inference
207
+ def __init__(self, pipe='0', img_size=640, stride=32):
208
+ self.img_size = img_size
209
+ self.stride = stride
210
+
211
+ if pipe.isnumeric():
212
+ pipe = eval(pipe) # local camera
213
+ # pipe = 'rtsp://192.168.1.64/1' # IP camera
214
+ # pipe = 'rtsp://username:[email protected]/1' # IP camera with login
215
+ # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
216
+
217
+ self.pipe = pipe
218
+ self.cap = cv2.VideoCapture(pipe) # video capture object
219
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
220
+
221
+ def __iter__(self):
222
+ self.count = -1
223
+ return self
224
+
225
+ def __next__(self):
226
+ self.count += 1
227
+ if cv2.waitKey(1) == ord('q'): # q to quit
228
+ self.cap.release()
229
+ cv2.destroyAllWindows()
230
+ raise StopIteration
231
+
232
+ # Read frame
233
+ if self.pipe == 0: # local camera
234
+ ret_val, img0 = self.cap.read()
235
+ img0 = cv2.flip(img0, 1) # flip left-right
236
+ else: # IP camera
237
+ n = 0
238
+ while True:
239
+ n += 1
240
+ self.cap.grab()
241
+ if n % 30 == 0: # skip frames
242
+ ret_val, img0 = self.cap.retrieve()
243
+ if ret_val:
244
+ break
245
+
246
+ # Print
247
+ assert ret_val, f'Camera Error {self.pipe}'
248
+ img_path = 'webcam.jpg'
249
+ print(f'webcam {self.count}: ', end='')
250
+
251
+ # Padded resize
252
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
253
+
254
+ # Convert
255
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
256
+ img = np.ascontiguousarray(img)
257
+
258
+ return img_path, img, img0, None
259
+
260
+ def __len__(self):
261
+ return 0
262
+
263
+
264
+ class LoadStreams: # multiple IP or RTSP cameras
265
+ def __init__(self, sources='streams.txt', img_size=640, stride=32):
266
+ self.mode = 'stream'
267
+ self.img_size = img_size
268
+ self.stride = stride
269
+
270
+ if os.path.isfile(sources):
271
+ with open(sources, 'r') as f:
272
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
273
+ else:
274
+ sources = [sources]
275
+
276
+ n = len(sources)
277
+ self.imgs = [None] * n
278
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
279
+ for i, s in enumerate(sources):
280
+ # Start the thread to read frames from the video stream
281
+ print(f'{i + 1}/{n}: {s}... ', end='')
282
+ url = eval(s) if s.isnumeric() else s
283
+ if 'youtube.com/' in url or 'youtu.be/' in url: # if source is YouTube video
284
+ check_requirements(('pafy', 'youtube_dl'))
285
+ import pafy
286
+ url = pafy.new(url).getbest(preftype="mp4").url
287
+ cap = cv2.VideoCapture(url)
288
+ assert cap.isOpened(), f'Failed to open {s}'
289
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
290
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
291
+ self.fps = cap.get(cv2.CAP_PROP_FPS) % 100
292
+
293
+ _, self.imgs[i] = cap.read() # guarantee first frame
294
+ thread = Thread(target=self.update, args=([i, cap]), daemon=True)
295
+ print(f' success ({w}x{h} at {self.fps:.2f} FPS).')
296
+ thread.start()
297
+ print('') # newline
298
+
299
+ # check for common shapes
300
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
301
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
302
+ if not self.rect:
303
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
304
+
305
+ def update(self, index, cap):
306
+ # Read next stream frame in a daemon thread
307
+ n = 0
308
+ while cap.isOpened():
309
+ n += 1
310
+ # _, self.imgs[index] = cap.read()
311
+ cap.grab()
312
+ if n == 4: # read every 4th frame
313
+ success, im = cap.retrieve()
314
+ self.imgs[index] = im if success else self.imgs[index] * 0
315
+ n = 0
316
+ time.sleep(1 / self.fps) # wait time
317
+
318
+ def __iter__(self):
319
+ self.count = -1
320
+ return self
321
+
322
+ def __next__(self):
323
+ self.count += 1
324
+ img0 = self.imgs.copy()
325
+ if cv2.waitKey(1) == ord('q'): # q to quit
326
+ cv2.destroyAllWindows()
327
+ raise StopIteration
328
+
329
+ # Letterbox
330
+ img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
331
+
332
+ # Stack
333
+ img = np.stack(img, 0)
334
+
335
+ # Convert
336
+ img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
337
+ img = np.ascontiguousarray(img)
338
+
339
+ return self.sources, img, img0, None
340
+
341
+ def __len__(self):
342
+ return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
343
+
344
+
345
+ def img2label_paths(img_paths):
346
+ # Define label paths as a function of image paths
347
+ sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
348
+ return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths]
349
+
350
+
351
+ class LoadImagesAndLabels(Dataset): # for training/testing
352
+ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
353
+ cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
354
+ self.img_size = img_size
355
+ self.augment = augment
356
+ self.hyp = hyp
357
+ self.image_weights = image_weights
358
+ self.rect = False if image_weights else rect
359
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
360
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
361
+ self.stride = stride
362
+ self.path = path
363
+ #self.albumentations = Albumentations() if augment else None
364
+
365
+ try:
366
+ f = [] # image files
367
+ for p in path if isinstance(path, list) else [path]:
368
+ p = Path(p) # os-agnostic
369
+ if p.is_dir(): # dir
370
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
371
+ # f = list(p.rglob('**/*.*')) # pathlib
372
+ elif p.is_file(): # file
373
+ with open(p, 'r') as t:
374
+ t = t.read().strip().splitlines()
375
+ parent = str(p.parent) + os.sep
376
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
377
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
378
+ else:
379
+ raise Exception(f'{prefix}{p} does not exist')
380
+ self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
381
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
382
+ assert self.img_files, f'{prefix}No images found'
383
+ except Exception as e:
384
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
385
+
386
+ # Check cache
387
+ self.label_files = img2label_paths(self.img_files) # labels
388
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
389
+ if cache_path.is_file():
390
+ cache, exists = torch.load(cache_path), True # load
391
+ #if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed
392
+ # cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
393
+ else:
394
+ cache, exists = self.cache_labels(cache_path, prefix), False # cache
395
+
396
+ # Display cache
397
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
398
+ if exists:
399
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
400
+ tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
401
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
402
+
403
+ # Read cache
404
+ cache.pop('hash') # remove hash
405
+ cache.pop('version') # remove version
406
+ labels, shapes, self.segments = zip(*cache.values())
407
+ self.labels = list(labels)
408
+ self.shapes = np.array(shapes, dtype=np.float64)
409
+ self.img_files = list(cache.keys()) # update
410
+ self.label_files = img2label_paths(cache.keys()) # update
411
+ if single_cls:
412
+ for x in self.labels:
413
+ x[:, 0] = 0
414
+
415
+ n = len(shapes) # number of images
416
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
417
+ nb = bi[-1] + 1 # number of batches
418
+ self.batch = bi # batch index of image
419
+ self.n = n
420
+ self.indices = range(n)
421
+
422
+ # Rectangular Training
423
+ if self.rect:
424
+ # Sort by aspect ratio
425
+ s = self.shapes # wh
426
+ ar = s[:, 1] / s[:, 0] # aspect ratio
427
+ irect = ar.argsort()
428
+ self.img_files = [self.img_files[i] for i in irect]
429
+ self.label_files = [self.label_files[i] for i in irect]
430
+ self.labels = [self.labels[i] for i in irect]
431
+ self.shapes = s[irect] # wh
432
+ ar = ar[irect]
433
+
434
+ # Set training image shapes
435
+ shapes = [[1, 1]] * nb
436
+ for i in range(nb):
437
+ ari = ar[bi == i]
438
+ mini, maxi = ari.min(), ari.max()
439
+ if maxi < 1:
440
+ shapes[i] = [maxi, 1]
441
+ elif mini > 1:
442
+ shapes[i] = [1, 1 / mini]
443
+
444
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
445
+
446
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
447
+ self.imgs = [None] * n
448
+ if cache_images:
449
+ if cache_images == 'disk':
450
+ self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
451
+ self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
452
+ self.im_cache_dir.mkdir(parents=True, exist_ok=True)
453
+ gb = 0 # Gigabytes of cached images
454
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
455
+ results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
456
+ pbar = tqdm(enumerate(results), total=n)
457
+ for i, x in pbar:
458
+ if cache_images == 'disk':
459
+ if not self.img_npy[i].exists():
460
+ np.save(self.img_npy[i].as_posix(), x[0])
461
+ gb += self.img_npy[i].stat().st_size
462
+ else:
463
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = x
464
+ gb += self.imgs[i].nbytes
465
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
466
+ pbar.close()
467
+
468
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
469
+ # Cache dataset labels, check images and read shapes
470
+ x = {} # dict
471
+ nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
472
+ pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
473
+ for i, (im_file, lb_file) in enumerate(pbar):
474
+ try:
475
+ # verify images
476
+ im = Image.open(im_file)
477
+ im.verify() # PIL verify
478
+ shape = exif_size(im) # image size
479
+ segments = [] # instance segments
480
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
481
+ assert im.format.lower() in img_formats, f'invalid image format {im.format}'
482
+
483
+ # verify labels
484
+ if os.path.isfile(lb_file):
485
+ nf += 1 # label found
486
+ with open(lb_file, 'r') as f:
487
+ l = [x.split() for x in f.read().strip().splitlines()]
488
+ if any([len(x) > 8 for x in l]): # is segment
489
+ classes = np.array([x[0] for x in l], dtype=np.float32)
490
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
491
+ l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
492
+ l = np.array(l, dtype=np.float32)
493
+ if len(l):
494
+ assert l.shape[1] == 5, 'labels require 5 columns each'
495
+ assert (l >= 0).all(), 'negative labels'
496
+ assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
497
+ assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
498
+ else:
499
+ ne += 1 # label empty
500
+ l = np.zeros((0, 5), dtype=np.float32)
501
+ else:
502
+ nm += 1 # label missing
503
+ l = np.zeros((0, 5), dtype=np.float32)
504
+ x[im_file] = [l, shape, segments]
505
+ except Exception as e:
506
+ nc += 1
507
+ print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
508
+
509
+ pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
510
+ f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
511
+ pbar.close()
512
+
513
+ if nf == 0:
514
+ print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
515
+
516
+ x['hash'] = get_hash(self.label_files + self.img_files)
517
+ x['results'] = nf, nm, ne, nc, i + 1
518
+ x['version'] = 0.1 # cache version
519
+ torch.save(x, path) # save for next time
520
+ logging.info(f'{prefix}New cache created: {path}')
521
+ return x
522
+
523
+ def __len__(self):
524
+ return len(self.img_files)
525
+
526
+ # def __iter__(self):
527
+ # self.count = -1
528
+ # print('ran dataset iter')
529
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
530
+ # return self
531
+
532
+ def __getitem__(self, index):
533
+ index = self.indices[index] # linear, shuffled, or image_weights
534
+
535
+ hyp = self.hyp
536
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
537
+ if mosaic:
538
+ # Load mosaic
539
+ if random.random() < 0.8:
540
+ img, labels = load_mosaic(self, index)
541
+ else:
542
+ img, labels = load_mosaic9(self, index)
543
+ shapes = None
544
+
545
+ # MixUp https://arxiv.org/pdf/1710.09412.pdf
546
+ if random.random() < hyp['mixup']:
547
+ if random.random() < 0.8:
548
+ img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
549
+ else:
550
+ img2, labels2 = load_mosaic9(self, random.randint(0, len(self.labels) - 1))
551
+ r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
552
+ img = (img * r + img2 * (1 - r)).astype(np.uint8)
553
+ labels = np.concatenate((labels, labels2), 0)
554
+
555
+ else:
556
+ # Load image
557
+ img, (h0, w0), (h, w) = load_image(self, index)
558
+
559
+ # Letterbox
560
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
561
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
562
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
563
+
564
+ labels = self.labels[index].copy()
565
+ if labels.size: # normalized xywh to pixel xyxy format
566
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
567
+
568
+ if self.augment:
569
+ # Augment imagespace
570
+ if not mosaic:
571
+ img, labels = random_perspective(img, labels,
572
+ degrees=hyp['degrees'],
573
+ translate=hyp['translate'],
574
+ scale=hyp['scale'],
575
+ shear=hyp['shear'],
576
+ perspective=hyp['perspective'])
577
+
578
+
579
+ #img, labels = self.albumentations(img, labels)
580
+
581
+ # Augment colorspace
582
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
583
+
584
+ # Apply cutouts
585
+ # if random.random() < 0.9:
586
+ # labels = cutout(img, labels)
587
+
588
+ if random.random() < hyp['paste_in']:
589
+ sample_labels, sample_images, sample_masks = [], [], []
590
+ while len(sample_labels) < 30:
591
+ sample_labels_, sample_images_, sample_masks_ = load_samples(self, random.randint(0, len(self.labels) - 1))
592
+ sample_labels += sample_labels_
593
+ sample_images += sample_images_
594
+ sample_masks += sample_masks_
595
+ #print(len(sample_labels))
596
+ if len(sample_labels) == 0:
597
+ break
598
+ labels = pastein(img, labels, sample_labels, sample_images, sample_masks)
599
+
600
+ nL = len(labels) # number of labels
601
+ if nL:
602
+ labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
603
+ labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
604
+ labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
605
+
606
+ if self.augment:
607
+ # flip up-down
608
+ if random.random() < hyp['flipud']:
609
+ img = np.flipud(img)
610
+ if nL:
611
+ labels[:, 2] = 1 - labels[:, 2]
612
+
613
+ # flip left-right
614
+ if random.random() < hyp['fliplr']:
615
+ img = np.fliplr(img)
616
+ if nL:
617
+ labels[:, 1] = 1 - labels[:, 1]
618
+
619
+ labels_out = torch.zeros((nL, 6))
620
+ if nL:
621
+ labels_out[:, 1:] = torch.from_numpy(labels)
622
+
623
+ # Convert
624
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
625
+ img = np.ascontiguousarray(img)
626
+
627
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
628
+
629
+ @staticmethod
630
+ def collate_fn(batch):
631
+ img, label, path, shapes = zip(*batch) # transposed
632
+ for i, l in enumerate(label):
633
+ l[:, 0] = i # add target image index for build_targets()
634
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
635
+
636
+ @staticmethod
637
+ def collate_fn4(batch):
638
+ img, label, path, shapes = zip(*batch) # transposed
639
+ n = len(shapes) // 4
640
+ img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
641
+
642
+ ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
643
+ wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
644
+ s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
645
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
646
+ i *= 4
647
+ if random.random() < 0.5:
648
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
649
+ 0].type(img[i].type())
650
+ l = label[i]
651
+ else:
652
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
653
+ l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
654
+ img4.append(im)
655
+ label4.append(l)
656
+
657
+ for i, l in enumerate(label4):
658
+ l[:, 0] = i # add target image index for build_targets()
659
+
660
+ return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
661
+
662
+
663
+ # Ancillary functions --------------------------------------------------------------------------------------------------
664
+ def load_image(self, index):
665
+ # loads 1 image from dataset, returns img, original hw, resized hw
666
+ img = self.imgs[index]
667
+ if img is None: # not cached
668
+ path = self.img_files[index]
669
+ img = cv2.imread(path) # BGR
670
+ assert img is not None, 'Image Not Found ' + path
671
+ h0, w0 = img.shape[:2] # orig hw
672
+ r = self.img_size / max(h0, w0) # resize image to img_size
673
+ if r != 1: # always resize down, only resize up if training with augmentation
674
+ interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
675
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
676
+ return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
677
+ else:
678
+ return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
679
+
680
+
681
+ def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
682
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
683
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
684
+ dtype = img.dtype # uint8
685
+
686
+ x = np.arange(0, 256, dtype=np.int16)
687
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
688
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
689
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
690
+
691
+ img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
692
+ cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
693
+
694
+
695
+ def hist_equalize(img, clahe=True, bgr=False):
696
+ # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
697
+ yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
698
+ if clahe:
699
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
700
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
701
+ else:
702
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
703
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
704
+
705
+
706
+ def load_mosaic(self, index):
707
+ # loads images in a 4-mosaic
708
+
709
+ labels4, segments4 = [], []
710
+ s = self.img_size
711
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
712
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
713
+ for i, index in enumerate(indices):
714
+ # Load image
715
+ img, _, (h, w) = load_image(self, index)
716
+
717
+ # place img in img4
718
+ if i == 0: # top left
719
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
720
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
721
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
722
+ elif i == 1: # top right
723
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
724
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
725
+ elif i == 2: # bottom left
726
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
727
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
728
+ elif i == 3: # bottom right
729
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
730
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
731
+
732
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
733
+ padw = x1a - x1b
734
+ padh = y1a - y1b
735
+
736
+ # Labels
737
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
738
+ if labels.size:
739
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
740
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
741
+ labels4.append(labels)
742
+ segments4.extend(segments)
743
+
744
+ # Concat/clip labels
745
+ labels4 = np.concatenate(labels4, 0)
746
+ for x in (labels4[:, 1:], *segments4):
747
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
748
+ # img4, labels4 = replicate(img4, labels4) # replicate
749
+
750
+ # Augment
751
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
752
+ #sample_segments(img4, labels4, segments4, probability=self.hyp['copy_paste'])
753
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])
754
+ img4, labels4 = random_perspective(img4, labels4, segments4,
755
+ degrees=self.hyp['degrees'],
756
+ translate=self.hyp['translate'],
757
+ scale=self.hyp['scale'],
758
+ shear=self.hyp['shear'],
759
+ perspective=self.hyp['perspective'],
760
+ border=self.mosaic_border) # border to remove
761
+
762
+ return img4, labels4
763
+
764
+
765
+ def load_mosaic9(self, index):
766
+ # loads images in a 9-mosaic
767
+
768
+ labels9, segments9 = [], []
769
+ s = self.img_size
770
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
771
+ for i, index in enumerate(indices):
772
+ # Load image
773
+ img, _, (h, w) = load_image(self, index)
774
+
775
+ # place img in img9
776
+ if i == 0: # center
777
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
778
+ h0, w0 = h, w
779
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
780
+ elif i == 1: # top
781
+ c = s, s - h, s + w, s
782
+ elif i == 2: # top right
783
+ c = s + wp, s - h, s + wp + w, s
784
+ elif i == 3: # right
785
+ c = s + w0, s, s + w0 + w, s + h
786
+ elif i == 4: # bottom right
787
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
788
+ elif i == 5: # bottom
789
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
790
+ elif i == 6: # bottom left
791
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
792
+ elif i == 7: # left
793
+ c = s - w, s + h0 - h, s, s + h0
794
+ elif i == 8: # top left
795
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
796
+
797
+ padx, pady = c[:2]
798
+ x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
799
+
800
+ # Labels
801
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
802
+ if labels.size:
803
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
804
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
805
+ labels9.append(labels)
806
+ segments9.extend(segments)
807
+
808
+ # Image
809
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
810
+ hp, wp = h, w # height, width previous
811
+
812
+ # Offset
813
+ yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
814
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
815
+
816
+ # Concat/clip labels
817
+ labels9 = np.concatenate(labels9, 0)
818
+ labels9[:, [1, 3]] -= xc
819
+ labels9[:, [2, 4]] -= yc
820
+ c = np.array([xc, yc]) # centers
821
+ segments9 = [x - c for x in segments9]
822
+
823
+ for x in (labels9[:, 1:], *segments9):
824
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
825
+ # img9, labels9 = replicate(img9, labels9) # replicate
826
+
827
+ # Augment
828
+ #img9, labels9, segments9 = remove_background(img9, labels9, segments9)
829
+ img9, labels9, segments9 = copy_paste(img9, labels9, segments9, probability=self.hyp['copy_paste'])
830
+ img9, labels9 = random_perspective(img9, labels9, segments9,
831
+ degrees=self.hyp['degrees'],
832
+ translate=self.hyp['translate'],
833
+ scale=self.hyp['scale'],
834
+ shear=self.hyp['shear'],
835
+ perspective=self.hyp['perspective'],
836
+ border=self.mosaic_border) # border to remove
837
+
838
+ return img9, labels9
839
+
840
+
841
+ def load_samples(self, index):
842
+ # loads images in a 4-mosaic
843
+
844
+ labels4, segments4 = [], []
845
+ s = self.img_size
846
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
847
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
848
+ for i, index in enumerate(indices):
849
+ # Load image
850
+ img, _, (h, w) = load_image(self, index)
851
+
852
+ # place img in img4
853
+ if i == 0: # top left
854
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
855
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
856
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
857
+ elif i == 1: # top right
858
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
859
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
860
+ elif i == 2: # bottom left
861
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
862
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
863
+ elif i == 3: # bottom right
864
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
865
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
866
+
867
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
868
+ padw = x1a - x1b
869
+ padh = y1a - y1b
870
+
871
+ # Labels
872
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
873
+ if labels.size:
874
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
875
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
876
+ labels4.append(labels)
877
+ segments4.extend(segments)
878
+
879
+ # Concat/clip labels
880
+ labels4 = np.concatenate(labels4, 0)
881
+ for x in (labels4[:, 1:], *segments4):
882
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
883
+ # img4, labels4 = replicate(img4, labels4) # replicate
884
+
885
+ # Augment
886
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
887
+ sample_labels, sample_images, sample_masks = sample_segments(img4, labels4, segments4, probability=0.5)
888
+
889
+ return sample_labels, sample_images, sample_masks
890
+
891
+
892
+ def copy_paste(img, labels, segments, probability=0.5):
893
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
894
+ n = len(segments)
895
+ if probability and n:
896
+ h, w, c = img.shape # height, width, channels
897
+ im_new = np.zeros(img.shape, np.uint8)
898
+ for j in random.sample(range(n), k=round(probability * n)):
899
+ l, s = labels[j], segments[j]
900
+ box = w - l[3], l[2], w - l[1], l[4]
901
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
902
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
903
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
904
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
905
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
906
+
907
+ result = cv2.bitwise_and(src1=img, src2=im_new)
908
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
909
+ i = result > 0 # pixels to replace
910
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
911
+ img[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
912
+
913
+ return img, labels, segments
914
+
915
+
916
+ def remove_background(img, labels, segments):
917
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
918
+ n = len(segments)
919
+ h, w, c = img.shape # height, width, channels
920
+ im_new = np.zeros(img.shape, np.uint8)
921
+ img_new = np.ones(img.shape, np.uint8) * 114
922
+ for j in range(n):
923
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
924
+
925
+ result = cv2.bitwise_and(src1=img, src2=im_new)
926
+
927
+ i = result > 0 # pixels to replace
928
+ img_new[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
929
+
930
+ return img_new, labels, segments
931
+
932
+
933
+ def sample_segments(img, labels, segments, probability=0.5):
934
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
935
+ n = len(segments)
936
+ sample_labels = []
937
+ sample_images = []
938
+ sample_masks = []
939
+ if probability and n:
940
+ h, w, c = img.shape # height, width, channels
941
+ for j in random.sample(range(n), k=round(probability * n)):
942
+ l, s = labels[j], segments[j]
943
+ box = l[1].astype(int).clip(0,w-1), l[2].astype(int).clip(0,h-1), l[3].astype(int).clip(0,w-1), l[4].astype(int).clip(0,h-1)
944
+
945
+ #print(box)
946
+ if (box[2] <= box[0]) or (box[3] <= box[1]):
947
+ continue
948
+
949
+ sample_labels.append(l[0])
950
+
951
+ mask = np.zeros(img.shape, np.uint8)
952
+
953
+ cv2.drawContours(mask, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
954
+ sample_masks.append(mask[box[1]:box[3],box[0]:box[2],:])
955
+
956
+ result = cv2.bitwise_and(src1=img, src2=mask)
957
+ i = result > 0 # pixels to replace
958
+ mask[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
959
+ #print(box)
960
+ sample_images.append(mask[box[1]:box[3],box[0]:box[2],:])
961
+
962
+ return sample_labels, sample_images, sample_masks
963
+
964
+
965
+ def replicate(img, labels):
966
+ # Replicate labels
967
+ h, w = img.shape[:2]
968
+ boxes = labels[:, 1:].astype(int)
969
+ x1, y1, x2, y2 = boxes.T
970
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
971
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
972
+ x1b, y1b, x2b, y2b = boxes[i]
973
+ bh, bw = y2b - y1b, x2b - x1b
974
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
975
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
976
+ img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
977
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
978
+
979
+ return img, labels
980
+
981
+
982
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
983
+ # Resize and pad image while meeting stride-multiple constraints
984
+ shape = img.shape[:2] # current shape [height, width]
985
+ if isinstance(new_shape, int):
986
+ new_shape = (new_shape, new_shape)
987
+
988
+ # Scale ratio (new / old)
989
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
990
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
991
+ r = min(r, 1.0)
992
+
993
+ # Compute padding
994
+ ratio = r, r # width, height ratios
995
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
996
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
997
+ if auto: # minimum rectangle
998
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
999
+ elif scaleFill: # stretch
1000
+ dw, dh = 0.0, 0.0
1001
+ new_unpad = (new_shape[1], new_shape[0])
1002
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
1003
+
1004
+ dw /= 2 # divide padding into 2 sides
1005
+ dh /= 2
1006
+
1007
+ if shape[::-1] != new_unpad: # resize
1008
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
1009
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
1010
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
1011
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
1012
+ return img, ratio, (dw, dh)
1013
+
1014
+
1015
+ def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
1016
+ border=(0, 0)):
1017
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
1018
+ # targets = [cls, xyxy]
1019
+
1020
+ height = img.shape[0] + border[0] * 2 # shape(h,w,c)
1021
+ width = img.shape[1] + border[1] * 2
1022
+
1023
+ # Center
1024
+ C = np.eye(3)
1025
+ C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
1026
+ C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
1027
+
1028
+ # Perspective
1029
+ P = np.eye(3)
1030
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
1031
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
1032
+
1033
+ # Rotation and Scale
1034
+ R = np.eye(3)
1035
+ a = random.uniform(-degrees, degrees)
1036
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
1037
+ s = random.uniform(1 - scale, 1.1 + scale)
1038
+ # s = 2 ** random.uniform(-scale, scale)
1039
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
1040
+
1041
+ # Shear
1042
+ S = np.eye(3)
1043
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
1044
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
1045
+
1046
+ # Translation
1047
+ T = np.eye(3)
1048
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
1049
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
1050
+
1051
+ # Combined rotation matrix
1052
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
1053
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
1054
+ if perspective:
1055
+ img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
1056
+ else: # affine
1057
+ img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
1058
+
1059
+ # Visualize
1060
+ # import matplotlib.pyplot as plt
1061
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
1062
+ # ax[0].imshow(img[:, :, ::-1]) # base
1063
+ # ax[1].imshow(img2[:, :, ::-1]) # warped
1064
+
1065
+ # Transform label coordinates
1066
+ n = len(targets)
1067
+ if n:
1068
+ use_segments = any(x.any() for x in segments)
1069
+ new = np.zeros((n, 4))
1070
+ if use_segments: # warp segments
1071
+ segments = resample_segments(segments) # upsample
1072
+ for i, segment in enumerate(segments):
1073
+ xy = np.ones((len(segment), 3))
1074
+ xy[:, :2] = segment
1075
+ xy = xy @ M.T # transform
1076
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
1077
+
1078
+ # clip
1079
+ new[i] = segment2box(xy, width, height)
1080
+
1081
+ else: # warp boxes
1082
+ xy = np.ones((n * 4, 3))
1083
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
1084
+ xy = xy @ M.T # transform
1085
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
1086
+
1087
+ # create new boxes
1088
+ x = xy[:, [0, 2, 4, 6]]
1089
+ y = xy[:, [1, 3, 5, 7]]
1090
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
1091
+
1092
+ # clip
1093
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
1094
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
1095
+
1096
+ # filter candidates
1097
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
1098
+ targets = targets[i]
1099
+ targets[:, 1:5] = new[i]
1100
+
1101
+ return img, targets
1102
+
1103
+
1104
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
1105
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
1106
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
1107
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
1108
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
1109
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
1110
+
1111
+
1112
+ def bbox_ioa(box1, box2):
1113
+ # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
1114
+ box2 = box2.transpose()
1115
+
1116
+ # Get the coordinates of bounding boxes
1117
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
1118
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
1119
+
1120
+ # Intersection area
1121
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
1122
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
1123
+
1124
+ # box2 area
1125
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
1126
+
1127
+ # Intersection over box2 area
1128
+ return inter_area / box2_area
1129
+
1130
+
1131
+ def cutout(image, labels):
1132
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1133
+ h, w = image.shape[:2]
1134
+
1135
+ # create random masks
1136
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
1137
+ for s in scales:
1138
+ mask_h = random.randint(1, int(h * s))
1139
+ mask_w = random.randint(1, int(w * s))
1140
+
1141
+ # box
1142
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1143
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1144
+ xmax = min(w, xmin + mask_w)
1145
+ ymax = min(h, ymin + mask_h)
1146
+
1147
+ # apply random color mask
1148
+ image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
1149
+
1150
+ # return unobscured labels
1151
+ if len(labels) and s > 0.03:
1152
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1153
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1154
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
1155
+
1156
+ return labels
1157
+
1158
+
1159
+ def pastein(image, labels, sample_labels, sample_images, sample_masks):
1160
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1161
+ h, w = image.shape[:2]
1162
+
1163
+ # create random masks
1164
+ scales = [0.75] * 2 + [0.5] * 4 + [0.25] * 4 + [0.125] * 4 + [0.0625] * 6 # image size fraction
1165
+ for s in scales:
1166
+ if random.random() < 0.2:
1167
+ continue
1168
+ mask_h = random.randint(1, int(h * s))
1169
+ mask_w = random.randint(1, int(w * s))
1170
+
1171
+ # box
1172
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1173
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1174
+ xmax = min(w, xmin + mask_w)
1175
+ ymax = min(h, ymin + mask_h)
1176
+
1177
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1178
+ if len(labels):
1179
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1180
+ else:
1181
+ ioa = np.zeros(1)
1182
+
1183
+ if (ioa < 0.30).all() and len(sample_labels) and (xmax > xmin+20) and (ymax > ymin+20): # allow 30% obscuration of existing labels
1184
+ sel_ind = random.randint(0, len(sample_labels)-1)
1185
+ #print(len(sample_labels))
1186
+ #print(sel_ind)
1187
+ #print((xmax-xmin, ymax-ymin))
1188
+ #print(image[ymin:ymax, xmin:xmax].shape)
1189
+ #print([[sample_labels[sel_ind], *box]])
1190
+ #print(labels.shape)
1191
+ hs, ws, cs = sample_images[sel_ind].shape
1192
+ r_scale = min((ymax-ymin)/hs, (xmax-xmin)/ws)
1193
+ r_w = int(ws*r_scale)
1194
+ r_h = int(hs*r_scale)
1195
+
1196
+ if (r_w > 10) and (r_h > 10):
1197
+ r_mask = cv2.resize(sample_masks[sel_ind], (r_w, r_h))
1198
+ r_image = cv2.resize(sample_images[sel_ind], (r_w, r_h))
1199
+ temp_crop = image[ymin:ymin+r_h, xmin:xmin+r_w]
1200
+ m_ind = r_mask > 0
1201
+ if m_ind.astype(np.int).sum() > 60:
1202
+ temp_crop[m_ind] = r_image[m_ind]
1203
+ #print(sample_labels[sel_ind])
1204
+ #print(sample_images[sel_ind].shape)
1205
+ #print(temp_crop.shape)
1206
+ box = np.array([xmin, ymin, xmin+r_w, ymin+r_h], dtype=np.float32)
1207
+ if len(labels):
1208
+ labels = np.concatenate((labels, [[sample_labels[sel_ind], *box]]), 0)
1209
+ else:
1210
+ labels = np.array([[sample_labels[sel_ind], *box]])
1211
+
1212
+ image[ymin:ymin+r_h, xmin:xmin+r_w] = temp_crop
1213
+
1214
+ return labels
1215
+
1216
+ class Albumentations:
1217
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
1218
+ def __init__(self):
1219
+ self.transform = None
1220
+ import albumentations as A
1221
+
1222
+ self.transform = A.Compose([
1223
+ A.CLAHE(p=0.01),
1224
+ A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.01),
1225
+ A.RandomGamma(gamma_limit=[80, 120], p=0.01),
1226
+ A.Blur(p=0.01),
1227
+ A.MedianBlur(p=0.01),
1228
+ A.ToGray(p=0.01),
1229
+ A.ImageCompression(quality_lower=75, p=0.01),],
1230
+ bbox_params=A.BboxParams(format='pascal_voc', label_fields=['class_labels']))
1231
+
1232
+ #logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
1233
+
1234
+ def __call__(self, im, labels, p=1.0):
1235
+ if self.transform and random.random() < p:
1236
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
1237
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
1238
+ return im, labels
1239
+
1240
+
1241
+ def create_folder(path='./new'):
1242
+ # Create folder
1243
+ if os.path.exists(path):
1244
+ shutil.rmtree(path) # delete output folder
1245
+ os.makedirs(path) # make new output folder
1246
+
1247
+
1248
+ def flatten_recursive(path='../coco'):
1249
+ # Flatten a recursive directory by bringing all files to top level
1250
+ new_path = Path(path + '_flat')
1251
+ create_folder(new_path)
1252
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
1253
+ shutil.copyfile(file, new_path / Path(file).name)
1254
+
1255
+
1256
+ def extract_boxes(path='../coco/'): # from utils.datasets import *; extract_boxes('../coco128')
1257
+ # Convert detection dataset into classification dataset, with one directory per class
1258
+
1259
+ path = Path(path) # images dir
1260
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
1261
+ files = list(path.rglob('*.*'))
1262
+ n = len(files) # number of files
1263
+ for im_file in tqdm(files, total=n):
1264
+ if im_file.suffix[1:] in img_formats:
1265
+ # image
1266
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
1267
+ h, w = im.shape[:2]
1268
+
1269
+ # labels
1270
+ lb_file = Path(img2label_paths([str(im_file)])[0])
1271
+ if Path(lb_file).exists():
1272
+ with open(lb_file, 'r') as f:
1273
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
1274
+
1275
+ for j, x in enumerate(lb):
1276
+ c = int(x[0]) # class
1277
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
1278
+ if not f.parent.is_dir():
1279
+ f.parent.mkdir(parents=True)
1280
+
1281
+ b = x[1:] * [w, h, w, h] # box
1282
+ # b[2:] = b[2:].max() # rectangle to square
1283
+ b[2:] = b[2:] * 1.2 + 3 # pad
1284
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
1285
+
1286
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
1287
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
1288
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
1289
+
1290
+
1291
+ def autosplit(path='../coco', weights=(0.9, 0.1, 0.0), annotated_only=False):
1292
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
1293
+ Usage: from utils.datasets import *; autosplit('../coco')
1294
+ Arguments
1295
+ path: Path to images directory
1296
+ weights: Train, val, test weights (list)
1297
+ annotated_only: Only use images with an annotated txt file
1298
+ """
1299
+ path = Path(path) # images dir
1300
+ files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
1301
+ n = len(files) # number of files
1302
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
1303
+
1304
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
1305
+ [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing
1306
+
1307
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
1308
+ for i, img in tqdm(zip(indices, files), total=n):
1309
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
1310
+ with open(path / txt[i], 'a') as f:
1311
+ f.write(str(img) + '\n') # add image to txt file
1312
+
1313
+
1314
+ def load_segmentations(self, index):
1315
+ key = '/work/handsomejw66/coco17/' + self.img_files[index]
1316
+ #print(key)
1317
+ # /work/handsomejw66/coco17/
1318
+ return self.segs[key]
1319