diff --git a/utils/datasets.py b/utils/datasets.py index 3f88635d..56690ae0 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -357,10 +357,15 @@ class LoadImagesAndLabels(Dataset): # for training/testing f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name) if not os.path.exists(Path(f).parent): os.makedirs(Path(f).parent) # make new output folder - box = xywh2xyxy(x[1:].reshape(-1, 4) * np.array([1, 1, 1.5, 1.5])).ravel() - b = np.clip(box, 0, 1) # clip boxes outside of image - ret_val = cv2.imwrite(f, img[int(b[1] * h):int(b[3] * h), int(b[0] * w):int(b[2] * w)]) - assert ret_val, 'Failure extracting classifier boxes' + + b = x[1:] * np.array([w, h, w, h]) # box + b[2:] = b[2:].max() # rectangle to square + b[2:] = b[2:] * 1.3 + 30 # pad + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) + + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image + b[[1, 3]] = np.clip(b[[1, 3]], 0, h) + assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes' else: ne += 1 # file empty diff --git a/utils/utils.py b/utils/utils.py index 856893ac..322ce246 100755 --- a/utils/utils.py +++ b/utils/utils.py @@ -624,6 +624,29 @@ def select_best_evolve(path='evolve*.txt'): # from utils.utils import *; select print(file, x[fitness(x).argmax()]) +def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random() + # crops images into random squares up to scale fraction + # WARNING: overwrites images! + for file in tqdm(sorted(glob.glob('%s/*.*' % path))): + img = cv2.imread(file) # BGR + if img is not None: + h, w = img.shape[:2] + + # create random mask + a = 30 # minimum size (pixels) + mask_h = random.randint(a, int(max(a, h * scale))) # mask height + mask_w = mask_h # mask width + + # box + xmin = max(0, random.randint(0, w) - mask_w // 2) + ymin = max(0, random.randint(0, h) - mask_h // 2) + xmax = min(w, xmin + mask_w) + ymax = min(h, ymin + mask_h) + + # apply random color mask + cv2.imwrite(file, img[ymin:ymax, xmin:xmax]) + + def coco_single_class_labels(path='../coco/labels/train2014/', label_class=43): # Makes single-class coco datasets. from utils.utils import *; coco_single_class_labels() if os.path.exists('new/'):