simple_source.py 3.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

# function:
#    interface to load data from txt file.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import numpy as np
import copy
from ..dataset import Dataset


class SimpleSource(Dataset):
    """
    Load image files for testing purpose

    Args:
K
Kaipeng Deng 已提交
33
        images (list): list of path of images
34 35 36 37 38
        samples (int): number of samples to load, -1 means all
        load_img (bool): should images be loaded
    """

    def __init__(self,
K
Kaipeng Deng 已提交
39
                 images=[],
40 41 42 43 44
                 samples=-1,
                 load_img=True,
                 **kwargs):
        super(SimpleSource, self).__init__()
        self._epoch = -1
K
Kaipeng Deng 已提交
45 46 47 48 49
        for image in images:
            assert image != '' and os.path.isfile(image), \
                    "Image {} not found".format(image)
        self._images = images
        self._fname = None
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        self._simple = None
        self._pos = -1
        self._drained = False
        self._samples = samples
        self._load_img = load_img
        self._imid2path = {}

    def next(self):
        if self._epoch < 0:
            self.reset()

        if self._pos >= self.size():
            self._drained = True
            raise StopIteration("no more data in " + str(self))
        else:
            sample = copy.deepcopy(self._simple[self._pos])
            if self._load_img:
                sample['image'] = self._load_image(sample['im_file'])
K
Kaipeng Deng 已提交
68

69 70 71 72 73 74
            self._pos += 1
            return sample

    def _load(self):
        ct = 0
        records = []
K
Kaipeng Deng 已提交
75 76 77 78 79 80 81 82
        for image in self._images:
            if self._samples > 0 and ct >= self._samples:
                break
            rec = {'im_id': np.array([ct]), 'im_file': image}
            self._imid2path[ct] = image
            ct += 1
            records.append(rec)
        assert len(records) > 0, "no image file found"
83 84 85
        return records

    def _load_image(self, where):
K
Kaipeng Deng 已提交
86
        with open(where, 'rb') as f:
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
            return f.read()

    def reset(self):
        if self._simple is None:
            self._simple = self._load()

        if self._epoch < 0:
            self._epoch = 0
        else:
            self._epoch += 1

        self._pos = 0
        self._drained = False

    def size(self):
        return len(self._simple)

    def drained(self):
        assert self._epoch >= 0, "the first epoch has not started yet"
        return self._pos >= self.size()

    def epoch_id(self):
        return self._epoch

    def get_imid2path(self):
        """return image id to image path map"""
        return self._imid2path