folder.py 15.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

import os
import sys
17
from PIL import Image
18

19
import paddle
20
from paddle.io import Dataset
L
LielinJiang 已提交
21
from paddle.utils import try_import
22

23
__all__ = []
24 25 26 27 28 29 30


def has_valid_extension(filename, extensions):
    """Checks if a file is a vilid extension.

    Args:
        filename (str): path to a file
31
        extensions (list[str]|tuple[str]): extensions to consider
32 33 34 35

    Returns:
        bool: True if the filename ends with one of given extensions
    """
36 37 38
    assert isinstance(
        extensions, (list, tuple)
    ), "`extensions` must be list or tuple."
39
    extensions = tuple([x.lower() for x in extensions])
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    return filename.lower().endswith(extensions)


def make_dataset(dir, class_to_idx, extensions, is_valid_file=None):
    images = []
    dir = os.path.expanduser(dir)

    if extensions is not None:

        def is_valid_file(x):
            return has_valid_extension(x, extensions)

    for target in sorted(class_to_idx.keys()):
        d = os.path.join(dir, target)
        if not os.path.isdir(d):
            continue
        for root, _, fnames in sorted(os.walk(d, followlinks=True)):
            for fname in sorted(fnames):
                path = os.path.join(root, fname)
                if is_valid_file(path):
                    item = (path, class_to_idx[target])
                    images.append(item)

    return images


class DatasetFolder(Dataset):
    """A generic data loader where the samples are arranged in this way:

69 70
    .. code-block:: text

71 72 73 74 75 76 77 78 79
        root/class_a/1.ext
        root/class_a/2.ext
        root/class_a/3.ext

        root/class_b/123.ext
        root/class_b/456.ext
        root/class_b/789.ext

    Args:
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        root (str): Root directory path.
        loader (Callable, optional): A function to load a sample given its path. Default: None.
        extensions (list[str]|tuple[str], optional): A list of allowed extensions.
            Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
            If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
            '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
        transform (Callable, optional): A function/transform that takes in
            a sample and returns a transformed version. Default: None.
        is_valid_file (Callable, optional): A function that takes path of a file
            and check if the file is a valid file. Both :attr:`extensions` and
            :attr:`is_valid_file` should not be passed. Default: None.

    Returns:
        :ref:`api_paddle_io_Dataset`. An instance of DatasetFolder.

    Attributes:
        classes (list[str]): List of the class names.
        class_to_idx (dict[str, int]): Dict with items (class_name, class_index).
        samples (list[tuple[str, int]]): List of (sample_path, class_index) tuples.
        targets (list[int]): The class_index value for each image in the dataset.
100 101 102 103 104 105

    Example:

        .. code-block:: python

            import shutil
106 107
            import tempfile
            import cv2
108
            import numpy as np
109 110
            import paddle.vision.transforms as T
            from pathlib import Path
111
            from paddle.vision.datasets import DatasetFolder
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

            def make_fake_file(img_path: str):
                if img_path.endswith((".jpg", ".png", ".jpeg")):
                    fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
                    cv2.imwrite(img_path, fake_img)
                elif img_path.endswith(".txt"):
                    with open(img_path, "w") as f:
                        f.write("This is a fake file.")

            def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
                root = Path(root)
                root.mkdir(parents=True, exist_ok=True)
                for subpath in directory_hierarchy:
                    if isinstance(subpath, str):
                        filepath = root / subpath
                        file_maker(str(filepath))
                    else:
                        dirname = list(subpath.keys())[0]
                        make_directory(root / dirname, subpath[dirname])

            directory_hirerarchy = [
                {"class_0": [
                    "abc.jpg",
                    "def.png"]},
                {"class_1": [
                    "ghi.jpeg",
                    "jkl.png",
                    {"mno": [
                        "pqr.jpeg",
                        "stu.jpg"]}]},
                "this_will_be_ignored.txt",
            ]

            # You can replace this with any directory to explore the structure
            # of generated data. e.g. fake_data_dir = "./temp_dir"
            fake_data_dir = tempfile.mkdtemp()
            make_directory(fake_data_dir, directory_hirerarchy)
            data_folder_1 = DatasetFolder(fake_data_dir)
            print(data_folder_1.classes)
            # ['class_0', 'class_1']
            print(data_folder_1.class_to_idx)
            # {'class_0': 0, 'class_1': 1}
            print(data_folder_1.samples)
            # [('./temp_dir/class_0/abc.jpg', 0), ('./temp_dir/class_0/def.png', 0),
            #  ('./temp_dir/class_1/ghi.jpeg', 1), ('./temp_dir/class_1/jkl.png', 1),
            #  ('./temp_dir/class_1/mno/pqr.jpeg', 1), ('./temp_dir/class_1/mno/stu.jpg', 1)]
            print(data_folder_1.targets)
            # [0, 0, 1, 1, 1, 1]
            print(len(data_folder_1))
            # 6

            for i in range(len(data_folder_1)):
                img, label = data_folder_1[i]
                # do something with img and label
                print(type(img), img.size, label)
                # <class 'PIL.Image.Image'> (32, 32) 0


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

            data_folder_2 = DatasetFolder(
                fake_data_dir,
                loader=lambda x: cv2.imread(x),  # load image with OpenCV
                extensions=(".jpg",),  # only load *.jpg files
                transform=transform,  # apply transform to every image
            )

            print([img_path for img_path, label in data_folder_2.samples])
            # ['./temp_dir/class_0/abc.jpg', './temp_dir/class_1/mno/stu.jpg']
            print(len(data_folder_2))
            # 2

            for img, label in iter(data_folder_2):
                # do something with img and label
                print(type(img), img.shape, label)
                # <class 'paddle.Tensor'> [3, 64, 64] 0

            shutil.rmtree(fake_data_dir)
201 202
    """

