code stringlengths 17 6.64M |
|---|
class MonoDepthCfg(TypedDict):
'Monocular depth trainer config. See each sub-class for details.'
net: NetCfg
loss: LossCfg
dataset: DataCfg
loader: LoaderCfg
optimizer: OptCfg
scheduler: SchedCfg
trainer: TrainCfg
|
def _apply_op(img: Tensor, op_name: str, magnitude: float, interpolation: InterpolationMode, fill: Optional[List[float]]):
if (op_name == 'ShearX'):
raise ValueError(f'Attempted geometric transformation "{op_name}"')
elif (op_name == 'ShearY'):
raise ValueError(f'Attempted geometric transforma... |
class AutoAugmentPolicy(Enum):
'AutoAugment policies learned on different data.\n Available policies are IMAGENET, CIFAR10 and SVHN.\n '
IMAGENET = 'imagenet'
CIFAR10 = 'cifar10'
SVHN = 'svhn'
|
class AutoAugment(torch.nn.Module):
'AutoAugment data augmentation method based on\n `"AutoAugment: Learning Augmentation Strategies from Data" <https://arxiv.org/pdf/1805.09501.pdf>`_.\n If the image is torch Tensor, it should be of type torch.uint8, and it is expected\n to have [..., 1 or 3, H, W] shap... |
class RandAugment(torch.nn.Module):
'RandAugment data augmentation method based on\n `"RandAugment: Practical automated data augmentation with a reduced search space"\n <https://arxiv.org/abs/1909.13719>`_.\n If the image is torch Tensor, it should be of type torch.uint8, and it is expected\n to have ... |
class TrivialAugmentWide(torch.nn.Module):
'Dataset-independent data-augmentation with TrivialAugment Wide, as described in\n `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" <https://arxiv.org/abs/2103.10158>`.\n If the image is torch Tensor, it should be of type torch.uint8, and it is... |
class RichProgressBar(plc.RichProgressBar):
'Progress bar that removes all `grad norms` from display.'
def get_metrics(self, trainer, pl_module):
m = super().get_metrics(trainer, pl_module)
m = {k: v for (k, v) in m.items() if ('grad' not in k)}
return m
|
class TQDMProgressBar(plc.TQDMProgressBar):
'Progress bar that removes all `grad norms` from display.'
def get_metrics(self, trainer, pl_module):
m = super().get_metrics(trainer, pl_module)
m = {k: v for (k, v) in m.items() if ('grad' not in k)}
return m
|
class TrainingManager(plc.Callback):
'Callback to save a dummy file as an indicator when training has started/finished.'
def __init__(self, ckpt_dir: Path):
super().__init__()
ckpt_dir.mkdir(exist_ok=True, parents=True)
self.fstart = (ckpt_dir / 'training')
if self.fstart.is_f... |
class DetectAnomaly(plc.Callback):
'Check for NaN/infinite loss at each core step. Replacement for `detect_anomaly=True`.'
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, unused=0):
if (not (loss := outputs['loss']).isfinite()):
raise ValueError(f'Detected NaN/... |
def default_convert(data):
"\n Function that converts each NumPy array element into a :class:`torch.Tensor`. If the input is a `Sequence`,\n `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.\n If the input is not an NumPy array, it is left unchang... |
def default_collate(batch):
"\n Function that takes in a batch of data and puts the elements within the batch\n into a tensor with an additional outer dimension - batch size. The exact output type can be\n a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a\n Collection o... |
def opt_args_deco(deco: Callable) -> Callable:
'Meta-decorator to make implementing of decorators with optional arguments more intuitive\n\n Recall: Decorators are equivalent to applying functions sequentially\n >>> func = deco(func)\n\n If we want to provide optional arguments, it would be the equiv... |
def delegates(to: Optional[Callable]=None, keep: bool=False):
'From https://www.fast.ai/2019/08/06/delegation/\n Decorator to replace `**kwargs` in signature with params from `to`.\n\n This can be used to decorate either a class\n ```\n @delegates()\n class Child(Parent): ...\n ```\n ... |
def map_container(f: Callable) -> Callable:
"Decorator to recursively apply a function to arbitrary nestings of `dict`, `list`, `tuple` & `set`\n\n NOTE: `f` can have an arbitrary signature, but the first arg must be the item we want to apply `f` to.\n\n Example:\n ```\n @map_apply\n def sq... |
@opt_args_deco
def retry_new_on_error(__getitem__: Callable, exc: Union[(BaseException, Sequence[BaseException])]=Exception, silent: bool=False, max: Optional[int]=None, use_blacklist: bool=False) -> Callable:
'Decorator to wrap a BaseDataset __getitem__ function, and retry a different index if there is an error.... |
def readlines(file: PathLike, /, encoding=None) -> list[str]:
'Read file as a list of strings.'
with open(file, encoding=encoding) as f:
return f.read().splitlines()
|
def pil2np(img: Image, /) -> NDArray:
'Convert PIL image [0, 255] into numpy [0, 1].'
return (np.array(img, dtype=np.float32) / 255.0)
|
def np2pil(arr: NDArray, /) -> Image:
'Convert numpy image [0, 1] into PIL [0, 255].'
return Image.fromarray((arr * 255).astype(np.uint8))
|
def write_yaml(file: PathLike, data: dict, mkdir: bool=False, sort_keys: bool=False) -> None:
'Write data to a yaml file.'
file = Path(file).with_suffix('.yaml')
if mkdir:
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, 'w') as f:
yaml.dump(data, f, sort_keys=sort_keys)
|
def load_yaml(file: PathLike) -> dict:
'Load a single yaml file. '
with open(file) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
return data
|
def load_merge_yaml(*files: PathLike) -> dict:
'Load a list of YAML cfg and recursively merge into a single config.\n\n Following dictionary merging rules, the first file is the "base" config, which gets updated by the second file.\n We chain this rule for however many cfg we have, i.e. ((((1 <- 2) <- 3) <-... |
def _merge_yaml(old: dict, new: dict) -> dict:
'Recursively merge two YAML cfg.\n Dictionaries are recursively merged. All other types simply update the current value.\n\n NOTE: This means that a "list of dicts" will simply be updated to whatever the new value is,\n not appended to or recursively checked... |
class BaseMetric(Metric):
higher_is_better = False
full_state_update = False
'Base class for depth estimation metrics.'
def __init__(self, mode: str='raw', **kwargs):
super().__init__(**kwargs)
assert (mode in MODES)
self.mode: str = mode
self.sf: int = {'raw': 1, 'log... |
class MAE(BaseMetric):
'Compute the mean absolute error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return (pred - target).abs().nanmean(dim=1)
|
class RMSE(BaseMetric):
'Compute the root mean squared error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return (pred - target).pow(2).nanmean(dim=1).sqrt()
|
class ScaleInvariant(BaseMetric):
'Compute the scale invariant error.'
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
err = (pred - target)
return (err.pow(2).nanmean(dim=1) - err.nanmean(dim=1).pow(2)).sqrt()
|
class AbsRel(BaseMetric):
'Compute the absolute relative error.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sf = 100
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return ((pred - target).abs() / target).nanmean(dim=1)
|
class SqRel(BaseMetric):
'Compute the absolute relative squared error.'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sf = 100
def _compute(self, pred: Tensor, target: Tensor) -> Tensor:
return ((pred - target).pow(2) / target.pow(2)).nanmean(dim=1)
|
class DeltaAcc(BaseMetric):
higher_is_better = True
'Compute the accuracy for a given error threshold.'
def __init__(self, delta: float, **kwargs):
super().__init__(**kwargs)
assert (self.mode == 'raw'), 'Accuracy should only be computed using raw depths.'
self.delta: float = delt... |
class Timer():
"Context manager for timing a block of code.\n\n Attributes:\n :param name: (str) Timer label when printing.\n :param as_ms: (bool) If `True`, store time as `milliseconds`, otherwise `seconds`.\n :param sync_gpu: (bool) If `True`, ensure that GPU is synced on Timer enter and exit.\n ... |
class MultiLevelTimer():
"Context manager Timer capable of being nested across multiple levels.\n\n NOTE: We use the *instance* of this class as a context manager, not the class itself (see examples).\n\n Timers are stored as a dict, mapping labels to (depth, start, end, elapsed).\n In order to allow for... |
def _get_items(split, mode):
file = kr.get_split_file(split, mode)
if ((split == 'benchmark') and (mode == 'test')):
return []
side2cam = {'l': 'image_02', 'r': 'image_03'}
lines = [line.split() for line in io.readlines(file)]
items = [{'seq': line[0], 'cam': side2cam[line[2]], 'stem': int... |
class TestKitti():
def test_image_files(self):
(splits, seqs) = ([], [])
for s in SPLITS:
for m in MODES:
for i in _get_items(s, m):
f = kr.get_image_file(i['seq'], i['cam'], i['stem'])
if (not f.is_file()):
... |
def _get_items(split, mode):
file = kr.get_split_file(split, mode)
if ((split == 'benchmark') and (mode == 'test')):
return []
side2cam = {'l': 'image_02', 'r': 'image_03'}
lines = [line.split() for line in io.readlines(file)]
items = [{'seq': line[0].split('/')[0], 'drive': line[0].split(... |
class TestKitti():
def test_image_files(self):
(splits, seqs) = ([], [])
for s in SPLITS:
for m in MODES:
for i in _get_items(s, m):
f = kr.get_images_path(i['seq'], i['drive'], i['cam'])
if (not f.is_dir()):
... |
def _get_items(mode):
return syp.load_split(mode)[1]
|
class TestKitti():
def test_image_files(self):
(modes, scenes) = ([], [])
for m in MODES:
for i in _get_items(m):
f = syp.get_image_file(*i)
if (not f.is_file()):
scenes.append(i[0])
modes.append(f'{m}')
a... |
class TmpData(BaseDataset):
def __init__(self, n, **kwargs):
self.n = range(n)
super().__init__(**kwargs)
def __len__(self):
return len(self.n)
def load(self, item, x, y, meta):
x['item'] = self.n[item]
return (x, y, meta)
def augment(self, x, y, meta):
... |
class TestBaseDataset():
def test_base(self):
'Test that we have the expected functions.'
with pytest.raises(TypeError):
_ = BaseDataset()
assert hasattr(BaseDataset, '__repr__'), 'Missing attribute from base dataset.'
assert hasattr(BaseDataset, '__len__'), 'Missing a... |
def test_all():
'Check all expected symbols are imported.'
items = {'register', 'NET_REG', 'DATA_REG', 'LOSS_REG', 'SCHED_REG'}
assert (set(registry.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_sched():
'Check scheduler registry has all expected keys.'
keys = {'steplr', 'exp', 'cos', 'cos_warm', 'plateau'}
assert (set(SCHED_REG.keys()) == keys), f'Incorrect SCHEDULER keys.'
|
def test_add_net():
'Check adding to the network registry.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
assert (name in NET_REG), 'Missing item from NETWORK registry.'
NET_REG.pop(name)
|
def test_add_loss():
'Check adding to the loss registry.'
(name, type) = ('test', 'loss')
@register(name, type)
class Test():
...
assert (name in LOSS_REG), 'Missing item from LOSS registry.'
LOSS_REG.pop(name)
|
def test_add_dataset():
'Check adding to the dataset registry.'
(name, type) = ('test', 'data')
@register(name, type)
class Test():
...
assert (name in DATA_REG), 'Missing item from DATASET registry.'
DATA_REG.pop(name)
|
def test_add_auto():
'Check automatic adding based on class name.'
name = 'test'
@register(name)
class TestNet():
...
assert (name in NET_REG), 'Missing item from automatic NET registry.'
NET_REG.pop(name)
@register(name)
class TestLoss():
...
assert (name in LOSS... |
def test_add_multiple():
name = ('test1', 'test2')
@register(name, type='net')
class TestNet():
...
for n in name:
assert (n in NET_REG), 'Missing item from automatic NET registry.'
[NET_REG.pop(n) for n in name]
|
def test_register_types():
'Check raised exception when adding to unknown registry.'
with pytest.raises(TypeError):
@register(name='temp', type='foo')
class Test():
...
|
def test_register_duplicates():
'Check raised exception when registering a duplicate name.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
with pytest.raises(ValueError):
@register(name, type)
class Test2():
...
with pytest.raises(V... |
def test_register_overwrite():
'Check registry items can be overwritten if desired.'
(name, type) = ('test', 'net')
@register(name, type)
class Test():
...
assert (NET_REG[name] == Test), 'Unexpected base class when overwriting.'
@register(name, type, overwrite=True)
class Test2(... |
def test_ignore_main():
'Check classes created in `__main__` are ignored.'
from unittest.mock import Mock
(name, type) = ('test', 'loss')
Mock.__module__ = '__main__'
with pytest.warns(UserWarning):
_ = register(name, type)(Mock)
assert (name not in LOSS_REG), 'Class from `__main__` no... |
def test_all():
'Check all expected symbols are imported.'
items = {'MaskReg'}
assert (set(mask.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check MaskReg is added to LOSS_REGISTRY.'
assert ('disp_mask' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_mask'] == MaskReg), 'Incorrect class in loss registry.'
|
def test_mask():
'Test MaskReg when all values are 1.'
shape = (1, 1, 100, 200)
(loss, loss_dict) = MaskReg().forward(torch.ones(shape))
assert (loss == 0), 'Error in correct BCELoss.'
assert (not loss_dict), 'Unexpected keys in `loss_dict`.'
(loss, loss_dict) = MaskReg().forward(torch.zeros(s... |
def test_all():
'Check all expected symbols are imported.'
items = {'OccReg'}
assert (set(occlusion.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check OcclusionReg is added to LOSS_REGISTRY.'
assert ('disp_occ' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_occ'] == OccReg), 'Incorrect class in loss registry.'
|
def test_occlusion_ones():
'Test OcclusionReg when all values are 1.'
shape = (1, 1, 100, 200)
input = torch.ones(shape)
(loss, loss_dict) = OccReg(invert=False).forward(input)
assert (loss == 1.0), 'Error in `invert=False`.'
assert (not loss_dict), 'Unexpected keys in `loss_dict`.'
(loss,... |
def test_occlusion_rand():
'Test OcclusionReg with a random tensor.'
shape = (1, 1, 100, 200)
input = torch.rand(shape)
mean = input.mean()
(loss, loss_dict) = OccReg(invert=False).forward(input)
assert (loss == mean), 'Error in `invert=False`.'
assert (not loss_dict), 'Unexpected keys in ... |
def test_all():
'Check all expected symbols are imported.'
items = {'SmoothReg', 'FeatPeakReg', 'FeatSmoothReg'}
assert (set(smooth.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_registry():
'Check smoothness regularizations are added to LOSS_REGISTRY.'
assert ('disp_smooth' in LOSS_REG), 'Missing key from loss registry.'
assert (LOSS_REG['disp_smooth'] == SmoothReg), 'Incorrect class in loss registry.'
assert ('feat_peaky' in LOSS_REG), 'Missing key from loss registr... |
def test_all():
'Check all expected symbols are imported.'
items = {'rgb_from_disp', 'rgb_from_feat'}
assert (set(viz.__all__) == items), 'Incorrect keys in `__all__`.'
|
class TestRGBfromDisp():
def test_default(self):
x = torch.rand(2, 1, 10, 20)
out = rgb_from_disp(x)
out2 = rgb_from_disp(x, cmap='turbo', vmin=0, vmax=[np.percentile(x[0], 95), np.percentile(x[1], 95)])
assert np.allclose(out, out2), 'Incorrect default params.'
def test_rang... |
class TestRGBfromFeat():
def test_norm(self):
x = torch.rand(1, 5, 10, 20)
out = rgb_from_feat(x).squeeze().flatten((- 2), (- 1))
assert torch.allclose(out.min((- 1))[0], out.new_zeros(3)), 'Incorrect min norm.'
assert torch.allclose(out.max((- 1))[0], out.new_ones(3)), 'Incorrect... |
class TestDefaultCollate():
def test_base(self):
torch_collate = torch.utils.data._utils.collate.default_collate
input = [torch.rand(3, 100, 200) for _ in range(5)]
target = torch_collate(input)
out = default_collate(input)
assert out.allclose(target), 'Error when matching... |
def test_all():
'Check all expected symbols are imported.'
items = {'opt_args_deco', 'delegates', 'map_container', 'retry_new_on_error'}
assert (set(deco.__all__) == items), 'Incorrect keys in `__all__`.'
|
@opt_args_deco
def _deco(func, prefix='', suffix=''):
'Helper.'
def wrapper(*args, **kwargs):
out = func(*args, **kwargs)
return (out, f'{prefix}{out}{suffix}')
return wrapper
|
def _add(a, b):
'Helper.'
return (a + b)
|
class TestOptArgsDeco():
def test_base(self):
'Test different ways of instantiating optional arguments.'
func = _deco(_add)
assert (func(1, 2) == (3, '3')), 'Error with default arguments.'
func = _deco(_add, prefix='***')
assert (func(1, 2) == (3, '***3')), 'Error with fir... |
def _parent(a, b=0, c=None, **kwargs):
...
|
def _child(new, *args, **kwargs):
...
|
class TestDelegates():
def test_default(self):
fn = delegates(_parent)(_child)
sig = inspect.signature(fn)
sigd = dict(sig.parameters)
assert (list(sigd) == ['new', 'a', 'b', 'c']), 'Incorrect delegated signature.'
|
def _stringify(x, suffix=''):
'Helper.'
return f'{x}{suffix}'
|
class TestMapContainer():
def test_single(self):
'Test with a single input, i.e. equivalent to the original function.'
input = 2
func = map_container(_stringify)
assert (func(input) == _stringify(input)), "Error in 'map_apply' single input"
assert (func(input, suffix='***'... |
class Dataset():
def __init__(self, n):
self.n = n
self.log_time = True
self.timer = MultiLevelTimer()
self.__class__.__getitem__ = retry_new_on_error(self.__class__.getitem, exc=self.retry_exc, silent=self.silent, max=self.max, use_blacklist=self.use_blacklist)
def __init_su... |
class TestRetryDifferentOnError():
def test_default(self):
'Test default parameters, catching any exception and logging.'
class TmpData(Dataset, retry_exc=Exception, silent=False, max_retries=None, use_blacklist=False):
def getitem(self, item):
if ((item % 2) == 0):
... |
def _random_pil(shape):
return Image.fromarray(np.random.randint(0, 255, size=shape, dtype=np.uint8))
|
def _random_np(shape):
return np.random.rand(*shape).astype(np.float32)
|
def _random_torch(shape):
return torch.rand(shape, dtype=torch.float32)
|
def test_all():
'Check all expected symbols are imported.'
items = {'readlines', 'pil2np', 'np2pil', 'write_yaml', 'load_yaml', 'load_merge_yaml'}
assert (set(io.__all__) == items), 'Incorrect keys in `__all__`.'
|
def test_pil2np():
'Test conversion from PIL to numpy.'
shape = (100, 200, 3)
image = _random_pil(shape)
out = pil2np(image)
assert isinstance(out, np.ndarray), 'Output should be a numpy array.'
assert (out.dtype == np.float32), 'Output should be float32.'
assert (out.shape == shape), 'Out... |
def test_np2pil():
'Test conversion from numpy to PIL.'
shape = (h, w, _) = (100, 200, 3)
image = _random_np(shape)
out = np2pil(image)
assert isinstance(out, Image.Image), 'Output should be a PIL Image.'
assert (out.size == (w, h)), 'Output should be same size as input.'
(vmax, vmin) = ou... |
def test_all():
'Check all expected symbols are imported.'
items = {'get_logger', 'flatten_dict', 'sort_dict', 'apply_cmap'}
assert (set(misc.__all__) == items), 'Incorrect keys in `__all__`.'
|
class TensorGetLogger():
def test_default(self):
key = 'test1234'
logger = get_logger(key)
assert (key in logging.root.manager.loggerDict), 'Logger not created.'
assert (logger == logging.root.manager.loggerDict[key]), 'Incorrect logger created.'
assert (not logger.propaga... |
class TestFlatten():
def test_default(self):
'Test basic nesting & default separator.'
d = {'a': 1, 'b': 2, 'c': dict(a=1, b=2)}
tgt = {'a': 1, 'b': 2, 'c/a': 1, 'c/b': 2}
out = flatten_dict(d)
assert (out == tgt), 'Incorrect flattened keys.'
out = flatten_dict(d, ... |
class TestSortedDict():
def test_sorted_dict(self):
'Test sorting dict keys.'
d = dict(b=2, c=1, a=10)
tgt = dict(a=10, b=2, c=1)
out = sort_dict(d)
assert (out == tgt), 'Incorrect sorted order'
with pytest.raises(TypeError):
sort_dict({'a': 1, 1: 0, 't... |
class TestApplyCmap():
def test_default(self):
'Test applying a cmap with default parameters.'
arr = np.array([0, 0, 0.5, 0.5, 1, 1])
out = apply_cmap(arr)
assert np.allclose(out[0], out[1]), 'Incorrect 0 mapping.'
assert np.allclose(out[2], out[3]), 'Incorrect 0.5 mapping... |
def test_all():
'Check all expected symbols are imported.'
items = {'Timer', 'MultiLevelTimer'}
assert (set(timers.__all__) == items), 'Incorrect keys in `__all__`.'
|
class TestTimer():
def test_options(self):
'Test that formatting options are set correctly.'
(name, precision) = ('Test', 4)
timer = Timer(name=name, as_ms=True, precision=precision)
assert (timer.name == name), 'Incorrect Timer name'
assert (repr(timer) == f'Timer(name={n... |
class TestMultiLevelTimer():
def test_options(self):
'Test that formatting options are set correctly.'
(name, precision) = ('Test', 4)
timer = MultiLevelTimer(name=name, as_ms=True, sync_gpu=False, precision=precision)
assert (repr(timer) == f'MultiLevelTimer(name={name}, as_ms=Tr... |
def is_image_file(filename):
return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
|
def make_dataset(dir, max_dataset_size=float('inf')):
cache = (dir.rstrip('/') + '.txt')
if os.path.isfile(cache):
print(('Using filelist cached at %s' % cache))
with open(cache) as f:
images = [line.strip() for line in f]
if images[0].startswith(dir):
print('Us... |
def make_multiple_dataset(dir, max_dataset_size=float('inf')):
subdir = ['Deepfakes', 'Face2Face', 'FaceSwap', 'NeuralTextures']
total_image_list = []
(last_dir, dir) = (((dir.split('/')[(- 2)] + '/') + dir.split('/')[(- 1)]), '/'.join(dir.split('/')[:(- 2)]))
print(dir)
for sdir in subdir:
... |
def make_multiple_dataset_real(dir, max_dataset_size=float('inf')):
subdir = ['faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faceforensics_aligned/Deepfakes/original', 'faceforensics_aligned/Face2Face/original', 'faceforensics_alig... |
def make_multiple_dataset_fake(dir, max_dataset_size=float('inf')):
subdir = ['faces/celebahq/pgan-pretrained-128-png', 'faces/celebahq/sgan-pretrained-128-png', 'faces/celebahq/glow-pretrained-128-png', 'faceforensics_aligned/Deepfakes/manipulated', 'faceforensics_aligned/Face2Face/manipulated', 'faceforensics_a... |
def make_CNNDetection_dataset(dir, max_dataset_size=float('inf'), mode='real'):
classes = os.listdir(dir)
total_image_list = []
total_class_list = []
print(dir)
if (mode == 'real'):
sdir = '0_real'
elif (mode == 'fake'):
sdir = '1_fake'
for cls in classes:
curr_dir ... |
def default_loader(path):
return Image.open(path).convert('RGB')
|
class PairedDataset(data.Dataset):
'A dataset class for paired images\n e.g. corresponding real and manipulated images\n '
def __init__(self, opt, im_path_real, im_path_fake, is_val=False, with_mask=False):
'Initialize this dataset class.\n\n Parameters:\n opt -- experiment op... |
class UnpairedDataset(data.Dataset):
'A dataset class for loading images within a single folder\n '
def __init__(self, opt, im_path, is_val=False):
'Initialize this dataset class.\n\n Parameters:\n opt -- experiment options\n im_path -- path to folder of images\n ... |
def get_available_masks():
' Return a list of the available masks for cli '
masks = sorted([name for (name, obj) in inspect.getmembers(sys.modules[__name__]) if (inspect.isclass(obj) and (name != 'Mask'))])
masks.append('none')
return masks
|
def get_default_mask():
' Set the default mask for cli '
masks = get_available_masks()
default = 'dfl_full'
default = (default if (default in masks) else masks[0])
return default
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.