voc2012.py 6.3 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   Copyright (c) 2020 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.

from __future__ import print_function

import io
import tarfile
import numpy as np
from PIL import Image

22
import paddle
K
Kaipeng Deng 已提交
23
from paddle.io import Dataset
24
from paddle.dataset.common import _check_exists_and_download
K
Kaipeng Deng 已提交
25

26
__all__ = []
K
Kaipeng Deng 已提交
27

L
LielinJiang 已提交
28
VOC_URL = 'https://dataset.bj.bcebos.com/voc/VOCtrainval_11-May-2012.tar'
K
Kaipeng Deng 已提交
29

30
VOC_MD5 = '6cd6e144f989b92b3379bac3b3de84fd'
K
Kaipeng Deng 已提交
31 32 33 34 35 36 37 38 39 40 41
SET_FILE = 'VOCdevkit/VOC2012/ImageSets/Segmentation/{}.txt'
DATA_FILE = 'VOCdevkit/VOC2012/JPEGImages/{}.jpg'
LABEL_FILE = 'VOCdevkit/VOC2012/SegmentationClass/{}.png'

CACHE_DIR = 'voc2012'

MODE_FLAG_MAP = {'train': 'trainval', 'test': 'train', 'valid': "val"}


class VOC2012(Dataset):
    """
42
    Implementation of `VOC2012 <http://host.robots.ox.ac.uk/pascal/VOC/voc2012/>`_ dataset.
L
LielinJiang 已提交
43

K
Kaipeng Deng 已提交
44
    Args:
45 46 47 48 49 50 51 52
        data_file (str, optional): Path to data file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/voc2012.
        mode (str, optional): Either train or test mode. Default 'train'.
        transform (Callable, optional): Transform to perform on image, None for no transform. Default: None.
        download (bool, optional): Download dataset automatically if :attr:`data_file` is None. Default: True.
        backend (str, optional): Specifies which type of image to be returned:
            PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
            If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_vision_image_get_image_backend>`,
53
            default backend is 'pil'. Default: None.
K
Kaipeng Deng 已提交
54

55 56 57
    Returns:
        :ref:`api_paddle_io_Dataset`. An instance of VOC2012 dataset.

K
Kaipeng Deng 已提交
58 59 60 61
    Examples:

        .. code-block:: python

62 63
            import itertools
            import paddle.vision.transforms as T
64
            from paddle.vision.datasets import VOC2012
K
Kaipeng Deng 已提交
65 66


67 68 69 70 71 72 73 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 104
            voc2012 = VOC2012()
            print(len(voc2012))
            # 2913

            for i in range(5):  # only show first 5 images
                img, label = voc2012[i]
                # do something with img and label
                print(type(img), img.size)
                # <class 'PIL.JpegImagePlugin.JpegImageFile'> (500, 281)
                print(type(label), label.size)
                # <class 'PIL.PngImagePlugin.PngImageFile'> (500, 281)


            transform = T.Compose(
                [
                    T.ToTensor(),
                    T.Normalize(
                        mean=[0.5, 0.5, 0.5],
                        std=[0.5, 0.5, 0.5],
                        to_rgb=True,
                    ),
                ]
            )

            voc2012_test = VOC2012(
                mode="test",
                transform=transform,  # apply transform to every image
                backend="cv2",  # use OpenCV as image transform backend
            )
            print(len(voc2012_test))
            # 1464

            for img, label in itertools.islice(iter(voc2012_test), 5):  # only show first 5 images
                # do something with img and label
                print(type(img), img.shape)
                # <class 'paddle.Tensor'> [3, 281, 500]
                print(type(label), label.shape)
                # <class 'numpy.ndarray'> (281, 500)
K
Kaipeng Deng 已提交
105 106 107 108 109 110
    """

    def __init__(self,
                 data_file=None,
                 mode='train',
                 transform=None,
111 112
                 download=True,
                 backend=None):
K
Kaipeng Deng 已提交
113 114
        assert mode.lower() in ['train', 'valid', 'test'], \
            "mode should be 'train', 'valid' or 'test', but got {}".format(mode)
115 116 117 118 119

        if backend is None:
            backend = paddle.vision.get_image_backend()
        if backend not in ['pil', 'cv2']:
            raise ValueError(
120 121
                "Expected backend are one of ['pil', 'cv2'], but got {}".format(
                    backend))
122 123
        self.backend = backend

K
Kaipeng Deng 已提交
124 125 126 127 128
        self.flag = MODE_FLAG_MAP[mode.lower()]

        self.data_file = data_file
        if self.data_file is None:
            assert download, "data_file is not set and downloading automatically is disabled"
129 130 131
            self.data_file = _check_exists_and_download(data_file, VOC_URL,
                                                        VOC_MD5, CACHE_DIR,
                                                        download)
K
Kaipeng Deng 已提交
132 133 134 135 136
        self.transform = transform

        # read dataset into memory
        self._load_anno()

137 138
        self.dtype = paddle.get_default_dtype()

K
Kaipeng Deng 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    def _load_anno(self):
        self.name2mem = {}
        self.data_tar = tarfile.open(self.data_file)
        for ele in self.data_tar.getmembers():
            self.name2mem[ele.name] = ele

        set_file = SET_FILE.format(self.flag)
        sets = self.data_tar.extractfile(self.name2mem[set_file])

        self.data = []
        self.labels = []

        for line in sets:
            line = line.strip()
            data = DATA_FILE.format(line.decode('utf-8'))
            label = LABEL_FILE.format(line.decode('utf-8'))
            self.data.append(data)
            self.labels.append(label)

    def __getitem__(self, idx):
        data_file = self.data[idx]
        label_file = self.labels[idx]

        data = self.data_tar.extractfile(self.name2mem[data_file]).read()
        label = self.data_tar.extractfile(self.name2mem[label_file]).read()
        data = Image.open(io.BytesIO(data))
        label = Image.open(io.BytesIO(label))
166 167 168 169 170

        if self.backend == 'cv2':
            data = np.array(data)
            label = np.array(label)

K
Kaipeng Deng 已提交
171 172
        if self.transform is not None:
            data = self.transform(data)
173 174 175 176 177

        if self.backend == 'cv2':
            return data.astype(self.dtype), label.astype(self.dtype)

        return data, label
K
Kaipeng Deng 已提交
178 179 180

    def __len__(self):
        return len(self.data)
181 182 183 184

    def __del__(self):
        if self.data_tar:
            self.data_tar.close()