File size: 19,563 Bytes
ae29340 | 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 | from pathlib import Path
import numpy as np
import cv2
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.compat.v1 as tf1
from torch.utils.data import Dataset
import random
import torch.nn.functional as F
class ImageHelper:
COLOR_TRANSFORMATIONS = [
"saturation",
"contrast",
"brightness",
]
def __init__(self, img_path, label_path, output_size, **kwargs):
self.img_path = img_path
self.label_path = label_path
self.output_size = output_size
self.kwargs = kwargs
# Stereo
self.to_stereo = False
if "to_stereo" in kwargs.keys() and kwargs["to_stereo"]:
self.to_stereo = True
# Flip
self.flip = False
if "flip" in kwargs.keys() and kwargs["flip"]:
self.flip = True
# Color transformations
self.color_transformations = []
for k, v in self.kwargs.items():
if k in self.COLOR_TRANSFORMATIONS and v:
self.color_transformations.append(k)
def get(self):
# Load
img = cv2.imread(str(self.img_path))
label = cv2.imread(str(self.label_path))
# Size checking
assert img.shape == label.shape
# Flip
if self.flip:
img, label = self.apply_transformation("flip", img, label)
# Color transformations
for color_tr in self.color_transformations:
img, label = self.apply_transformation(color_tr, img, label)
# Numpy3333
if type(img) != np.ndarray:
img = np.array(img)
if type(label) != np.ndarray:
label = np.array(label)
# To stereo
if self.to_stereo:
img = np.concatenate((img, img), axis=1)
label = np.concatenate((label, label), axis=1)
# Size
img = cv2.resize(img, self.output_size[::-1])
label = cv2.resize(
label, self.output_size[::-1], interpolation=cv2.INTER_NEAREST
)
label = label[:, :, 0]
return img, label
@classmethod
def apply_transformation(cls, transformation, img, label):
if transformation == "flip":
return cls.tensor_to_numpy(
tf.image.flip_left_right(img)
), cls.tensor_to_numpy(tf.image.flip_left_right(label))
elif transformation == "saturation":
return cls.tensor_to_numpy(tf.image.random_saturation(img, 0.5, 1.5)), label
elif transformation == "contrast":
return cls.tensor_to_numpy(tf.image.random_contrast(img, 0.5, 1.5)), label
elif transformation == "brightness":
return cls.tensor_to_numpy(tf.image.random_brightness(img, 0.3)), label
elif transformation == "rotate":
raise ValueError("This transformation is not supported yet")
elif transformation == "directed_crop":
raise ValueError("This transformation is not supported")
@staticmethod
def tensor_to_numpy(tensor):
if tf.executing_eagerly():
a = tensor.numpy()
else:
raise NotImplementedError(
"Please adapt the Data Generator to work when not executing eagerly"
)
return a
class DataGenerator(keras.utils.Sequence):
def __init__(
self,
images_path,
labels_path,
n_classes,
batch_size=32,
output_size=(480, 640),
to_stereo=False,
flip=False,
saturation=False,
contrast=False,
brightness=False,
class_mappings=None,
):
self.images_path = Path(images_path)
self.labels_path = Path(labels_path)
self.n_classes = n_classes
self.batch_size = batch_size
self.output_size = output_size
self.to_stereo = to_stereo
self.class_mappings = class_mappings
# Check image and labels dir
img_paths = sorted(list(self.images_path.iterdir()))
def has_label(img_filename):
return (self.labels_path / f"{img_filename.stem}.png").exists()
if not all(map(has_label, img_paths)):
raise FileNotFoundError("Check every image has a label")
# Obtain transformations
transformations = []
if flip:
transformations.append("flip")
if saturation:
transformations.append("saturation")
if contrast:
transformations.append("contrast")
if brightness:
transformations.append("brightness")
# Prepare augmentation
elements = []
for image_path in img_paths:
label_path = self.labels_path / f"{image_path.stem}.png"
elements.append(
ImageHelper(
image_path,
label_path,
self.output_size,
to_stereo=self.to_stereo,
)
)
for tr in transformations:
elements.append(
ImageHelper(
image_path,
label_path,
self.output_size,
to_stereo=self.to_stereo,
**{tr: True},
)
)
self.elements = elements
# Shuffle
np.random.shuffle(self.elements)
def __getitem__(self, idx):
batch_elements = self.elements[
idx * self.batch_size : (idx + 1) * self.batch_size
]
batch_elements_tuple = list(map(lambda x: x.get(), batch_elements))
X, y = zip(*batch_elements_tuple)
X, y = np.array(X), np.array(y)
y_onehot = np.zeros(y.shape + (self.n_classes,))
for i in np.unique(y):
i = int(i)
idx_for_this_class = np.where(y == i)
if self.class_mappings:
y_onehot[
idx_for_this_class
+ (
np.ones(len(idx_for_this_class[0]), dtype=int)
* self.class_mappings[i],
)
] = 1
else:
y_onehot[
idx_for_this_class
+ (np.ones(len(idx_for_this_class[0]), dtype=int) * i,)
] = 1
final_X, final_y = X.astype(np.float64) / 255, y_onehot.astype(bool)
# assert final_X.shape[:-1] == final_y.shape[:-1]
return final_X, final_y
def get_item_name(self, idx):
return self.elements[idx].img_path.stem
def __len__(self):
try:
return np.int(len(self.elements) / self.batch_size)
except AttributeError:
return int(len(self.elements) / self.batch_size)
def on_epoch_end(self):
np.random.shuffle(self.elements)
@classmethod
def create_generators(
cls,
dataset_dir,
n_classes,
training_batch_size=32,
validation_batch_size=8,
output_size=(480, 640),
to_stereo=False,
transformations=tuple(),
class_mappings=None,
):
"""
Utily method to create both generators
Args:
dataset_dir: path of the dataset, must have training and val dirs
training_batch_size: batch size of the training generator
output_size: shape of the generated images
transformations: for data agumentations
to_stereo: whether the image and label must be converted to stereo
class_mappings: dict containing a mapping for each class
Returns: a tuple with the training and val genearators
"""
dataset_dir = Path(dataset_dir)
training_generator = cls(
dataset_dir / "training" / "images",
dataset_dir / "training" / "labels",
n_classes,
batch_size=training_batch_size,
output_size=output_size,
to_stereo=to_stereo,
**{tr: True for tr in transformations},
class_mappings=class_mappings,
)
validation_generator = cls(
dataset_dir / "val" / "images",
dataset_dir / "val" / "labels",
n_classes,
batch_size=validation_batch_size,
output_size=output_size,
to_stereo=to_stereo,
**{tr: True for tr in transformations},
class_mappings=class_mappings,
)
return training_generator, validation_generator
y_k_size = 6
x_k_size = 6
class BaseDataset(Dataset):
def __init__(
self,
ignore_label=255,
base_size=2048,
crop_size=(512, 1024),
scale_factor=16,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
):
self.base_size = base_size
self.crop_size = crop_size
self.ignore_label = ignore_label
self.mean = mean
self.std = std
self.scale_factor = scale_factor
self.files = []
def __len__(self):
return len(self.files)
def input_transform(self, image, city=True):
if city:
image = image.astype(np.float32)[:, :, ::-1]
else:
image = image.astype(np.float32)
image = image / 255.0
image -= self.mean
image /= self.std
return image
def label_transform(self, label):
return np.array(label).astype(np.uint8)
def pad_image(self, image, h, w, size, padvalue):
pad_image = image.copy()
pad_h = max(size[0] - h, 0)
pad_w = max(size[1] - w, 0)
if pad_h > 0 or pad_w > 0:
pad_image = cv2.copyMakeBorder(
image, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=padvalue
)
return pad_image
def rand_crop(self, image, label, edge):
h, w = image.shape[:-1]
image = self.pad_image(image, h, w, self.crop_size, (0.0, 0.0, 0.0))
label = self.pad_image(label, h, w, self.crop_size, (self.ignore_label,))
edge = self.pad_image(edge, h, w, self.crop_size, (0.0,))
new_h, new_w = label.shape
x = random.randint(0, new_w - self.crop_size[1])
y = random.randint(0, new_h - self.crop_size[0])
image = image[y : y + self.crop_size[0], x : x + self.crop_size[1]]
label = label[y : y + self.crop_size[0], x : x + self.crop_size[1]]
edge = edge[y : y + self.crop_size[0], x : x + self.crop_size[1]]
return image, label, edge
def multi_scale_aug(
self, image, label=None, edge=None, rand_scale=1, rand_crop=True
):
long_size = np.int(self.base_size * rand_scale + 0.5)
h, w = image.shape[:2]
if h > w:
new_h = long_size
new_w = np.int(w * long_size / h + 0.5)
else:
new_w = long_size
new_h = np.int(h * long_size / w + 0.5)
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
if label is not None:
label = cv2.resize(label, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
if edge is not None:
edge = cv2.resize(edge, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
else:
return image
if rand_crop:
image, label, edge = self.rand_crop(image, label, edge)
return image, label, edge
def gen_sample(
self,
image,
label,
multi_scale=True,
is_flip=True,
edge_pad=True,
edge_size=4,
city=False,
):
edge = cv2.Canny(label, 0.1, 0.2)
kernel = np.ones((edge_size, edge_size), np.uint8)
if edge_pad:
edge = edge[y_k_size:-y_k_size, x_k_size:-x_k_size]
edge = np.pad(
edge, ((y_k_size, y_k_size), (x_k_size, x_k_size)), mode="constant"
)
edge = (cv2.dilate(edge, kernel, iterations=1) > 50) * 1.0
if multi_scale:
rand_scale = 0.5 + random.randint(0, self.scale_factor) / 10.0
image, label, edge = self.multi_scale_aug(
image, label, edge, rand_scale=rand_scale
)
image = self.input_transform(image, city=city)
label = self.label_transform(label)
image = image.transpose((2, 0, 1))
if is_flip:
flip = np.random.choice(2) * 2 - 1
image = image[:, :, ::flip]
label = label[:, ::flip]
edge = edge[:, ::flip]
return image, label, edge
def inference(self, config, model, image):
size = image.size()
pred = model(image)
if config.MODEL.NUM_OUTPUTS > 1:
pred = pred[config.TEST.OUTPUT_INDEX]
pred = F.interpolate(
input=pred,
size=size[-2:],
mode="bilinear",
align_corners=config.MODEL.ALIGN_CORNERS,
)
return pred.exp()
class PIDNetDataset(BaseDataset):
def __init__(
self,
images_path,
labels_path,
n_classes,
output_size=(480, 640),
to_stereo=False,
flip=False,
saturation=False,
contrast=False,
brightness=False,
class_mappings=None,
multi_scale=True,
ignore_label=255,
base_size=2048,
crop_size=(512, 1024),
scale_factor=16,
# mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225],
mean=[0.342, 0.374, 0.416],
std=[0.241, 0.239, 0.253],
bd_dilate_size=4,
):
super(PIDNetDataset, self).__init__(
ignore_label, base_size, crop_size, scale_factor, mean, std
)
self.images_path = Path(images_path)
self.labels_path = Path(labels_path)
self.n_classes = n_classes
self.output_size = output_size
self.to_stereo = to_stereo
self.class_mappings = class_mappings
self.bd_dilate_size = bd_dilate_size
self.multi_scale = multi_scale
self.flip = flip
# Check image and labels dir
img_paths = sorted(list(self.images_path.iterdir()))
def has_label(img_filename):
return (self.labels_path / f"{img_filename.stem}.png").exists()
if not all(map(has_label, img_paths)):
raise FileNotFoundError("Check every image has a label")
# Obtain transformations
transformations = []
# if flip:
# transformations.append('flip')
if saturation:
transformations.append("saturation")
if contrast:
transformations.append("contrast")
if brightness:
transformations.append("brightness")
# Prepare augmentation
elements = []
for image_path in img_paths:
label_path = self.labels_path / f"{image_path.stem}.png"
elements.append(
ImageHelper(
image_path,
label_path,
self.output_size,
to_stereo=self.to_stereo,
)
)
for tr in transformations:
elements.append(
ImageHelper(
image_path,
label_path,
self.output_size,
to_stereo=self.to_stereo,
**{tr: True},
)
)
self.elements = elements
def __len__(self):
return len(self.elements)
def __getitem__(self, idx):
element = self.elements[idx]
name = element.img_path.stem
X, y = element.get()
# Class mappings
if self.class_mappings:
y = np.vectorize(lambda x: self.class_mappings[x])(y).astype(np.uint8)
y_onehot = np.zeros(y.shape + (self.n_classes,))
for i in np.unique(y):
i = int(i)
idx_for_this_class = np.where(y == i)
if self.class_mappings:
y_onehot[
idx_for_this_class
+ (
np.ones(len(idx_for_this_class[0]), dtype=int)
* self.class_mappings[i],
)
] = 1
else:
y_onehot[
idx_for_this_class
+ (np.ones(len(idx_for_this_class[0]), dtype=int) * i,)
] = 1
# assert final_X.shape[:-1] == final_y.shape[:-1]
image, label = X, y
image, label, edge = self.gen_sample(
image, label, self.multi_scale, self.flip, edge_size=self.bd_dilate_size
)
return image.copy(), label.copy(), edge.copy(), np.array(image.shape), name
@classmethod
def create_train_and_test_datasets(
cls,
dataset_dir,
n_classes,
output_size=(480, 640),
to_stereo=False,
transformations=tuple(),
class_mappings=None,
):
dataset_dir = Path(dataset_dir)
training_generator = cls(
dataset_dir / "training" / "images",
dataset_dir / "training" / "labels",
n_classes,
output_size=output_size,
to_stereo=to_stereo,
**{tr: True for tr in transformations},
class_mappings=class_mappings,
)
validation_generator = cls(
dataset_dir / "val" / "images",
dataset_dir / "val" / "labels",
n_classes,
output_size=output_size,
to_stereo=to_stereo,
# **{tr: True for tr in transformations}
class_mappings=class_mappings,
)
return training_generator, validation_generator
class MergedDataset(Dataset):
def __init__(self, *datasets):
self.datasets = datasets
for d in self.datasets:
assert isinstance(d, Dataset)
self.lens = [len(d) for d in self.datasets]
self.acc_lens = [sum(self.lens[: i + 1]) for i in range(len(self.lens))]
def __len__(self):
return sum(self.lens)
def __getitem__(self, idx):
for i in range(len(self.acc_lens)):
if idx < self.acc_lens[i]:
diff = self.acc_lens[i - 1] if i != 0 else 0
s = self.datasets[i][idx - diff]
# assert s[1].max() <= 3
# assert s[1].max() <= 3
return s
raise ValueError(
f"idx out of range, was {idx}, should be less than {self.__len__()}"
)
if __name__ == "__main__":
"""
dataset_dir = Path('/home/user/nas/Datasets/egocentric_segmentation/joint-ep-of-thu-ego-for-5-office-objects/')
helper = ImageHelper(
dataset_dir / 'training' / 'images' / 'L515_020_003_rgb_0246.jpg',
dataset_dir / 'training' / 'labels' / 'L515_020_003_rgb_0246.png',
(480, 640),
to_stereo=True
)
image, label = helper.get()
"""
gen = DataGenerator(
Path(
"C:/Users/xruser/RealTimeSemanticSegmentation/joint-ep-of-thu-ego-stereo-1280x480/joint-ep-of-thu-ego-stereo-1280x480/"
)
/ "pruned_training"
/ "images",
Path(
"C:/Users/xruser/RealTimeSemanticSegmentation/joint-ep-of-thu-ego-stereo-1280x480/joint-ep-of-thu-ego-stereo-1280x480/"
)
/ "pruned_training"
/ "labels",
7,
batch_size=4,
to_stereo=True,
)
images, labels = gen[0]
print("hola")
|