simple_dataset.py 4.3 KB
Newer Older
D
dyning 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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
from paddle.io import Dataset

from .imaug import transform, create_operators
D
dyning 已提交
20

D
dyning 已提交
21 22

class SimpleDataSet(Dataset):
D
dyning 已提交
23
    def __init__(self, config, mode, logger):
D
dyning 已提交
24
        super(SimpleDataSet, self).__init__()
25
        self.logger = logger
D
dyning 已提交
26

D
dyning 已提交
27 28 29
        global_config = config['Global']
        dataset_config = config[mode]['dataset']
        loader_config = config[mode]['loader']
L
LDOUBLEV 已提交
30 31 32 33
        if 'data_num_per_epoch' in loader_config.keys():
            data_num_per_epoch = loader_config['data_num_per_epoch']
        else:
            data_num_per_epoch = None
D
dyning 已提交
34

D
dyning 已提交
35 36 37
        self.delimiter = dataset_config.get('delimiter', '\t')
        label_file_list = dataset_config.pop('label_file_list')
        data_source_num = len(label_file_list)
38 39 40
        ratio_list = dataset_config.get("ratio_list", [1.0])
        if isinstance(ratio_list, (float, int)):
            ratio_list = [float(ratio_list)] * len(data_source_num)
D
dyning 已提交
41 42 43 44

        assert len(
            ratio_list
        ) == data_source_num, "The length of ratio_list should be the same as the file_list."
D
dyning 已提交
45 46
        self.data_dir = dataset_config['data_dir']
        self.do_shuffle = loader_config['shuffle']
D
dyning 已提交
47

D
dyning 已提交
48
        logger.info("Initialize indexs of datasets:%s" % label_file_list)
L
LDOUBLEV 已提交
49 50
        self.data_lines = self.get_image_info_list(label_file_list, ratio_list,
                                                   data_num_per_epoch)
51 52 53
        self.data_idx_order_list = list(range(len(self.data_lines)))
        if mode.lower() == "train":
            self.shuffle_data_random()
D
dyning 已提交
54 55
        self.ops = create_operators(dataset_config['transforms'], global_config)

L
LDOUBLEV 已提交
56 57 58 59
    def _sample_dataset(self, datas, sample_ratio, data_num_per_epoch=None):
        sample_num = round(len(datas) * sample_ratio)

        if data_num_per_epoch is not None:
L
LDOUBLEV 已提交
60
            sample_num = int(data_num_per_epoch * sample_ratio)
L
LDOUBLEV 已提交
61

L
LDOUBLEV 已提交
62
        nums, rem = int(sample_num // len(datas)), int(sample_num % len(datas))
L
LDOUBLEV 已提交
63 64 65 66 67 68
        return list(datas) * nums + random.sample(datas, rem)

    def get_image_info_list(self,
                            file_list,
                            ratio_list,
                            data_num_per_epoch=None):
D
dyning 已提交
69 70
        if isinstance(file_list, str):
            file_list = [file_list]
71 72
        data_lines = []
        for idx, file in enumerate(file_list):
D
dyning 已提交
73 74
            with open(file, "rb") as f:
                lines = f.readlines()
L
LDOUBLEV 已提交
75 76
                lines = self._sample_dataset(lines, ratio_list[idx],
                                             data_num_per_epoch)
77 78
                data_lines.extend(lines)
        return data_lines
D
dyning 已提交
79 80 81

    def shuffle_data_random(self):
        if self.do_shuffle:
82
            random.shuffle(self.data_lines)
D
dyning 已提交
83
        return
D
dyning 已提交
84

D
dyning 已提交
85
    def __getitem__(self, idx):
86 87
        file_idx = self.data_idx_order_list[idx]
        data_line = self.data_lines[file_idx]
88 89 90
        try:
            data_line = data_line.decode('utf-8')
            substr = data_line.strip("\n").split(self.delimiter)
L
littletomatodonkey 已提交
91 92
            file_name = substr[0]
            label = substr[1]
93 94
            img_path = os.path.join(self.data_dir, file_name)
            data = {'img_path': img_path, 'label': label}
L
LDOUBLEV 已提交
95 96
            if not os.path.exists(img_path):
                raise Exception("{} does not exist!".format(img_path))
97 98 99 100 101 102 103 104 105
            with open(data['img_path'], 'rb') as f:
                img = f.read()
                data['image'] = img
            outs = transform(data, self.ops)
        except Exception as e:
            self.logger.error(
                "When parsing line {}, error happened with msg: {}".format(
                    data_line, e))
            outs = None
D
dyning 已提交
106 107 108 109 110 111
        if outs is None:
            return self.__getitem__(np.random.randint(self.__len__()))
        return outs

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