-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdata_gen.py
73 lines (58 loc) · 2.23 KB
/
data_gen.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
70
71
72
73
import os
import pickle
import cv2 as cv
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
from config import im_size, pickle_file_aligned, num_train, IMG_DIR
from utils import name2idx
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
'train': transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]),
'valid': transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
class FaceAttributesDataset(Dataset):
def __init__(self, split):
with open(pickle_file_aligned, 'rb') as file:
data = pickle.load(file)
samples = data['samples']
if split == 'train':
self.samples = samples[:num_train]
else:
self.samples = samples[num_train:]
self.transformer = data_transforms[split]
def __getitem__(self, i):
sample = self.samples[i]
filename = sample['filename']
full_path = os.path.join(IMG_DIR, filename)
# full_path = sample['filename']
# bbox = sample['bboxes'][0]
img = cv.imread(full_path)
# img = crop_image(img, bbox)
img = cv.resize(img, (im_size, im_size))
# img aug
img = img[..., ::-1] # RGB
img = transforms.ToPILImage()(img)
img = self.transformer(img)
age = sample['attr']['age'] / 100.
pitch = (sample['attr']['angle']['pitch'] + 180) / 360
roll = (sample['attr']['angle']['roll'] + 180) / 360
yaw = (sample['attr']['angle']['yaw'] + 180) / 360
beauty = sample['attr']['beauty'] / 100.
expression = name2idx(sample['attr']['expression']['type'])
gender = name2idx(sample['attr']['gender']['type'])
glasses = name2idx(sample['attr']['glasses']['type'])
race = name2idx(sample['attr']['race']['type'])
return img, np.array([age, pitch, roll, yaw, beauty]), expression, gender, glasses, race
def __len__(self):
return len(self.samples)
if __name__ == "__main__":
dataset = FaceAttributesDataset('train')
print(dataset[0])