-
Notifications
You must be signed in to change notification settings - Fork 6
/
dataset.py
172 lines (131 loc) · 5.6 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
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
import random
import torch
import torch.nn as nn
from torch.utils import data
from torch.autograd import Variable
import os, sys
import numpy as np
import cv2
from torchvision import transforms
import alphabet
str1 = alphabet.alphabet
def str_Converter_init():
dict = {"PAD": 0, "SOS": 1, "EOS": 2, "Blank": 3}
for i, char in enumerate(str1):
# NOTE: 0 is reserved for 'blank' required by wrap_ctc
dict[char] = i + 4
nclass = len(str1) + 5
return dict, nclass
def str_Converter(label, dict):
if dict.__contains__(label):
return dict[label]
else:
return len(str1) + 4
def extract_vertices(lines, dict):
labels = []
lenght_lable = []
for line in lines:
label = line.rstrip('\n').lstrip('\ufeff')
if label != "###":
for i in range(len(label)):
labels.append(str_Converter(label[i], dict))
labels.append(2)
lenght_lable.append(len(label))
return labels, lenght_lable
def rotate_img(img, angle_range=10):
center_x = (img.shape[1] - 1) // 2
center_y = (img.shape[0] - 1) // 2
angle = angle_range * (np.random.rand() * 2 - 1)
M = cv2.getRotationMatrix2D((center_x, center_y), angle, 1.0) # 12
img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
return img
def subsequent_mask(size):
# Mask out subsequent positions.
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0
def make_std_mask(tgt, pad=0):
# Create a mask to hide padding and future words.
tgt_mask = (tgt != pad).unsqueeze(-2)
tgt_mask = tgt_mask & Variable(
subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))
return Variable(tgt_mask.cuda(), requires_grad=False)
def mask_gen(size, lable_lenght):
mask = np.triu(np.ones((size, size)), k=1).astype('uint8')
total_lenght = 1
lable_lenght_next = 0
for i in range(len(lable_lenght) - 1):
lable_lenght_next = lable_lenght[i + 1]
total_lenght += (lable_lenght[i] + 1)
mask[total_lenght:total_lenght + lable_lenght[i + 1], :total_lenght] = 1
mask[total_lenght + lable_lenght_next + 1:, :total_lenght] = 1
mask = torch.from_numpy(mask) == 0
return mask
def resize_padding(image, w=512):
max_wh = max(image.shape[0], image.shape[1])
newImage = np.zeros((max_wh, max_wh, 3), np.uint8)
newImage[:image.shape[0], :image.shape[1], :] = image
newImage = cv2.resize(newImage, (w, w))
return newImage
class custom_dataset(data.Dataset):
def __init__(self, img_path, gt_path, len_img=512, batch_max_length=200):
super(custom_dataset, self).__init__()
self.img_files = [os.path.join(img_path, img_file) for img_file in sorted(os.listdir(img_path))]
self.gt_files = [os.path.join(gt_path, gt_file) for gt_file in sorted(os.listdir(gt_path))]
self.len_img = len_img
self.batch_max_length = batch_max_length
self.dict, self.nclass = str_Converter_init()
print(len(self.img_files))
for i in range(len(self.img_files)):
img_id = [os.path.basename(self.img_files[i]).strip('.JPG').strip('.jpg'),
os.path.basename(self.gt_files[i]).strip('.txt').strip('gt_')]
if img_id[0] == img_id[1]:
continue
else:
print(img_id[0])
print(img_id[1])
sys.exit('img list and txt list is not matched')
def __len__(self):
return len(self.img_files)
def __getitem__(self, index):
transform = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
gt_path = self.gt_files[index]
img = cv2.imread(self.img_files[index], cv2.IMREAD_COLOR)
img = resize_padding(img)
if random.random() < 0.5:
rotate_angle = random.randint(-30, 30)
img = rotate_img(img, rotate_angle)
img = cv2.resize(img, (self.len_img, self.len_img))
img = img / 255.0
img = torch.Tensor(img).permute(2, 0, 1)
with open(gt_path, 'r', encoding='utf-8-sig') as f:
lines = f.readlines()
tags, lenght_lables = extract_vertices(lines, self.dict)
tags_y = tags[:]
tags_y.append(3)
mask = mask_gen(self.batch_max_length, lenght_lables)
label = np.zeros(self.batch_max_length, dtype=int)
label[0] = 1
for i in range(len(tags)):
label[i + 1] = tags[i]
label = torch.from_numpy(label)
label_y = np.zeros(self.batch_max_length, dtype=int)
for i in range(len(tags_y)):
label_y[i] = tags_y[i]
label_y = torch.from_numpy(label_y)
tgt_mask = (label != 0).unsqueeze(-2)
mask = tgt_mask & Variable(mask.type_as(tgt_mask.data))
return transform(img), label, label_y, mask
class test_load(data.Dataset):
def __init__(self, img_path, len_img=512):
self.img_files = [os.path.join(img_path, img_file) for img_file in sorted(os.listdir(img_path))]
self.len_img = len_img
def __len__(self):
return len(self.img_files)
def __getitem__(self, index):
transform = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
img = cv2.imread(self.img_files[index], cv2.IMREAD_COLOR)
img = cv2.resize(img, (self.len_img, self.len_img))
img = img / 255.0
img = torch.Tensor(img).permute(2, 0, 1)
return transform(img)