File size: 22,663 Bytes
1ab03a3 | 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 | import os
from io import BytesIO
from pathlib import Path
import lmdb
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.datasets import CIFAR10, LSUNClass
import torch
import pandas as pd
import torchvision.transforms.functional as Ftrans
class ImageDataset(Dataset):
def __init__(
self,
folder,
image_size,
exts=['jpg'],
do_augment: bool = True,
do_transform: bool = True,
do_normalize: bool = True,
sort_names=False,
has_subdir: bool = True,
):
super().__init__()
self.folder = folder
self.image_size = image_size
# relative paths (make it shorter, saves memory and faster to sort)
if has_subdir:
self.paths = [
p.relative_to(folder) for ext in exts
for p in Path(f'{folder}').glob(f'**/*.{ext}')
]
else:
self.paths = [
p.relative_to(folder) for ext in exts
for p in Path(f'{folder}').glob(f'*.{ext}')
]
if sort_names:
self.paths = sorted(self.paths)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return len(self.paths)
def __getitem__(self, index):
path = os.path.join(self.folder, self.paths[index])
img = Image.open(path)
# if the image is 'rgba'!
img = img.convert('RGB')
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class SubsetDataset(Dataset):
def __init__(self, dataset, size):
assert len(dataset) >= size
self.dataset = dataset
self.size = size
def __len__(self):
return self.size
def __getitem__(self, index):
assert index < self.size
return self.dataset[index]
class BaseLMDB(Dataset):
def __init__(self, path, original_resolution, zfill: int = 5):
self.original_resolution = original_resolution
self.zfill = zfill
self.env = lmdb.open(
path,
max_readers=32,
readonly=True,
lock=False,
readahead=False,
meminit=False,
)
if not self.env:
raise IOError('Cannot open lmdb dataset', path)
with self.env.begin(write=False) as txn:
self.length = int(
txn.get('length'.encode('utf-8')).decode('utf-8'))
def __len__(self):
return self.length
def __getitem__(self, index):
with self.env.begin(write=False) as txn:
key = f'{self.original_resolution}-{str(index).zfill(self.zfill)}'.encode(
'utf-8')
img_bytes = txn.get(key)
buffer = BytesIO(img_bytes)
img = Image.open(buffer)
return img
def make_transform(
image_size,
flip_prob=0.5,
crop_d2c=False,
):
if crop_d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
transform.append(transforms.RandomHorizontalFlip(p=flip_prob))
transform.append(transforms.ToTensor())
transform.append(transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
transform = transforms.Compose(transform)
return transform
class FFHQlmdb(Dataset):
def __init__(self,
path=os.path.expanduser('datasets/ffhq256.lmdb'),
image_size=256,
original_resolution=256,
split=None,
as_tensor: bool = True,
do_augment: bool = True,
do_normalize: bool = True,
**kwargs):
self.original_resolution = original_resolution
self.data = BaseLMDB(path, original_resolution, zfill=5)
self.length = len(self.data)
if split is None:
self.offset = 0
elif split == 'train':
# last 60k
self.length = self.length - 10000
self.offset = 10000
elif split == 'test':
# first 10k
self.length = 10000
self.offset = 0
else:
raise NotImplementedError()
transform = [
transforms.Resize(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if as_tensor:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return self.length
def __getitem__(self, index):
assert index < self.length
index = index + self.offset
img = self.data[index]
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class Crop:
def __init__(self, x1, x2, y1, y2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def __call__(self, img):
return Ftrans.crop(img, self.x1, self.y1, self.x2 - self.x1,
self.y2 - self.y1)
def __repr__(self):
return self.__class__.__name__ + "(x1={}, x2={}, y1={}, y2={})".format(
self.x1, self.x2, self.y1, self.y2)
def d2c_crop():
# from D2C paper for CelebA dataset.
cx = 89
cy = 121
x1 = cy - 64
x2 = cy + 64
y1 = cx - 64
y2 = cx + 64
return Crop(x1, x2, y1, y2)
class CelebAlmdb(Dataset):
"""
also supports for d2c crop.
"""
def __init__(self,
path,
image_size,
original_resolution=128,
split=None,
as_tensor: bool = True,
do_augment: bool = True,
do_normalize: bool = True,
crop_d2c: bool = False,
**kwargs):
self.original_resolution = original_resolution
self.data = BaseLMDB(path, original_resolution, zfill=7)
self.length = len(self.data)
self.crop_d2c = crop_d2c
if split is None:
self.offset = 0
else:
raise NotImplementedError()
if crop_d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if as_tensor:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return self.length
def __getitem__(self, index):
assert index < self.length
index = index + self.offset
img = self.data[index]
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class Horse_lmdb(Dataset):
def __init__(self,
path=os.path.expanduser('datasets/horse256.lmdb'),
image_size=128,
original_resolution=256,
do_augment: bool = True,
do_transform: bool = True,
do_normalize: bool = True,
**kwargs):
self.original_resolution = original_resolution
print(path)
self.data = BaseLMDB(path, original_resolution, zfill=7)
self.length = len(self.data)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return self.length
def __getitem__(self, index):
img = self.data[index]
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index}
class Bedroom_lmdb(Dataset):
def __init__(self,
path=os.path.expanduser('datasets/bedroom256.lmdb'),
image_size=128,
original_resolution=256,
do_augment: bool = True,
do_transform: bool = True,
do_normalize: bool = True,
**kwargs):
self.original_resolution = original_resolution
print(path)
self.data = BaseLMDB(path, original_resolution, zfill=7)
self.length = len(self.data)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def __len__(self):
return self.length
def __getitem__(self, index):
img = self.data[index]
img = self.transform(img)
return {'img': img, 'index': index}
class CelebAttrDataset(Dataset):
id_to_cls = [
'5_o_Clock_Shadow', 'Arched_Eyebrows', 'Attractive', 'Bags_Under_Eyes',
'Bald', 'Bangs', 'Big_Lips', 'Big_Nose', 'Black_Hair', 'Blond_Hair',
'Blurry', 'Brown_Hair', 'Bushy_Eyebrows', 'Chubby', 'Double_Chin',
'Eyeglasses', 'Goatee', 'Gray_Hair', 'Heavy_Makeup', 'High_Cheekbones',
'Male', 'Mouth_Slightly_Open', 'Mustache', 'Narrow_Eyes', 'No_Beard',
'Oval_Face', 'Pale_Skin', 'Pointy_Nose', 'Receding_Hairline',
'Rosy_Cheeks', 'Sideburns', 'Smiling', 'Straight_Hair', 'Wavy_Hair',
'Wearing_Earrings', 'Wearing_Hat', 'Wearing_Lipstick',
'Wearing_Necklace', 'Wearing_Necktie', 'Young'
]
cls_to_id = {v: k for k, v in enumerate(id_to_cls)}
def __init__(self,
folder,
image_size=64,
attr_path=os.path.expanduser(
'datasets/celeba_anno/list_attr_celeba.txt'),
ext='png',
only_cls_name: str = None,
only_cls_value: int = None,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True,
d2c: bool = False):
super().__init__()
self.folder = folder
self.image_size = image_size
self.ext = ext
# relative paths (make it shorter, saves memory and faster to sort)
paths = [
str(p.relative_to(folder))
for p in Path(f'{folder}').glob(f'**/*.{ext}')
]
paths = [str(each).split('.')[0] + '.jpg' for each in paths]
if d2c:
transform = [
d2c_crop(),
transforms.Resize(image_size),
]
else:
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
with open(attr_path) as f:
# discard the top line
f.readline()
self.df = pd.read_csv(f, delim_whitespace=True)
self.df = self.df[self.df.index.isin(paths)]
if only_cls_name is not None:
self.df = self.df[self.df[only_cls_name] == only_cls_value]
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
name = row.name.split('.')[0]
name = f'{name}.{self.ext}'
path = os.path.join(self.folder, name)
img = Image.open(path)
labels = [0] * len(self.id_to_cls)
for k, v in row.items():
labels[self.cls_to_id[k]] = int(v)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': torch.tensor(labels)}
class CelebD2CAttrDataset(CelebAttrDataset):
"""
the dataset is used in the D2C paper.
it has a specific crop from the original CelebA.
"""
def __init__(self,
folder,
image_size=64,
attr_path=os.path.expanduser(
'datasets/celeba_anno/list_attr_celeba.txt'),
ext='jpg',
only_cls_name: str = None,
only_cls_value: int = None,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True,
d2c: bool = True):
super().__init__(folder,
image_size,
attr_path,
ext=ext,
only_cls_name=only_cls_name,
only_cls_value=only_cls_value,
do_augment=do_augment,
do_transform=do_transform,
do_normalize=do_normalize,
d2c=d2c)
class CelebAttrFewshotDataset(Dataset):
def __init__(
self,
cls_name,
K,
img_folder,
img_size=64,
ext='png',
seed=0,
only_cls_name: str = None,
only_cls_value: int = None,
all_neg: bool = False,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True,
d2c: bool = False,
) -> None:
self.cls_name = cls_name
self.K = K
self.img_folder = img_folder
self.ext = ext
if all_neg:
path = f'data/celeba_fewshots/K{K}_allneg_{cls_name}_{seed}.csv'
else:
path = f'data/celeba_fewshots/K{K}_{cls_name}_{seed}.csv'
self.df = pd.read_csv(path, index_col=0)
if only_cls_name is not None:
self.df = self.df[self.df[only_cls_name] == only_cls_value]
if d2c:
transform = [
d2c_crop(),
transforms.Resize(img_size),
]
else:
transform = [
transforms.Resize(img_size),
transforms.CenterCrop(img_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
name = row.name.split('.')[0]
name = f'{name}.{self.ext}'
path = os.path.join(self.img_folder, name)
img = Image.open(path)
# (1, 1)
label = torch.tensor(int(row[self.cls_name])).unsqueeze(-1)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': label}
class CelebD2CAttrFewshotDataset(CelebAttrFewshotDataset):
def __init__(self,
cls_name,
K,
img_folder,
img_size=64,
ext='jpg',
seed=0,
only_cls_name: str = None,
only_cls_value: int = None,
all_neg: bool = False,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True,
is_negative=False,
d2c: bool = True) -> None:
super().__init__(cls_name,
K,
img_folder,
img_size,
ext=ext,
seed=seed,
only_cls_name=only_cls_name,
only_cls_value=only_cls_value,
all_neg=all_neg,
do_augment=do_augment,
do_transform=do_transform,
do_normalize=do_normalize,
d2c=d2c)
self.is_negative = is_negative
class CelebHQAttrDataset(Dataset):
id_to_cls = [
'5_o_Clock_Shadow', 'Arched_Eyebrows', 'Attractive', 'Bags_Under_Eyes',
'Bald', 'Bangs', 'Big_Lips', 'Big_Nose', 'Black_Hair', 'Blond_Hair',
'Blurry', 'Brown_Hair', 'Bushy_Eyebrows', 'Chubby', 'Double_Chin',
'Eyeglasses', 'Goatee', 'Gray_Hair', 'Heavy_Makeup', 'High_Cheekbones',
'Male', 'Mouth_Slightly_Open', 'Mustache', 'Narrow_Eyes', 'No_Beard',
'Oval_Face', 'Pale_Skin', 'Pointy_Nose', 'Receding_Hairline',
'Rosy_Cheeks', 'Sideburns', 'Smiling', 'Straight_Hair', 'Wavy_Hair',
'Wearing_Earrings', 'Wearing_Hat', 'Wearing_Lipstick',
'Wearing_Necklace', 'Wearing_Necktie', 'Young'
]
cls_to_id = {v: k for k, v in enumerate(id_to_cls)}
def __init__(self,
path=os.path.expanduser('datasets/celebahq256.lmdb'),
image_size=None,
attr_path=os.path.expanduser(
'datasets/celeba_anno/CelebAMask-HQ-attribute-anno.txt'),
original_resolution=256,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True):
super().__init__()
self.image_size = image_size
self.data = BaseLMDB(path, original_resolution, zfill=5)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
with open(attr_path) as f:
# discard the top line
f.readline()
self.df = pd.read_csv(f, delim_whitespace=True)
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
img_name = row.name
img_idx, ext = img_name.split('.')
img = self.data[img_idx]
labels = [0] * len(self.id_to_cls)
for k, v in row.items():
labels[self.cls_to_id[k]] = int(v)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': torch.tensor(labels)}
class CelebHQAttrFewshotDataset(Dataset):
def __init__(self,
cls_name,
K,
path,
image_size,
original_resolution=256,
do_augment: bool = False,
do_transform: bool = True,
do_normalize: bool = True):
super().__init__()
self.image_size = image_size
self.cls_name = cls_name
self.K = K
self.data = BaseLMDB(path, original_resolution, zfill=5)
transform = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
]
if do_augment:
transform.append(transforms.RandomHorizontalFlip())
if do_transform:
transform.append(transforms.ToTensor())
if do_normalize:
transform.append(
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
self.transform = transforms.Compose(transform)
self.df = pd.read_csv(f'data/celebahq_fewshots/K{K}_{cls_name}.csv',
index_col=0)
def pos_count(self, cls_name):
return (self.df[cls_name] == 1).sum()
def neg_count(self, cls_name):
return (self.df[cls_name] == -1).sum()
def __len__(self):
return len(self.df)
def __getitem__(self, index):
row = self.df.iloc[index]
img_name = row.name
img_idx, ext = img_name.split('.')
img = self.data[img_idx]
# (1, 1)
label = torch.tensor(int(row[self.cls_name])).unsqueeze(-1)
if self.transform is not None:
img = self.transform(img)
return {'img': img, 'index': index, 'labels': label}
class Repeat(Dataset):
def __init__(self, dataset, new_len) -> None:
super().__init__()
self.dataset = dataset
self.original_len = len(dataset)
self.new_len = new_len
def __len__(self):
return self.new_len
def __getitem__(self, index):
index = index % self.original_len
return self.dataset[index]
|