simple_dataset.py 5.24 KB
Newer Older
dyning's avatar
dyning committed
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 numpy as np
import os
import random
WenmuZhou's avatar
WenmuZhou committed
17
import traceback
dyning's avatar
dyning committed
18
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):
tink2123's avatar
tink2123 committed
25
        print("===== simpledataset ========")
dyning's avatar
dyning committed
26
        super(SimpleDataSet, self).__init__()
27
        self.logger = logger
28
        self.mode = mode.lower()
dyning's avatar
dyning committed
29

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

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

        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
44
45
        self.data_dir = dataset_config['data_dir']
        self.do_shuffle = loader_config['shuffle']
dyning's avatar
dyning committed
46

47
        self.seed = seed
dyning's avatar
dyning committed
48
        logger.info("Initialize indexs of datasets:%s" % label_file_list)
LDOUBLEV's avatar
LDOUBLEV committed
49
        self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
50
        self.data_idx_order_list = list(range(len(self.data_lines)))
51
        if self.mode == "train" and self.do_shuffle:
52
            self.shuffle_data_random()
dyning's avatar
dyning committed
53
54
        self.ops = create_operators(dataset_config['transforms'], global_config)

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

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

WenmuZhou's avatar
WenmuZhou committed
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
    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
        load_data_ops = self.ops[:2]
        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]
            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)
            if data is None:
                continue
            ext_data.append(data)
        return ext_data

dyning's avatar
dyning committed
104
    def __getitem__(self, idx):
105
106
        file_idx = self.data_idx_order_list[idx]
        data_line = self.data_lines[file_idx]
107
108
        try:
            data_line = data_line.decode('utf-8')
109
            substr = data_line.strip("\n").strip("\r").split(self.delimiter)
littletomatodonkey's avatar
littletomatodonkey committed
110
111
            file_name = substr[0]
            label = substr[1]
112
113
            img_path = os.path.join(self.data_dir, file_name)
            data = {'img_path': img_path, 'label': label}
LDOUBLEV's avatar
LDOUBLEV committed
114
115
            if not os.path.exists(img_path):
                raise Exception("{} does not exist!".format(img_path))
116
117
118
            with open(data['img_path'], 'rb') as f:
                img = f.read()
                data['image'] = img
WenmuZhou's avatar
WenmuZhou committed
119
            data['ext_data'] = self.get_ext_data()
120
            outs = transform(data, self.ops)
WenmuZhou's avatar
WenmuZhou committed
121
        except:
WenmuZhou's avatar
WenmuZhou committed
122
            error_meg = traceback.format_exc()
123
124
            self.logger.error(
                "When parsing line {}, error happened with msg: {}".format(
WenmuZhou's avatar
WenmuZhou committed
125
                    data_line, error_meg))
126
            outs = None
dyning's avatar
dyning committed
127
        if outs is None:
128
129
130
131
            # 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
132
133
134
135
        return outs

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