|
|
|
""" |
|
Dataloaders and dataset utils |
|
""" |
|
|
|
import glob |
|
import hashlib |
|
import json |
|
import math |
|
import os |
|
import random |
|
import shutil |
|
import time |
|
from itertools import repeat |
|
from multiprocessing.pool import Pool, ThreadPool |
|
from pathlib import Path |
|
from threading import Thread |
|
from zipfile import ZipFile |
|
|
|
import cv2 |
|
import numpy as np |
|
import torch |
|
import torch.nn.functional as F |
|
import yaml |
|
from PIL import ExifTags, Image, ImageOps |
|
from tqdm import tqdm |
|
|
|
from .augmentations import letterbox |
|
from .general import (xyn2xy, xywh2xyxy, xywhn2xyxy) |
|
|
|
|
|
HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' |
|
IMG_FORMATS = ['bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp'] |
|
VID_FORMATS = ['asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'wmv'] |
|
|
|
|
|
for orientation in ExifTags.TAGS.keys(): |
|
if ExifTags.TAGS[orientation] == 'Orientation': |
|
break |
|
|
|
|
|
def get_hash(paths): |
|
|
|
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) |
|
h = hashlib.md5(str(size).encode()) |
|
h.update(''.join(paths).encode()) |
|
return h.hexdigest() |
|
|
|
|
|
def exif_size(img): |
|
|
|
s = img.size |
|
try: |
|
rotation = dict(img._getexif().items())[orientation] |
|
if rotation == 6: |
|
s = (s[1], s[0]) |
|
elif rotation == 8: |
|
s = (s[1], s[0]) |
|
except: |
|
pass |
|
|
|
return s |
|
|
|
|
|
def exif_transpose(image): |
|
""" |
|
Transpose a PIL image accordingly if it has an EXIF Orientation tag. |
|
Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose() |
|
|
|
:param image: The image to transpose. |
|
:return: An image. |
|
""" |
|
exif = image.getexif() |
|
orientation = exif.get(0x0112, 1) |
|
if orientation > 1: |
|
method = {2: Image.FLIP_LEFT_RIGHT, |
|
3: Image.ROTATE_180, |
|
4: Image.FLIP_TOP_BOTTOM, |
|
5: Image.TRANSPOSE, |
|
6: Image.ROTATE_270, |
|
7: Image.TRANSVERSE, |
|
8: Image.ROTATE_90, |
|
}.get(orientation) |
|
if method is not None: |
|
image = image.transpose(method) |
|
del exif[0x0112] |
|
image.info["exif"] = exif.tobytes() |
|
return image |
|
|
|
class LoadImages: |
|
|
|
def __init__(self, path, img_size=640, stride=32, auto=True): |
|
p = str(Path(path).resolve()) |
|
if '*' in p: |
|
files = sorted(glob.glob(p, recursive=True)) |
|
elif os.path.isdir(p): |
|
files = sorted(glob.glob(os.path.join(p, '*.*'))) |
|
elif os.path.isfile(p): |
|
files = [p] |
|
else: |
|
raise Exception(f'ERROR: {p} does not exist') |
|
|
|
images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] |
|
videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] |
|
ni, nv = len(images), len(videos) |
|
|
|
self.img_size = img_size |
|
self.stride = stride |
|
self.files = images + videos |
|
self.nf = ni + nv |
|
self.video_flag = [False] * ni + [True] * nv |
|
self.mode = 'image' |
|
self.auto = auto |
|
if any(videos): |
|
self.new_video(videos[0]) |
|
else: |
|
self.cap = None |
|
assert self.nf > 0, f'No images or videos found in {p}. ' \ |
|
f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' |
|
|
|
def __iter__(self): |
|
self.count = 0 |
|
return self |
|
|
|
def __next__(self): |
|
if self.count == self.nf: |
|
raise StopIteration |
|
path = self.files[self.count] |
|
|
|
if self.video_flag[self.count]: |
|
|
|
self.mode = 'video' |
|
ret_val, img0 = self.cap.read() |
|
while not ret_val: |
|
self.count += 1 |
|
self.cap.release() |
|
if self.count == self.nf: |
|
raise StopIteration |
|
else: |
|
path = self.files[self.count] |
|
self.new_video(path) |
|
ret_val, img0 = self.cap.read() |
|
|
|
self.frame += 1 |
|
s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ' |
|
|
|
else: |
|
|
|
self.count += 1 |
|
img0 = cv2.imread(path) |
|
assert img0 is not None, f'Image Not Found {path}' |
|
s = f'image {self.count}/{self.nf} {path}: ' |
|
|
|
|
|
img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] |
|
|
|
|
|
img = img.transpose((2, 0, 1))[::-1] |
|
img = np.ascontiguousarray(img) |
|
|
|
return path, img, img0, self.cap, s |
|
|
|
def new_video(self, path): |
|
self.frame = 0 |
|
self.cap = cv2.VideoCapture(path) |
|
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
|
|
|
def __len__(self): |
|
return self.nf |
|
|
|
|
|
def img2label_paths(img_paths): |
|
|
|
sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep |
|
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] |
|
|
|
|
|
|
|
def load_image(self, i): |
|
|
|
im = self.imgs[i] |
|
if im is None: |
|
npy = self.img_npy[i] |
|
if npy and npy.exists(): |
|
im = np.load(npy) |
|
else: |
|
path = self.img_files[i] |
|
im = cv2.imread(path) |
|
assert im is not None, f'Image Not Found {path}' |
|
h0, w0 = im.shape[:2] |
|
r = self.img_size / max(h0, w0) |
|
if r != 1: |
|
im = cv2.resize(im, (int(w0 * r), int(h0 * r)), |
|
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR) |
|
return im, (h0, w0), im.shape[:2] |
|
else: |
|
return self.imgs[i], self.img_hw0[i], self.img_hw[i] |
|
|
|
|
|
def load_mosaic(self, index): |
|
|
|
labels4, segments4 = [], [] |
|
s = self.img_size |
|
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) |
|
indices = [index] + random.choices(self.indices, k=3) |
|
random.shuffle(indices) |
|
for i, index in enumerate(indices): |
|
|
|
img, _, (h, w) = load_image(self, index) |
|
|
|
|
|
if i == 0: |
|
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) |
|
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc |
|
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h |
|
elif i == 1: |
|
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc |
|
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h |
|
elif i == 2: |
|
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) |
|
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) |
|
elif i == 3: |
|
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) |
|
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) |
|
|
|
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] |
|
padw = x1a - x1b |
|
padh = y1a - y1b |
|
|
|
|
|
labels, segments = self.labels[index].copy(), self.segments[index].copy() |
|
if labels.size: |
|
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) |
|
segments = [xyn2xy(x, w, h, padw, padh) for x in segments] |
|
labels4.append(labels) |
|
segments4.extend(segments) |
|
|
|
|
|
labels4 = np.concatenate(labels4, 0) |
|
for x in (labels4[:, 1:], *segments4): |
|
np.clip(x, 0, 2 * s, out=x) |
|
|
|
|
|
return img4, labels4 |
|
|
|
|
|
def load_mosaic9(self, index): |
|
|
|
labels9, segments9 = [], [] |
|
s = self.img_size |
|
indices = [index] + random.choices(self.indices, k=8) |
|
random.shuffle(indices) |
|
for i, index in enumerate(indices): |
|
|
|
img, _, (h, w) = load_image(self, index) |
|
|
|
|
|
if i == 0: |
|
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) |
|
h0, w0 = h, w |
|
c = s, s, s + w, s + h |
|
elif i == 1: |
|
c = s, s - h, s + w, s |
|
elif i == 2: |
|
c = s + wp, s - h, s + wp + w, s |
|
elif i == 3: |
|
c = s + w0, s, s + w0 + w, s + h |
|
elif i == 4: |
|
c = s + w0, s + hp, s + w0 + w, s + hp + h |
|
elif i == 5: |
|
c = s + w0 - w, s + h0, s + w0, s + h0 + h |
|
elif i == 6: |
|
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h |
|
elif i == 7: |
|
c = s - w, s + h0 - h, s, s + h0 |
|
elif i == 8: |
|
c = s - w, s + h0 - hp - h, s, s + h0 - hp |
|
|
|
padx, pady = c[:2] |
|
x1, y1, x2, y2 = (max(x, 0) for x in c) |
|
|
|
|
|
labels, segments = self.labels[index].copy(), self.segments[index].copy() |
|
if labels.size: |
|
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) |
|
segments = [xyn2xy(x, w, h, padx, pady) for x in segments] |
|
labels9.append(labels) |
|
segments9.extend(segments) |
|
|
|
|
|
img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] |
|
hp, wp = h, w |
|
|
|
|
|
yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) |
|
img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] |
|
|
|
|
|
labels9 = np.concatenate(labels9, 0) |
|
labels9[:, [1, 3]] -= xc |
|
labels9[:, [2, 4]] -= yc |
|
c = np.array([xc, yc]) |
|
segments9 = [x - c for x in segments9] |
|
|
|
for x in (labels9[:, 1:], *segments9): |
|
np.clip(x, 0, 2 * s, out=x) |
|
|
|
|
|
|
|
return img9, labels9 |
|
|
|
|
|
def create_folder(path='./new'): |
|
|
|
if os.path.exists(path): |
|
shutil.rmtree(path) |
|
os.makedirs(path) |
|
|
|
|
|
def flatten_recursive(path='../datasets/coco128'): |
|
|
|
new_path = Path(path + '_flat') |
|
create_folder(new_path) |
|
for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): |
|
shutil.copyfile(file, new_path / Path(file).name) |
|
|
|
|
|
def extract_boxes(path='../datasets/coco128'): |
|
|
|
path = Path(path) |
|
shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None |
|
files = list(path.rglob('*.*')) |
|
n = len(files) |
|
for im_file in tqdm(files, total=n): |
|
if im_file.suffix[1:] in IMG_FORMATS: |
|
|
|
im = cv2.imread(str(im_file))[..., ::-1] |
|
h, w = im.shape[:2] |
|
|
|
|
|
lb_file = Path(img2label_paths([str(im_file)])[0]) |
|
if Path(lb_file).exists(): |
|
with open(lb_file) as f: |
|
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) |
|
|
|
for j, x in enumerate(lb): |
|
c = int(x[0]) |
|
f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' |
|
if not f.parent.is_dir(): |
|
f.parent.mkdir(parents=True) |
|
|
|
b = x[1:] * [w, h, w, h] |
|
|
|
b[2:] = b[2:] * 1.2 + 3 |
|
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) |
|
|
|
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) |
|
b[[1, 3]] = np.clip(b[[1, 3]], 0, h) |
|
assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' |
|
|
|
|
|
def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): |
|
""" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files |
|
Usage: from utils.datasets import *; autosplit() |
|
Arguments |
|
path: Path to images directory |
|
weights: Train, val, test weights (list, tuple) |
|
annotated_only: Only use images with an annotated txt file |
|
""" |
|
path = Path(path) |
|
files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) |
|
n = len(files) |
|
random.seed(0) |
|
indices = random.choices([0, 1, 2], weights=weights, k=n) |
|
|
|
txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] |
|
[(path.parent / x).unlink(missing_ok=True) for x in txt] |
|
|
|
print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) |
|
for i, img in tqdm(zip(indices, files), total=n): |
|
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): |
|
with open(path.parent / txt[i], 'a') as f: |
|
f.write('./' + img.relative_to(path.parent).as_posix() + '\n') |
|
|
|
|