paired_dataset.py 2.1 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7
import cv2
import paddle
import os.path
from .base_dataset import BaseDataset, get_params, get_transform
from .image_folder import make_dataset

from .builder import DATASETS
L
LielinJiang 已提交
8
from .transforms.builder import build_transforms
L
LielinJiang 已提交
9 10 11


@DATASETS.register()
L
LielinJiang 已提交
12
class PairedDataset(BaseDataset):
L
LielinJiang 已提交
13 14
    """A dataset class for paired image dataset.
    """
L
LielinJiang 已提交
15
    def __init__(self, cfg):
L
LielinJiang 已提交
16 17 18
        """Initialize this dataset class.

        Args:
L
LielinJiang 已提交
19
            cfg (dict): configs of datasets.
L
LielinJiang 已提交
20
        """
L
LielinJiang 已提交
21
        BaseDataset.__init__(self, cfg)
L
LielinJiang 已提交
22 23 24 25
        self.dir_AB = os.path.join(cfg.dataroot,
                                   cfg.phase)  # get the image directory
        self.AB_paths = sorted(make_dataset(
            self.dir_AB, cfg.max_dataset_size))  # get image paths
L
LielinJiang 已提交
26

L
LielinJiang 已提交
27 28
        self.input_nc = self.cfg.output_nc if self.cfg.direction == 'BtoA' else self.cfg.input_nc
        self.output_nc = self.cfg.input_nc if self.cfg.direction == 'BtoA' else self.cfg.output_nc
L
LielinJiang 已提交
29
        self.transforms = build_transforms(cfg.transforms)
L
LielinJiang 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

    def __getitem__(self, index):
        """Return a data point and its metadata information.

        Parameters:
            index - - a random integer for data indexing

        Returns a dictionary that contains A, B, A_paths and B_paths
            A (tensor) - - an image in the input domain
            B (tensor) - - its corresponding image in the target domain
            A_paths (str) - - image paths
            B_paths (str) - - image paths (same as A_paths)
        """
        # read a image given a random integer index
        AB_path = self.AB_paths[index]
L
LielinJiang 已提交
45
        AB = cv2.cvtColor(cv2.imread(AB_path), cv2.COLOR_BGR2RGB)
L
LielinJiang 已提交
46 47 48 49 50 51 52 53 54 55

        # split AB image into A and B
        h, w = AB.shape[:2]
        # w, h = AB.size
        w2 = int(w / 2)

        A = AB[:h, :w2, :]
        B = AB[:h, w2:, :]

        # apply the same transform to both A and B
L
LielinJiang 已提交
56
        A, B = self.transforms((A, B))
L
LielinJiang 已提交
57

L
LielinJiang 已提交
58
        return {'A': A, 'B': B, 'A_paths': AB_path, 'B_paths': AB_path}
L
LielinJiang 已提交
59 60 61 62

    def __len__(self):
        """Return the total number of images in the dataset."""
        return len(self.AB_paths)