dataset_traversal.py 13.5 KB
Newer Older
L
LDOUBLEV 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#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
import random
S
shaohua.zhang 已提交
17
import sys
L
LDOUBLEV 已提交
18

S
shaohua.zhang 已提交
19
import cv2
L
LDOUBLEV 已提交
20 21
import lmdb

T
tink2123 已提交
22
from ppocr.utils.utility import get_image_file_list
S
shaohua.zhang 已提交
23
from ppocr.utils.utility import initial_logger
T
tink2123 已提交
24
from .img_tools import process_image, process_image_srn, get_img_data
S
shaohua.zhang 已提交
25
logger = initial_logger()
L
LDOUBLEV 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39


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']
T
tink2123 已提交
40
        self.drop_last = False
T
tink2123 已提交
41
        self.use_tps = False
T
tink2123 已提交
42 43 44
        self.num_heads = None
        if "num_heads" in params:
            self.num_heads = params['num_heads']
T
tink2123 已提交
45
        if "tps" in params:
T
tink2123 已提交
46
            self.ues_tps = True
T
tink2123 已提交
47
        self.use_distort = False
T
tink2123 已提交
48
        if "distort" in params:
T
tink2123 已提交
49 50 51 52 53
            self.use_distort = params['distort'] and params['use_gpu']
            if not params['use_gpu']:
                logger.info(
                    "Distort operation can only support in GPU. Distort will be set to False."
                )
L
LDOUBLEV 已提交
54 55
        if params['mode'] == 'train':
            self.batch_size = params['train_batch_size_per_card']
T
tink2123 已提交
56
            self.drop_last = True
T
tink2123 已提交
57
        else:
L
LDOUBLEV 已提交
58
            self.batch_size = params['test_batch_size_per_card']
T
tink2123 已提交
59
            self.drop_last = False
60
            self.use_distort = False
T
tink2123 已提交
61 62
        self.infer_img = params['infer_img']

L
LDOUBLEV 已提交
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
    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():
T
tink2123 已提交
115
            if self.mode != 'train' and self.infer_img is not None:
T
tink2123 已提交
116 117 118
                image_file_list = get_image_file_list(self.infer_img)
                for single_img in image_file_list:
                    img = cv2.imread(single_img)
T
tink2123 已提交
119
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
T
tink2123 已提交
120
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
T
tink2123 已提交
121 122 123 124 125
                    if self.loss_type == 'srn':
                        norm_img = process_image_srn(
                            img=img,
                            image_shape=self.image_shape,
                            num_heads=self.num_heads,
T
tink2123 已提交
126
                            max_text_length=self.max_text_length)
T
tink2123 已提交
127 128 129 130 131 132 133
                    else:
                        norm_img = process_image(
                            img=img,
                            image_shape=self.image_shape,
                            char_ops=self.char_ops,
                            tps=self.use_tps,
                            infer_mode=True)
T
tink2123 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
                    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
T
tink2123 已提交
153 154
                            outs = []
                            if self.loss_type == "srn":
T
tink2123 已提交
155
                                outs = process_image_srn(
T
tink2123 已提交
156 157 158 159 160 161 162
                                    img=img,
                                    image_shape=self.image_shape,
                                    num_heads=self.num_heads,
                                    max_text_length=self.max_text_length,
                                    label=label,
                                    char_ops=self.char_ops,
                                    loss_type=self.loss_type)
T
tink2123 已提交
163 164

                            else:
T
tink2123 已提交
165
                                outs = process_image(
T
tink2123 已提交
166 167 168 169 170 171
                                    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)
T
tink2123 已提交
172 173 174 175 176 177 178
                            if outs is None:
                                continue
                            yield outs

                    if finish_read_num == len(lmdb_sets):
                        break
                self.close_lmdb_dataset(lmdb_sets)
T
tink2123 已提交
179

L
LDOUBLEV 已提交
180 181 182 183 184 185 186
        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 = []
T
tink2123 已提交
187 188 189
            if not self.drop_last:
                if len(batch_outs) != 0:
                    yield batch_outs
L
LDOUBLEV 已提交
190

T
tink2123 已提交
191
        if self.infer_img is None:
T
tink2123 已提交
192 193
            return batch_iter_reader
        return sample_iter_reader
L
LDOUBLEV 已提交
194 195 196 197 198 199 200 201


class SimpleReader(object):
    def __init__(self, params):
        if params['mode'] != 'train':
            self.num_workers = 1
        else:
            self.num_workers = params['num_workers']
T
tink2123 已提交
202 203 204
        if params['mode'] != 'test':
            self.img_set_dir = params['img_set_dir']
            self.label_file_path = params['label_file_path']
T
tink2123 已提交
205
        self.use_gpu = params['use_gpu']
L
LDOUBLEV 已提交
206 207 208 209 210
        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']
T
tink2123 已提交
211
        self.infer_img = params['infer_img']
T
tink2123 已提交
212
        self.use_tps = False
T
tink2123 已提交
213 214
        if "num_heads" in params:
            self.num_heads = params['num_heads']
T
tink2123 已提交
215
        if "tps" in params:
