simple_dataset.py 5.94 KB
Newer Older
dyning's avatar
dyning 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 numpy as np
import os
littletomatodonkey's avatar
littletomatodonkey committed
16
import json
dyning's avatar
dyning committed
17
import random
18
import traceback
dyning's avatar
dyning committed
19
20
from paddle.io import Dataset
from .imaug import transform, create_operators
dyning's avatar
dyning committed
21

dyning's avatar
dyning committed
22
23

class SimpleDataSet(Dataset):
24
    def __init__(self, config, mode, logger, seed=None):
dyning's avatar
dyning committed
25
        super(SimpleDataSet, self).__init__()
26
        self.logger = logger
27
        self.mode = mode.lower()
dyning's avatar
dyning committed
28

dyning's avatar
dyning committed
29
30
31
        global_config = config['Global']
        dataset_config = config[mode]['dataset']
        loader_config = config[mode]['loader']
dyning's avatar
dyning committed
32

dyning's avatar
dyning committed
33
34
35
        self.delimiter = dataset_config.get('delimiter', '\t')
        label_file_list = dataset_config.pop('label_file_list')
        data_source_num = len(label_file_list)
andyjpaddle's avatar
andyjpaddle committed
36
        ratio_list = dataset_config.get("ratio_list", 1.0)
37
        if isinstance(ratio_list, (float, int)):
LDOUBLEV's avatar
LDOUBLEV committed
38
            ratio_list = [float(ratio_list)] * int(data_source_num)
dyning's avatar
dyning committed
39
40
41
42

        assert len(
            ratio_list
        ) == data_source_num, "The length of ratio_list should be the same as the file_list."
dyning's avatar
dyning committed
43
44
        self.data_dir = dataset_config['data_dir']
        self.do_shuffle = loader_config['shuffle']
45
        self.seed = seed
dyning's avatar
dyning committed
46
        logger.info("Initialize indexs of datasets:%s" % label_file_list)
LDOUBLEV's avatar
LDOUBLEV committed
47
        self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
48
        self.data_idx_order_list = list(range(len(self.data_lines)))
49
        if self.mode == "train" and self.do_shuffle:
50
            self.shuffle_data_random()
dyning's avatar
dyning committed
51
        self.ops = create_operators(dataset_config['transforms'], global_config)
andyjpaddle's avatar
andyjpaddle committed
52
53
        self.ext_op_transform_idx = dataset_config.get("ext_op_transform_idx",
                                                       2)
54
55
        self.need_reset = True in [x < 1 for x in ratio_list]

LDOUBLEV's avatar
LDOUBLEV committed
56
    def get_image_info_list(self, file_list, ratio_list):
dyning's avatar
dyning committed
57
58
        if isinstance(file_list, str):
            file_list = [file_list]
59
60
        data_lines = []
        for idx, file in enumerate(file_list):
dyning's avatar
dyning committed
61
62
            with open(file, "rb") as f:
                lines = f.readlines()
63
64
65
66
                if self.mode == "train" or ratio_list[idx] < 1.0:
                    random.seed(self.seed)
                    lines = random.sample(lines,
                                          round(len(lines) * ratio_list[idx]))
67
68
                data_lines.extend(lines)
        return data_lines
dyning's avatar
dyning committed
69
70

    def shuffle_data_random(self):
71
72
        random.seed(self.seed)
        random.shuffle(self.data_lines)
dyning's avatar
dyning committed
73
        return
dyning's avatar
dyning committed
74

75
76
77
78
79
80
81
82
83
84
    def _try_parse_filename_list(self, file_name):
        # multiple images -> one gt label
        if len(file_name) > 0 and file_name[0] == "[":
            try:
                info = json.loads(file_name)
                file_name = random.choice(info)
            except:
                pass
        return file_name

WenmuZhou's avatar
WenmuZhou committed
85
86
87
88
89
90
    def get_ext_data(self):
        ext_data_num = 0
        for op in self.ops:
            if hasattr(op, 'ext_data_num'):
                ext_data_num = getattr(op, 'ext_data_num')
                break
andyjpaddle's avatar
andyjpaddle committed
91
        load_data_ops = self.ops[:self.ext_op_transform_idx]
WenmuZhou's avatar
WenmuZhou committed
92
93
94
95
96
97
98
99
100
        ext_data = []

        while len(ext_data) < ext_data_num:
            file_idx = self.data_idx_order_list[np.random.randint(self.__len__(
            ))]
            data_line = self.data_lines[file_idx]
            data_line = data_line.decode('utf-8')
            substr = data_line.strip("\n").split(self.delimiter)
            file_name = substr[0]
101
            file_name = self._try_parse_filename_list(file_name)
WenmuZhou's avatar
WenmuZhou committed
102
103
104
105
106
107
108
109
110
            label = substr[1]
            img_path = os.path.join(self.data_dir, file_name)
            data = {'img_path': img_path, 'label': label}
            if not os.path.exists(img_path):
                continue
            with open(data['img_path'], 'rb') as f:
                img = f.read()
                data['image'] = img
            data = transform(data, load_data_ops)
111

andyjpaddle's avatar
andyjpaddle committed
112
            if data is None:
WenmuZhou's avatar
WenmuZhou committed
113
                continue
andyjpaddle's avatar
andyjpaddle committed
114
115
116
            if 'polys' in data.keys():
                if data['polys'].shape[1] != 4:
                    continue
WenmuZhou's avatar
WenmuZhou committed
117
118
119
            ext_data.append(data)
        return ext_data

dyning's avatar
dyning committed
120
    def __getitem__(self, idx):
121
        file_idx = self.data_idx_order_list[idx]
LDOUBLEV's avatar
LDOUBLEV committed
122
        data_line = self.data_lines[file_idx]
123
        try:
LDOUBLEV's avatar
LDOUBLEV committed
124
125
126
            data_line = data_line.decode('utf-8')
            substr = data_line.strip("\n").split(self.delimiter)
            file_name = substr[0]
127
            file_name = self._try_parse_filename_list(file_name)
LDOUBLEV's avatar
LDOUBLEV committed
128
129
130
131
132
            label = substr[1]
            img_path = os.path.join(self.data_dir, file_name)
            data = {'img_path': img_path, 'label': label}
            if not os.path.exists(img_path):
                raise Exception("{} does not exist!".format(img_path))
133
134
135
            with open(data['img_path'], 'rb') as f:
                img = f.read()
                data['image'] = img
WenmuZhou's avatar
WenmuZhou committed
136
            data['ext_data'] = self.get_ext_data()
137
            outs = transform(data, self.ops)
138
        except:
139
            self.logger.error(
LDOUBLEV's avatar
LDOUBLEV committed
140
                "When parsing line {}, error happened with msg: {}".format(
141
                    data_line, traceback.format_exc()))
142
            outs = None
dyning's avatar
dyning committed
143
        if outs is None:
144
145
146
147
            # during evaluation, we should fix the idx to get same results for many times of evaluation.
            rnd_idx = np.random.randint(self.__len__(
            )) if self.mode == "train" else (idx + 1) % self.__len__()
            return self.__getitem__(rnd_idx)
dyning's avatar
dyning committed
148
149
150
151
        return outs

    def __len__(self):
        return len(self.data_idx_order_list)