pgnet_dataset.py 4.03 KB
Newer Older
1
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
Jethong's avatar
Jethong committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# 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
from paddle.io import Dataset
from .imaug import transform, create_operators
import random


21
class PGDataSet(Dataset):
Jethong's avatar
Jethong committed
22
    def __init__(self, config, mode, logger, seed=None):
23
        super(PGDataSet, self).__init__()
Jethong's avatar
Jethong committed
24
25

        self.logger = logger
Jethong's avatar
Jethong committed
26
        self.seed = seed
Jethong's avatar
Jethong committed
27
        self.mode = mode
Jethong's avatar
Jethong committed
28
29
30
31
        global_config = config['Global']
        dataset_config = config[mode]['dataset']
        loader_config = config[mode]['loader']

Jethong's avatar
Jethong committed
32
        self.delimiter = dataset_config.get('delimiter', '\t')
Jethong's avatar
Jethong committed
33
34
35
36
37
38
39
40
        label_file_list = dataset_config.pop('label_file_list')
        data_source_num = len(label_file_list)
        ratio_list = dataset_config.get("ratio_list", [1.0])
        if isinstance(ratio_list, (float, int)):
            ratio_list = [float(ratio_list)] * int(data_source_num)
        assert len(
            ratio_list
        ) == data_source_num, "The length of ratio_list should be the same as the file_list."
Jethong's avatar
Jethong committed
41
        self.data_dir = dataset_config['data_dir']
Jethong's avatar
Jethong committed
42
43
44
        self.do_shuffle = loader_config['shuffle']

        logger.info("Initialize indexs of datasets:%s" % label_file_list)
Jethong's avatar
Jethong committed
45
        self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
Jethong's avatar
Jethong committed
46
47
48
49
50
51
52
53
        self.data_idx_order_list = list(range(len(self.data_lines)))
        if mode.lower() == "train":
            self.shuffle_data_random()

        self.ops = create_operators(dataset_config['transforms'], global_config)

    def shuffle_data_random(self):
        if self.do_shuffle:
Jethong's avatar
Jethong committed
54
            random.seed(self.seed)
Jethong's avatar
Jethong committed
55
56
57
            random.shuffle(self.data_lines)
        return

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

    def __getitem__(self, idx):
        file_idx = self.data_idx_order_list[idx]
Jethong's avatar
Jethong committed
74
        data_line = self.data_lines[file_idx]
Jethong's avatar
Jethong committed
75
        img_id = 0
Jethong's avatar
Jethong committed
76
        try:
Jethong's avatar
Jethong committed
77
78
79
80
81
            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)
Jethong's avatar
Jethong committed
82
            if self.mode.lower() == 'eval':
Jethong's avatar
Jethong committed
83
84
85
86
                try:
                    img_id = int(data_line.split(".")[0][7:])
                except:
                    img_id = 0
Jethong's avatar
Jethong committed
87
88
89
            data = {'img_path': img_path, 'label': label, 'img_id': img_id}
            if not os.path.exists(img_path):
                raise Exception("{} does not exist!".format(img_path))
Jethong's avatar
Jethong committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            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(
                    self.data_idx_order_list[idx], e))
            outs = None
        if outs is None:
            return self.__getitem__(np.random.randint(self.__len__()))
        return outs

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