203 204 205 206 207 208 209 210
    def __init__(
        self,
        root,
        loader=None,
        extensions=None,
        transform=None,
        is_valid_file=None,
    ):
211 212 213 214 215
        self.root = root
        self.transform = transform
        if extensions is None:
            extensions = IMG_EXTENSIONS
        classes, class_to_idx = self._find_classes(self.root)
216 217 218
        samples = make_dataset(
            self.root, class_to_idx, extensions, is_valid_file
        )
219
        if len(samples) == 0:
220 221 222 223 224 225
            raise (
                RuntimeError(
                    "Found 0 directories in subfolders of: " + self.root + "\n"
                    "Supported extensions are: " + ",".join(extensions)
                )
            )
226

227
        self.loader = default_loader if loader is None else loader
228 229 230 231 232 233 234
        self.extensions = extensions

        self.classes = classes
        self.class_to_idx = class_to_idx
        self.samples = samples
        self.targets = [s[1] for s in samples]

235 236
        self.dtype = paddle.get_default_dtype()

237 238 239 240 241 242 243 244
    def _find_classes(self, dir):
        """
        Finds the class folders in a dataset.

        Args:
            dir (string): Root directory path.

        Returns:
245
            tuple: (classes, class_to_idx) where classes are relative to (dir),
246 247 248 249 250 251 252 253
                    and class_to_idx is a dictionary.

        """
        if sys.version_info >= (3, 5):
            # Faster and available in Python 3.5 and above
            classes = [d.name for d in os.scandir(dir) if d.is_dir()]
        else:
            classes = [
254 255
                d
                for d in os.listdir(dir)
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                if os.path.isdir(os.path.join(dir, d))
            ]
        classes.sort()
        class_to_idx = {classes[i]: i for i in range(len(classes))}
        return classes, class_to_idx

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        """
        path, target = self.samples[index]
        sample = self.loader(path)
        if self.transform is not None:
            sample = self.transform(sample)

        return sample, target

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


281 282 283 284 285 286 287 288 289 290 291
IMG_EXTENSIONS = (
    '.jpg',
    '.jpeg',
    '.png',
    '.ppm',
    '.bmp',
    '.pgm',
    '.tif',
    '.tiff',
    '.webp',
)
292 293


294 295 296 297 298 299
def pil_loader(path):
    with open(path, 'rb') as f:
        img = Image.open(f)
        return img.convert('RGB')


300
def cv2_loader(path):
L
LielinJiang 已提交
301
    cv2 = try_import('cv2')
302 303 304 305 306
    return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)


def default_loader(path):
    from paddle.vision import get_image_backend
307

308 309 310 311
    if get_image_backend() == 'cv2':
        return cv2_loader(path)
    else:
        return pil_loader(path)
312 313 314 315 316


class ImageFolder(Dataset):
    """A generic data loader where the samples are arranged in this way:

317 318
    .. code-block:: text

319 320 321 322 323
        root/1.ext
        root/2.ext
        root/sub_dir/3.ext

    Args:
324 325
        root (str): Root directory path.
        loader (Callable, optional): A function to load a sample given its path. Default: None.
