Path: blob/master/gfpgan/data/ffhq_degradation_dataset.py
884 views
import cv21import math2import numpy as np3import os.path as osp4import torch5import torch.utils.data as data6from basicsr.data import degradations as degradations7from basicsr.data.data_util import paths_from_folder8from basicsr.data.transforms import augment9from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor10from basicsr.utils.registry import DATASET_REGISTRY11from torchvision.transforms.functional import (adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation,12normalize)131415@DATASET_REGISTRY.register()16class FFHQDegradationDataset(data.Dataset):17"""FFHQ dataset for GFPGAN.1819It reads high resolution images, and then generate low-quality (LQ) images on-the-fly.2021Args:22opt (dict): Config for train datasets. It contains the following keys:23dataroot_gt (str): Data root path for gt.24io_backend (dict): IO backend type and other kwarg.25mean (list | tuple): Image mean.26std (list | tuple): Image std.27use_hflip (bool): Whether to horizontally flip.28Please see more options in the codes.29"""3031def __init__(self, opt):32super(FFHQDegradationDataset, self).__init__()33self.opt = opt34# file client (io backend)35self.file_client = None36self.io_backend_opt = opt['io_backend']3738self.gt_folder = opt['dataroot_gt']39self.mean = opt['mean']40self.std = opt['std']41self.out_size = opt['out_size']4243self.crop_components = opt.get('crop_components', False) # facial components44self.eye_enlarge_ratio = opt.get('eye_enlarge_ratio', 1) # whether enlarge eye regions4546if self.crop_components:47# load component list from a pre-process pth files48self.components_list = torch.load(opt.get('component_path'))4950# file client (lmdb io backend)51if self.io_backend_opt['type'] == 'lmdb':52self.io_backend_opt['db_paths'] = self.gt_folder53if not self.gt_folder.endswith('.lmdb'):54raise ValueError(f"'dataroot_gt' should end with '.lmdb', but received {self.gt_folder}")55with open(osp.join(self.gt_folder, 'meta_info.txt')) as fin:56self.paths = [line.split('.')[0] for line in fin]57else:58# disk backend: scan file list from a folder59self.paths = paths_from_folder(self.gt_folder)6061# degradation configurations62self.blur_kernel_size = opt['blur_kernel_size']63self.kernel_list = opt['kernel_list']64self.kernel_prob = opt['kernel_prob']65self.blur_sigma = opt['blur_sigma']66self.downsample_range = opt['downsample_range']67self.noise_range = opt['noise_range']68self.jpeg_range = opt['jpeg_range']6970# color jitter71self.color_jitter_prob = opt.get('color_jitter_prob')72self.color_jitter_pt_prob = opt.get('color_jitter_pt_prob')73self.color_jitter_shift = opt.get('color_jitter_shift', 20)74# to gray75self.gray_prob = opt.get('gray_prob')7677logger = get_root_logger()78logger.info(f'Blur: blur_kernel_size {self.blur_kernel_size}, sigma: [{", ".join(map(str, self.blur_sigma))}]')79logger.info(f'Downsample: downsample_range [{", ".join(map(str, self.downsample_range))}]')80logger.info(f'Noise: [{", ".join(map(str, self.noise_range))}]')81logger.info(f'JPEG compression: [{", ".join(map(str, self.jpeg_range))}]')8283if self.color_jitter_prob is not None:84logger.info(f'Use random color jitter. Prob: {self.color_jitter_prob}, shift: {self.color_jitter_shift}')85if self.gray_prob is not None:86logger.info(f'Use random gray. Prob: {self.gray_prob}')87self.color_jitter_shift /= 255.8889@staticmethod90def color_jitter(img, shift):91"""jitter color: randomly jitter the RGB values, in numpy formats"""92jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32)93img = img + jitter_val94img = np.clip(img, 0, 1)95return img9697@staticmethod98def color_jitter_pt(img, brightness, contrast, saturation, hue):99"""jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats"""100fn_idx = torch.randperm(4)101for fn_id in fn_idx:102if fn_id == 0 and brightness is not None:103brightness_factor = torch.tensor(1.0).uniform_(brightness[0], brightness[1]).item()104img = adjust_brightness(img, brightness_factor)105106if fn_id == 1 and contrast is not None:107contrast_factor = torch.tensor(1.0).uniform_(contrast[0], contrast[1]).item()108img = adjust_contrast(img, contrast_factor)109110if fn_id == 2 and saturation is not None:111saturation_factor = torch.tensor(1.0).uniform_(saturation[0], saturation[1]).item()112img = adjust_saturation(img, saturation_factor)113114if fn_id == 3 and hue is not None:115hue_factor = torch.tensor(1.0).uniform_(hue[0], hue[1]).item()116img = adjust_hue(img, hue_factor)117return img118119def get_component_coordinates(self, index, status):120"""Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file"""121components_bbox = self.components_list[f'{index:08d}']122if status[0]: # hflip123# exchange right and left eye124tmp = components_bbox['left_eye']125components_bbox['left_eye'] = components_bbox['right_eye']126components_bbox['right_eye'] = tmp127# modify the width coordinate128components_bbox['left_eye'][0] = self.out_size - components_bbox['left_eye'][0]129components_bbox['right_eye'][0] = self.out_size - components_bbox['right_eye'][0]130components_bbox['mouth'][0] = self.out_size - components_bbox['mouth'][0]131132# get coordinates133locations = []134for part in ['left_eye', 'right_eye', 'mouth']:135mean = components_bbox[part][0:2]136half_len = components_bbox[part][2]137if 'eye' in part:138half_len *= self.eye_enlarge_ratio139loc = np.hstack((mean - half_len + 1, mean + half_len))140loc = torch.from_numpy(loc).float()141locations.append(loc)142return locations143144def __getitem__(self, index):145if self.file_client is None:146self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)147148# load gt image149# Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32.150gt_path = self.paths[index]151img_bytes = self.file_client.get(gt_path)152img_gt = imfrombytes(img_bytes, float32=True)153154# random horizontal flip155img_gt, status = augment(img_gt, hflip=self.opt['use_hflip'], rotation=False, return_status=True)156h, w, _ = img_gt.shape157158# get facial component coordinates159if self.crop_components:160locations = self.get_component_coordinates(index, status)161loc_left_eye, loc_right_eye, loc_mouth = locations162163# ------------------------ generate lq image ------------------------ #164# blur165kernel = degradations.random_mixed_kernels(166self.kernel_list,167self.kernel_prob,168self.blur_kernel_size,169self.blur_sigma,170self.blur_sigma, [-math.pi, math.pi],171noise_range=None)172img_lq = cv2.filter2D(img_gt, -1, kernel)173# downsample174scale = np.random.uniform(self.downsample_range[0], self.downsample_range[1])175img_lq = cv2.resize(img_lq, (int(w // scale), int(h // scale)), interpolation=cv2.INTER_LINEAR)176# noise177if self.noise_range is not None:178img_lq = degradations.random_add_gaussian_noise(img_lq, self.noise_range)179# jpeg compression180if self.jpeg_range is not None:181img_lq = degradations.random_add_jpg_compression(img_lq, self.jpeg_range)182183# resize to original size184img_lq = cv2.resize(img_lq, (w, h), interpolation=cv2.INTER_LINEAR)185186# random color jitter (only for lq)187if self.color_jitter_prob is not None and (np.random.uniform() < self.color_jitter_prob):188img_lq = self.color_jitter(img_lq, self.color_jitter_shift)189# random to gray (only for lq)190if self.gray_prob and np.random.uniform() < self.gray_prob:191img_lq = cv2.cvtColor(img_lq, cv2.COLOR_BGR2GRAY)192img_lq = np.tile(img_lq[:, :, None], [1, 1, 3])193if self.opt.get('gt_gray'): # whether convert GT to gray images194img_gt = cv2.cvtColor(img_gt, cv2.COLOR_BGR2GRAY)195img_gt = np.tile(img_gt[:, :, None], [1, 1, 3]) # repeat the color channels196197# BGR to RGB, HWC to CHW, numpy to tensor198img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True)199200# random color jitter (pytorch version) (only for lq)201if self.color_jitter_pt_prob is not None and (np.random.uniform() < self.color_jitter_pt_prob):202brightness = self.opt.get('brightness', (0.5, 1.5))203contrast = self.opt.get('contrast', (0.5, 1.5))204saturation = self.opt.get('saturation', (0, 1.5))205hue = self.opt.get('hue', (-0.1, 0.1))206img_lq = self.color_jitter_pt(img_lq, brightness, contrast, saturation, hue)207208# round and clip209img_lq = torch.clamp((img_lq * 255.0).round(), 0, 255) / 255.210211# normalize212normalize(img_gt, self.mean, self.std, inplace=True)213normalize(img_lq, self.mean, self.std, inplace=True)214215if self.crop_components:216return_dict = {217'lq': img_lq,218'gt': img_gt,219'gt_path': gt_path,220'loc_left_eye': loc_left_eye,221'loc_right_eye': loc_right_eye,222'loc_mouth': loc_mouth223}224return return_dict225else:226return {'lq': img_lq, 'gt': img_gt, 'gt_path': gt_path}227228def __len__(self):229return len(self.paths)230231232