dataset_traversal.py 9.89 KB
Newer Older
LDOUBLEV's avatar
LDOUBLEV committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

import os
tink2123's avatar
tink2123 committed
16
import sys
LDOUBLEV's avatar
LDOUBLEV committed
17
18
19
20
21
22
23
24
25
import math
import random
import numpy as np
import cv2

import string
import lmdb

from ppocr.utils.utility import initial_logger
tink2123's avatar
tink2123 committed
26
from ppocr.utils.utility import get_image_file_list
LDOUBLEV's avatar
LDOUBLEV committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
logger = initial_logger()

from .img_tools import process_image, get_img_data


class LMDBReader(object):
    def __init__(self, params):
        if params['mode'] != 'train':
            self.num_workers = 1
        else:
            self.num_workers = params['num_workers']
        self.lmdb_sets_dir = params['lmdb_sets_dir']
        self.char_ops = params['char_ops']
        self.image_shape = params['image_shape']
        self.loss_type = params['loss_type']
        self.max_text_length = params['max_text_length']
        self.mode = params['mode']
tink2123's avatar
tink2123 committed
44
        self.drop_last = False
tink2123's avatar
tink2123 committed
45
        self.tps = False
tink2123's avatar
tink2123 committed
46
47
        if "tps" in params:
            self.tps = True
LDOUBLEV's avatar
LDOUBLEV committed
48
49
        if params['mode'] == 'train':
            self.batch_size = params['train_batch_size_per_card']
tink2123's avatar
tink2123 committed
50
            self.drop_last = params['drop_last']
tink2123's avatar
tink2123 committed
51
        else:
LDOUBLEV's avatar
LDOUBLEV committed
52
            self.batch_size = params['test_batch_size_per_card']
tink2123's avatar
tink2123 committed
53
54
        self.infer_img = params['infer_img']

LDOUBLEV's avatar
LDOUBLEV committed
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
    def load_hierarchical_lmdb_dataset(self):
        lmdb_sets = {}
        dataset_idx = 0
        for dirpath, dirnames, filenames in os.walk(self.lmdb_sets_dir + '/'):
            if not dirnames:
                env = lmdb.open(
                    dirpath,
                    max_readers=32,
                    readonly=True,
                    lock=False,
                    readahead=False,
                    meminit=False)
                txn = env.begin(write=False)
                num_samples = int(txn.get('num-samples'.encode()))
                lmdb_sets[dataset_idx] = {"dirpath":dirpath, "env":env, \
                    "txn":txn, "num_samples":num_samples}
                dataset_idx += 1
        return lmdb_sets

    def print_lmdb_sets_info(self, lmdb_sets):
        lmdb_info_strs = []
        for dataset_idx in range(len(lmdb_sets)):
            tmp_str = " %s:%d," % (lmdb_sets[dataset_idx]['dirpath'],
                                   lmdb_sets[dataset_idx]['num_samples'])
            lmdb_info_strs.append(tmp_str)
        lmdb_info_strs = ''.join(lmdb_info_strs)
        logger.info("DataSummary:" + lmdb_info_strs)
        return

    def close_lmdb_dataset(self, lmdb_sets):
        for dataset_idx in lmdb_sets:
            lmdb_sets[dataset_idx]['env'].close()
        return

    def get_lmdb_sample_info(self, txn, index):
        label_key = 'label-%09d'.encode() % index
        label = txn.get(label_key)
        if label is None:
            return None
        label = label.decode('utf-8')
        img_key = 'image-%09d'.encode() % index
        imgbuf = txn.get(img_key)
        img = get_img_data(imgbuf)
        if img is None:
            return None
        return img, label

    def __call__(self, process_id):
        if self.mode != 'train':
            process_id = 0

        def sample_iter_reader():
tink2123's avatar
tink2123 committed
107
            if self.mode != 'train' and self.infer_img is not None:
tink2123's avatar
tink2123 committed
108
109
110
                image_file_list = get_image_file_list(self.infer_img)
                for single_img in image_file_list:
                    img = cv2.imread(single_img)
tink2123's avatar
tink2123 committed
111
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
tink2123's avatar
tink2123 committed
112
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
tink2123's avatar
tink2123 committed
113
114
115
                    norm_img = process_image(
                        img=img,
                        image_shape=self.image_shape,
tink2123's avatar
tink2123 committed
116
                        char_ops=self.char_ops,
tink2123's avatar
tink2123 committed
117
118
                        tps=self.tps,
                        infer_mode=True)
tink2123's avatar
tink2123 committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
                    yield norm_img
            else:
                lmdb_sets = self.load_hierarchical_lmdb_dataset()
                if process_id == 0:
                    self.print_lmdb_sets_info(lmdb_sets)
                cur_index_sets = [1 + process_id] * len(lmdb_sets)
                while True:
                    finish_read_num = 0
                    for dataset_idx in range(len(lmdb_sets)):
                        cur_index = cur_index_sets[dataset_idx]
                        if cur_index > lmdb_sets[dataset_idx]['num_samples']:
                            finish_read_num += 1
                        else:
                            sample_info = self.get_lmdb_sample_info(
                                lmdb_sets[dataset_idx]['txn'], cur_index)
                            cur_index_sets[dataset_idx] += self.num_workers
                            if sample_info is None:
                                continue
                            img, label = sample_info
tink2123's avatar
tink2123 committed
138
139
140
141
142
143
144
                            outs = process_image(
                                img=img,
                                image_shape=self.image_shape,
                                label=label,
                                char_ops=self.char_ops,
                                loss_type=self.loss_type,
                                max_text_length=self.max_text_length)
