-
Notifications
You must be signed in to change notification settings - Fork 5
/
pytorch_datasets.py
71 lines (54 loc) · 1.82 KB
/
pytorch_datasets.py
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
import torch
from torch.utils.data import Dataset, DataLoader
from skimage import io, transform
import os
import numpy as np
import lmdb
import cv2
import random
class celeba_hq_dataset(Dataset):
"""CelebA HQ dataset."""
def __init__(self, data_dir, batchsize, transform=None):
self.root_dir = data_dir
self.num_imgs = len(os.listdir(self.root_dir))
self.transform = transform
self.batchsize = batchsize
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
np.random.seed()
idx = np.random.randint(0, self.num_imgs)
img_name = os.path.join(self.root_dir, '%d.jpg'%(idx))
image = io.imread(img_name)
image = image * 1.0 / 255.0
image = torch.from_numpy(image)
image = image.permute(2, 0, 1)
if self.transform:
image = self.transform(image)
return image
class afhq_dataset(Dataset):
"""AFHQ dataset."""
def __init__(self, data_dir, batchsize, category='cat', transform=None):
self.root_dir = os.path.join(data_dir, category)
self.files = os.listdir(self.root_dir)
self.num_imgs = len(self.files)
self.transform = transform
self.batchsize = batchsize
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
np.random.seed()
while True:
try:
idx = np.random.randint(0, self.num_imgs)
img_name = os.path.join(self.root_dir, '%s'%(self.files[idx]))
image = io.imread(img_name)
break
except:
continue
image = image * 1.0 / 255.0
image = torch.from_numpy(image)
image = image.permute(2, 0, 1)
if self.transform:
image = self.transform(image)
return image