-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
70 lines (47 loc) · 1.93 KB
/
dataset.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
from typing import Tuple, Callable
import torch
import torchvision
import os
import numpy as np
import cv2
class ImageDatasetLAB(torch.utils.data.Dataset):
def __init__(self, data_dir: str, transform: Callable = None) -> None:
""" ImageDatasetL2AB: Dataset class to handle a flat image directory.
Parameters
----------
data_dir : str
Path to the flat image directory. This directory should not contain any other subdirectory or unsupported file types.
transform : Callable
Callable that takes in a PIL image and returns the transformation result.
"""
super(ImageDatasetLAB, self).__init__()
self.data_dir = data_dir
self.img_files = os.listdir(self.data_dir)
self.transform = transform
def __len__(self) -> int:
return len(self.img_files)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
if torch.is_tensor(idx):
idx = idx.tolist()
if idx >= len(self):
raise IndexError
# load the image at the given index
load_path = os.path.join(self.data_dir, self.img_files[idx])
img = cv2.imread(load_path)
# translate the image to the LAB color space
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# convert image to PIL image for pytorch transformations
img = torchvision.transforms.functional.to_pil_image(img)
# apply transformation if necessary
if self.transform:
img = self.transform(img)
# convert image back to numpy and translate into LAB color space
if torch.is_tensor(img):
img = np.array(img)
img = img.transpose(1, 2, 0)
else:
img = np.array(img)
img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
# convert numpy.ndarray to torch.Tensor
img = torchvision.transforms.functional.to_tensor(img)
return img