tink2123's avatar
tink2123 committed
145
146
147
148
149
150
151
                            if outs is None:
                                continue
                            yield outs

                    if finish_read_num == len(lmdb_sets):
                        break
                self.close_lmdb_dataset(lmdb_sets)
tink2123's avatar
tink2123 committed
152

LDOUBLEV's avatar
LDOUBLEV committed
153
154
155
156
157
158
159
        def batch_iter_reader():
            batch_outs = []
            for outs in sample_iter_reader():
                batch_outs.append(outs)
                if len(batch_outs) == self.batch_size:
                    yield batch_outs
                    batch_outs = []
tink2123's avatar
tink2123 committed
160
161
162
            if not self.drop_last:
                if len(batch_outs) != 0:
                    yield batch_outs
LDOUBLEV's avatar
LDOUBLEV committed
163

tink2123's avatar
tink2123 committed
164
        if self.infer_img is None:
tink2123's avatar
tink2123 committed
165
166
            return batch_iter_reader
        return sample_iter_reader
LDOUBLEV's avatar
LDOUBLEV committed
167
168
169
170
171
172
173
174


class SimpleReader(object):
    def __init__(self, params):
        if params['mode'] != 'train':
            self.num_workers = 1
        else:
            self.num_workers = params['num_workers']
tink2123's avatar
tink2123 committed
175
176
177
        if params['mode'] != 'test':
            self.img_set_dir = params['img_set_dir']
            self.label_file_path = params['label_file_path']
LDOUBLEV's avatar
LDOUBLEV committed
178
179
180
181
182
        self.char_ops = params['char_ops']
        self.image_shape = params['image_shape']
        self.loss_type = params['loss_type']
        self.max_text_length = params['max_text_length']
        self.mode = params['mode']
tink2123's avatar
tink2123 committed
183
        self.infer_img = params['infer_img']
tink2123's avatar
tink2123 committed
184
185
186
        self.tps = False
        if "tps" in params:
            self.tps = True
tink2123's avatar
tink2123 committed
187
        self.drop_last = False
LDOUBLEV's avatar
LDOUBLEV committed
188
189
        if params['mode'] == 'train':
            self.batch_size = params['train_batch_size_per_card']
tink2123's avatar
tink2123 committed
190
            self.drop_last = params['drop_last']
LDOUBLEV's avatar
LDOUBLEV committed
191
        else:
tink2123's avatar
tink2123 committed
192
            self.batch_size = params['test_batch_size_per_card']
LDOUBLEV's avatar
LDOUBLEV committed
193
194
195
196
197
198

    def __call__(self, process_id):
        if self.mode != 'train':
            process_id = 0

        def sample_iter_reader():
tink2123's avatar
tink2123 committed
199
            if self.mode != 'train' and self.infer_img is not None:
tink2123's avatar
tink2123 committed
200
                image_file_list = get_image_file_list(self.infer_img)
tink2123's avatar
tink2123 committed
201
202
                for single_img in image_file_list:
                    img = cv2.imread(single_img)
tink2123's avatar
tink2123 committed
203
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
tink2123's avatar
tink2123 committed
204
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
tink2123's avatar
tink2123 committed
205
206
207
                    norm_img = process_image(
                        img=img,
                        image_shape=self.image_shape,
tink2123's avatar
tink2123 committed
208
209
210
                        char_ops=self.char_ops,
                        tps=self.tps,
                        infer_mode=True)
tink2123's avatar
tink2123 committed
211
                    yield norm_img
tink2123's avatar
tink2123 committed
212
213
214
215
216
217
            else:
                with open(self.label_file_path, "rb") as fin:
                    label_infor_list = fin.readlines()
                img_num = len(label_infor_list)
                img_id_list = list(range(img_num))
                random.shuffle(img_id_list)
tink2123's avatar
tink2123 committed
218
                if sys.platform == "win32":
tink2123's avatar
tink2123 committed
219
220
221
                    print("multiprocess is not fully compatible with Windows."
                          "num_workers will be 1.")
                    self.num_workers = 1
tink2123's avatar
tink2123 committed
222
223
224
225
226
227
228
229
                for img_id in range(process_id, img_num, self.num_workers):
                    label_infor = label_infor_list[img_id_list[img_id]]
                    substr = label_infor.decode('utf-8').strip("\n").split("\t")
                    img_path = self.img_set_dir + "/" + substr[0]
                    img = cv2.imread(img_path)
                    if img is None:
                        logger.info("{} does not exist!".format(img_path))
                        continue
tink2123's avatar
tink2123 committed
230
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
tink2123's avatar
tink2123 committed
231
232
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

tink2123's avatar
tink2123 committed
233
234
235
236
237
238
239
                    label = substr[1]
                    outs = process_image(img, self.image_shape, label,
                                         self.char_ops, self.loss_type,
                                         self.max_text_length)
                    if outs is None:
                        continue
                    yield outs
LDOUBLEV's avatar
LDOUBLEV committed
240
241
242
243
244
245
246
247

        def batch_iter_reader():
            batch_outs = []
            for outs in sample_iter_reader():
                batch_outs.append(outs)
                if len(batch_outs) == self.batch_size:
                    yield batch_outs
                    batch_outs = []
tink2123's avatar
tink2123 committed
248
249
250
            if not self.drop_last:
                if len(batch_outs) != 0:
                    yield batch_outs
LDOUBLEV's avatar
LDOUBLEV committed
251

tink2123's avatar
tink2123 committed
252
        if self.infer_img is None:
tink2123's avatar
tink2123 committed
253
254
            return batch_iter_reader
        return sample_iter_reader