326
        extensions (list[str]|tuple[str], optional): A list of allowed extensions.
327 328 329 330 331 332 333 334 335 336 337
            Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
            If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
            '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
        transform (Callable, optional): A function/transform that takes in
            a sample and returns a transformed version. Default: None.
        is_valid_file (Callable, optional): A function that takes path of a file
            and check if the file is a valid file. Both :attr:`extensions` and
            :attr:`is_valid_file` should not be passed. Default: None.

    Returns:
        :ref:`api_paddle_io_Dataset`. An instance of ImageFolder.
338

339 340
    Attributes:
        samples (list[str]): List of sample path.
341 342 343 344 345 346

    Example:

        .. code-block:: python

            import shutil
347 348
            import tempfile
            import cv2
349
            import numpy as np
350 351
            import paddle.vision.transforms as T
            from pathlib import Path
352
            from paddle.vision.datasets import ImageFolder
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

            def make_fake_file(img_path: str):
                if img_path.endswith((".jpg", ".png", ".jpeg")):
                    fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
                    cv2.imwrite(img_path, fake_img)
                elif img_path.endswith(".txt"):
                    with open(img_path, "w") as f:
                        f.write("This is a fake file.")

            def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
                root = Path(root)
                root.mkdir(parents=True, exist_ok=True)
                for subpath in directory_hierarchy:
                    if isinstance(subpath, str):
                        filepath = root / subpath
                        file_maker(str(filepath))
                    else:
                        dirname = list(subpath.keys())[0]
                        make_directory(root / dirname, subpath[dirname])

            directory_hirerarchy = [
                "abc.jpg",
                "def.png",
                {"ghi": [
                    "jkl.jpeg",
                    {"mno": [
                        "pqr.jpg"]}]},
                "this_will_be_ignored.txt",
            ]

            # You can replace this with any directory to explore the structure
            # of generated data. e.g. fake_data_dir = "./temp_dir"
            fake_data_dir = tempfile.mkdtemp()
            make_directory(fake_data_dir, directory_hirerarchy)
            image_folder_1 = ImageFolder(fake_data_dir)
            print(image_folder_1.samples)
            # ['./temp_dir/abc.jpg', './temp_dir/def.png',
            #  './temp_dir/ghi/jkl.jpeg', './temp_dir/ghi/mno/pqr.jpg']
            print(len(image_folder_1))
            # 4

            for i in range(len(image_folder_1)):
                (img,) = image_folder_1[i]
                # do something with img
                print(type(img), img.size)
                # <class 'PIL.Image.Image'> (32, 32)


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

            image_folder_2 = ImageFolder(
                fake_data_dir,
                loader=lambda x: cv2.imread(x),  # load image with OpenCV
                extensions=(".jpg",),  # only load *.jpg files
                transform=transform,  # apply transform to every image
            )

            print(image_folder_2.samples)
            # ['./temp_dir/abc.jpg', './temp_dir/ghi/mno/pqr.jpg']
            print(len(image_folder_2))
            # 2

            for (img,) in iter(image_folder_2):
                # do something with img
                print(type(img), img.shape)
                # <class 'paddle.Tensor'> [3, 64, 64]

            shutil.rmtree(fake_data_dir)
432 433 434 435 436 437 438 439 440 441
    """

    def __init__(
        self,
        root,
        loader=None,
        extensions=None,
        transform=None,
        is_valid_file=None,
    ):
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        self.root = root
        if extensions is None:
            extensions = IMG_EXTENSIONS

        samples = []
        path = os.path.expanduser(root)

        if extensions is not None:

            def is_valid_file(x):
                return has_valid_extension(x, extensions)

        for root, _, fnames in sorted(os.walk(path, followlinks=True)):
            for fname in sorted(fnames):
                f = os.path.join(root, fname)
                if is_valid_file(f):
                    samples.append(f)

        if len(samples) == 0:
461 462 463 464 465 466
            raise (
                RuntimeError(
                    "Found 0 files in subfolders of: " + self.root + "\n"
                    "Supported extensions are: " + ",".join(extensions)
                )
            )
467

468
        self.loader = default_loader if loader is None else loader
469 470 471 472 473 474 475 476 477 478
        self.extensions = extensions
        self.samples = samples
        self.transform = transform

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
L
LielinJiang 已提交
479
            sample of specific index.
480 481 482 483 484 485 486 487 488
        """
        path = self.samples[index]
        sample = self.loader(path)
        if self.transform is not None:
            sample = self.transform(sample)
        return [sample]

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