-
Notifications
You must be signed in to change notification settings - Fork 16
/
data.py
78 lines (63 loc) · 2.48 KB
/
data.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
74
75
76
77
78
import os
import numpy as np
import cv2
from glob import glob
import torch
from torch.utils.data import Dataset, DataLoader
def load_names(path, file_path):
f = open(file_path, "r")
data = f.read().split("\n")[:-1]
images = [os.path.join(path,"images", name) + ".jpg" for name in data]
masks = [os.path.join(path,"masks", name) + ".jpg" for name in data]
return images, masks
def load_data(path):
train_names_path = f"{path}/train.txt"
valid_names_path = f"{path}/val.txt"
train_x, train_y = load_names(path, train_names_path)
valid_x, valid_y = load_names(path, valid_names_path)
return (train_x, train_y), (valid_x, valid_y)
class KvasirDataset(Dataset):
""" Dataset for the Kvasir-SEG dataset. """
def __init__(self, images_path, masks_path, size):
"""
Arguments:
images_path: A list of path of the images.
masks_path: A list of path of the masks.
"""
self.images_path = images_path
self.masks_path = masks_path
self.height = size[0]
self.width = size[1]
self.n_samples = len(images_path)
def __getitem__(self, index):
""" Reading image and mask. """
image = cv2.imread(self.images_path[index], cv2.IMREAD_COLOR)
mask = cv2.imread(self.masks_path[index], cv2.IMREAD_GRAYSCALE)
""" Resizing. """
image1 = cv2.resize(image, (self.width, self.height))
# image2 = cv2.resize(image, (self.width//2, self.height//2))
# image3 = cv2.resize(image, (self.width//4, self.height//4))
mask = cv2.resize(mask, (self.width, self.height))
""" Proper channel formatting. """
image1 = np.transpose(image1, (2, 0, 1))
# image2 = np.transpose(image2, (2, 0, 1))
# image3 = np.transpose(image3, (2, 0, 1))
mask = np.expand_dims(mask, axis=0)
""" Normalization. """
image1 = image1/255.0
# image2 = image2/255.0
# image3 = image3/255.0
mask = mask/255.0
""" Changing datatype to float32. """
image1 = image1.astype(np.float32)
# image2 = image2.astype(np.float32)
# image3 = image3.astype(np.float32)
mask = mask.astype(np.float32)
""" Changing numpy to tensor. """
image1 = torch.from_numpy(image1)
# image2 = torch.from_numpy(image2)
# image3 = torch.from_numpy(image3)
mask = torch.from_numpy(mask)
return image1, mask
def __len__(self):
return self.n_samples