T
tink2123 已提交
216
            self.use_tps = True
T
tink2123 已提交
217
        self.use_distort = False
T
tink2123 已提交
218
        if "distort" in params:
T
tink2123 已提交
219 220 221 222 223
            self.use_distort = params['distort'] and params['use_gpu']
            if not params['use_gpu']:
                logger.info(
                    "Distort operation can only support in GPU.Distort will be set to False."
                )
L
LDOUBLEV 已提交
224 225
        if params['mode'] == 'train':
            self.batch_size = params['train_batch_size_per_card']
T
tink2123 已提交
226
            self.drop_last = True
L
LDOUBLEV 已提交
227
        else:
T
tink2123 已提交
228
            self.batch_size = params['test_batch_size_per_card']
T
tink2123 已提交
229
            self.drop_last = False
230
            self.use_distort = False
L
LDOUBLEV 已提交
231 232 233 234 235

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

T
tink2123 已提交
236 237
        def get_device_num():
            if self.use_gpu:
Neo__Wong's avatar
Neo__Wong 已提交
238
                gpus = os.environ.get("CUDA_VISIBLE_DEVICES", '1')
T
tink2123 已提交
239 240 241 242 243 244
                gpu_num = len(gpus.split(','))
                return gpu_num
            else:
                cpu_num = os.environ.get("CPU_NUM", 1)
                return int(cpu_num)

L
LDOUBLEV 已提交
245
        def sample_iter_reader():
T
tink2123 已提交
246
            if self.mode != 'train' and self.infer_img is not None:
T
tink2123 已提交
247
                image_file_list = get_image_file_list(self.infer_img)
T
tink2123 已提交
248 249
                for single_img in image_file_list:
                    img = cv2.imread(single_img)
T
tink2123 已提交
250
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
T
tink2123 已提交
251
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
T
tink2123 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264
                    if self.loss_type == 'srn':
                        norm_img = process_image_srn(
                            img=img,
                            image_shape=self.image_shape,
                            num_heads=self.num_heads,
                            max_text_length=self.max_text_length)
                    else:
                        norm_img = process_image(
                            img=img,
                            image_shape=self.image_shape,
                            char_ops=self.char_ops,
                            tps=self.use_tps,
                            infer_mode=True)
T
tink2123 已提交
265
                    yield norm_img
T
tink2123 已提交
266
            else:
S
shaohua.zhang 已提交
267
                with open(self.label_file_path, "r", encoding="utf-8") as fin:
T
tink2123 已提交
268 269 270 271
                    label_infor_list = fin.readlines()
                img_num = len(label_infor_list)
                img_id_list = list(range(img_num))
                random.shuffle(img_id_list)
littletomatodonkey's avatar
littletomatodonkey 已提交
272
                if sys.platform == "win32" and self.num_workers != 1:
T
tink2123 已提交
273 274 275
                    print("multiprocess is not fully compatible with Windows."
                          "num_workers will be 1.")
                    self.num_workers = 1
littletomatodonkey's avatar
littletomatodonkey 已提交
276 277
                if self.batch_size * get_device_num(
                ) * self.num_workers > img_num:
T
tink2123 已提交
278
                    raise Exception(
littletomatodonkey's avatar
littletomatodonkey 已提交
279 280 281
                        "The number of the whole data ({}) is smaller than the batch_size * devices_num * num_workers ({})".
                        format(img_num, self.batch_size * get_device_num() *
                               self.num_workers))
T
tink2123 已提交
282 283
                for img_id in range(process_id, img_num, self.num_workers):
                    label_infor = label_infor_list[img_id_list[img_id]]
S
shaohua.zhang 已提交
284 285
                    substr = label_infor.strip("\n").strip().split()
                    img_path = os.path.join(self.img_set_dir, substr[0])
T
tink2123 已提交
286 287 288 289
                    img = cv2.imread(img_path)
                    if img is None:
                        logger.info("{} does not exist!".format(img_path))
                        continue
T
tink2123 已提交
290
                    if img.shape[-1] == 1 or len(list(img.shape)) == 2:
T
tink2123 已提交
291 292
                        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

T
tink2123 已提交
293
                    label = substr[1]
T
tink2123 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
                    if self.loss_type == "srn":
                        outs = process_image_srn(
                            img=img,
                            image_shape=self.image_shape,
                            num_heads=self.num_heads,
                            max_text_length=self.max_text_length,
                            label=label,
                            char_ops=self.char_ops,
                            loss_type=self.loss_type)

                    else:
                        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,
                            distort=self.use_distort)
T
tink2123 已提交
313 314 315
                    if outs is None:
                        continue
                    yield outs
L
LDOUBLEV 已提交
316 317 318 319 320 321 322 323

        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 = []
T
tink2123 已提交
324 325 326
            if not self.drop_last:
                if len(batch_outs) != 0:
                    yield batch_outs
L
LDOUBLEV 已提交
327

T
tink2123 已提交
328
        if self.infer_img is None:
T
tink2123 已提交
329 330
            return batch_iter_reader
        return sample_iter_reader