code
stringlengths
17
6.64M
def test_ttsr_dict(): cfg = dict(type='TTSRDiscriminator', in_channels=3, in_size=160) net = build_component(cfg) net.init_weights(pretrained=None) inputs = torch.rand((2, 3, 160, 160)) output = net(inputs) assert (output.shape == (2, 1)) if torch.cuda.is_available(): net.init_weig...
def test_patch_discriminator(): cfg = dict(type='PatchDiscriminator', in_channels=3, base_channels=64, num_conv=3, norm_cfg=dict(type='BN'), init_cfg=dict(type='normal', gain=0.02)) net = build_component(cfg) net.init_weights(pretrained=None) input_shape = (1, 3, 64, 64) img = _demo_inputs(input_s...
def test_smpatch_discriminator(): cfg = dict(type='SoftMaskPatchDiscriminator', in_channels=3, base_channels=64, num_conv=3, with_spectral_norm=True) net = build_component(cfg) net.init_weights(pretrained=None) input_shape = (1, 3, 64, 64) img = _demo_inputs(input_shape) output = net(img) ...
def _demo_inputs(input_shape=(1, 3, 64, 64)): 'Create a superset of inputs needed to run backbone.\n\n Args:\n input_shape (tuple): input batch dimensions.\n Default: (1, 3, 64, 64).\n\n Returns:\n imgs: (Tensor): Images in FloatTensor with desired shapes.\n ' imgs = np.rando...
def test_max_feature(): conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3, 16, 16, 16) y1 = conv2d(x1) assert (y1.shape == (3, 16, 16, 16)) linear = MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3, 16) y2 = linear(x2) assert (y2.shape == (3, 16)) if tor...
def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) inputs = torch.rand((2, 3, 128, 128)) output = net(inputs) assert (output.shape == (2, 1)) if torch.cuda.is_available(): net.init_weights(pretrained=None) ...
def test_multi_layer_disc(): with pytest.raises(AssertionError): multi_disc = MultiLayerDiscriminator(3, 236, fc_in_channels=(- 100), out_act_cfg=None) with pytest.raises(TypeError): multi_disc = MultiLayerDiscriminator(3, 256, num_convs=3, stride_list=(1, 2)) input_g = torch.randn(1, 3, 2...
def test_unet_disc_with_spectral_norm(): disc = UNetDiscriminatorWithSpectralNorm(in_channels=3) img = torch.randn(1, 3, 16, 16) disc(img) with pytest.raises(TypeError): disc.init_weights(pretrained=233) if torch.cuda.is_available(): disc = disc.cuda() img = img.cuda() ...
def assert_dict_keys_equal(dictionary, target_keys): 'Check if the keys of the dictionary is equal to the target key set.' assert isinstance(dictionary, dict) assert (set(dictionary.keys()) == set(target_keys))
def assert_tensor_with_shape(tensor, shape): '"Check if the shape of the tensor is equal to the target shape.' assert isinstance(tensor, torch.Tensor) assert (tensor.shape == shape)
def test_plain_refiner(): 'Test PlainRefiner.' model = PlainRefiner() model.init_weights() model.train() (merged, alpha, trimap, raw_alpha) = _demo_inputs_pair() prediction = model(torch.cat([merged, raw_alpha.sigmoid()], 1), raw_alpha) assert_tensor_with_shape(prediction, torch.Size([1, 1...
def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False): '\n Create a superset of inputs needed to run refiner.\n\n Args:\n img_shape (tuple): shape of the input image.\n batch_size (int): batch size of the input batch.\n cuda (bool): whether transfer input into gpu.\n ' ...
def test_mlp_refiner(): model_cfg = dict(type='MLPRefiner', in_dim=8, out_dim=3, hidden_list=[8, 8, 8, 8]) mlp = build_component(model_cfg) assert (mlp.__class__.__name__ == 'MLPRefiner') inputs = torch.rand(2, 8) targets = torch.rand(2, 3) if torch.cuda.is_available(): inputs = inputs...
class TestBlur(): @classmethod def setup_class(cls): cls.kernel = [1, 3, 3, 1] cls.pad = (1, 1) @pytest.mark.skipif((not torch.cuda.is_available()), reason='requires cuda') def test_blur_cuda(self): blur = Blur(self.kernel, self.pad) x = torch.randn((2, 3, 8, 8)) ...
class TestModStyleConv(): @classmethod def setup_class(cls): cls.default_cfg = dict(in_channels=3, out_channels=1, kernel_size=3, style_channels=5, upsample=True) def test_mod_styleconv_cpu(self): conv = ModulatedStyleConv(**self.default_cfg) input_x = torch.randn((2, 3, 4, 4)) ...
class TestToRGB(): @classmethod def setup_class(cls): cls.default_cfg = dict(in_channels=5, style_channels=5, out_channels=3) def test_torgb_cpu(self): model = ModulatedToRGB(**self.default_cfg) input_x = torch.randn((2, 5, 4, 4)) style = torch.randn((2, 5)) res =...
class TestStyleGAN2Generator(): @classmethod def setup_class(cls): cls.default_cfg = dict(out_size=64, style_channels=16, num_mlps=4, channel_multiplier=1) def test_stylegan2_g_cpu(self): g = StyleGANv2Generator(**self.default_cfg) res = g(None, num_batches=2) assert (res...
class TestStyleGANv2Disc(): @classmethod def setup_class(cls): cls.default_cfg = dict(in_size=64, channel_multiplier=1) def test_stylegan2_disc_cpu(self): d = StyleGAN2Discriminator(**self.default_cfg) img = torch.randn((2, 3, 64, 64)) score = d(img) assert (score...
def test_get_module_device_cpu(): device = get_module_device(nn.Conv2d(3, 3, 3, 1, 1)) assert (device == torch.device('cpu')) with pytest.raises(ValueError): get_module_device(nn.Flatten())
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires cuda') def test_get_module_device_cuda(): module = nn.Conv2d(3, 3, 3, 1, 1).cuda() device = get_module_device(module) assert (device == next(module.parameters()).get_device()) with pytest.raises(ValueError): get_module_devic...
def test_res_block(): res_block = ResBlock(16, 32) x = torch.rand(2, 16, 64, 64) y = res_block(x) assert (y.shape == (2, 32, 64, 64)) res_block = ResBlock(16, 16) x = torch.rand(2, 16, 64, 64) y = res_block(x) assert (y.shape == (2, 16, 64, 64))
def test_hour_glass(): hour_glass = Hourglass(2, 16) x = torch.rand(2, 16, 64, 64) y = hour_glass(x) assert (y.shape == x.shape)
def test_feedback_hour_glass(): model_cfg = dict(type='FeedbackHourglass', mid_channels=16, num_keypoints=20) fhg = build_component(model_cfg) assert (fhg.__class__.__name__ == 'FeedbackHourglass') x = torch.rand(2, 3, 64, 64) (heatmap, last_hidden) = fhg.forward(x) assert (heatmap.shape == (2...
def test_reduce_to_five_heatmaps(): heatmap = torch.rand((2, 5, 64, 64)) new_heatmap = reduce_to_five_heatmaps(heatmap, False) assert (new_heatmap.shape == (2, 5, 64, 64)) new_heatmap = reduce_to_five_heatmaps(heatmap, True) assert (new_heatmap.shape == (2, 5, 64, 64)) heatmap = torch.rand((2,...
def test_lte(): model_cfg = dict(type='LTE', requires_grad=False, pixel_range=1.0, pretrained=None, load_pretrained_vgg=False) lte = build_component(model_cfg) assert (lte.__class__.__name__ == 'LTE') x = torch.rand(2, 3, 64, 64) (x_level3, x_level2, x_level1) = lte(x) assert (x_level1.shape =...
def test_light_cnn_feature_loss(): pretrained = ('https://download.openmmlab.com/mmediting/' + 'restorers/dic/light_cnn_feature.pth') pred = torch.rand((3, 3, 128, 128)) gt = torch.rand((3, 3, 128, 128)) feature_loss = LightCNNFeatureLoss(pretrained=pretrained) loss = feature_loss(pred, gt) as...
def _get_model_cfg(fname): '\n Grab configs necessary to create a model. These are deep copied to allow\n for safe modification of parameters without influencing other tests.\n ' config_dpath = 'configs/mattors' config_fpath = osp.join(config_dpath, fname) if (not osp.exists(config_dpath)): ...
def assert_dict_keys_equal(dictionary, target_keys): 'Check if the keys of the dictionary is equal to the target key set.' assert isinstance(dictionary, dict) assert (set(dictionary.keys()) == set(target_keys))
@patch.multiple(BaseMattor, __abstractmethods__=set()) def test_base_mattor(): backbone = dict(type='SimpleEncoderDecoder', encoder=dict(type='VGG16', in_channels=4), decoder=dict(type='PlainDecoder')) refiner = dict(type='PlainRefiner') train_cfg = mmcv.ConfigDict(train_backbone=True, train_refiner=True)...
def test_dim(): (model_cfg, train_cfg, test_cfg) = _get_model_cfg('dim/dim_stage3_v16_pln_1x1_1000k_comp1k.py') model_cfg['pretrained'] = None train_cfg.train_refiner = True test_cfg.refine = True model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg) input_train = _demo_input_...
def test_indexnet(): (model_cfg, _, test_cfg) = _get_model_cfg('indexnet/indexnet_mobv2_1x16_78k_comp1k.py') model_cfg['pretrained'] = None with torch.no_grad(): indexnet = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg) indexnet.eval() input_test = _demo_input_test((64, ...
def test_gca(): (model_cfg, train_cfg, test_cfg) = _get_model_cfg('gca/gca_r34_4x10_200k_comp1k.py') model_cfg['pretrained'] = None model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg) inputs = _demo_input_train((64, 64), batch_size=2) inputs['trimap'] = inputs['trimap'].expand_a...
def _demo_input_train(img_shape, batch_size=1, cuda=False): '\n Create a superset of inputs needed to run backbone.\n\n Args:\n img_shape (tuple): shape of the input image.\n batch_size (int): batch size of the input batch.\n cuda (bool): whether transfer input into gpu.\n ' colo...
def _demo_input_test(img_shape, batch_size=1, cuda=False, test_trans='resize'): '\n Create a superset of inputs needed to run backbone.\n\n Args:\n img_shape (tuple): shape of the input image.\n batch_size (int): batch size of the input batch.\n cuda (bool): whether transfer input into ...
def test_basic_restorer(): model_cfg = dict(type='BasicRestorer', generator=dict(type='MSRResNet', in_channels=3, out_channels=3, mid_channels=4, num_blocks=1, upscale_factor=4), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean')) train_cfg = None test_cfg = None restorer = build_model(...
def test_basicvsr_model(): model_cfg = dict(type='BasicVSR', generator=dict(type='BasicVSRNet', mid_channels=64, num_blocks=30, spynet_pretrained=None), pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum')) train_cfg = dict(fix_iter=1) train_cfg = mmcv.Config(train_cfg) test_cfg = None ...
def test_dic_model(): pretrained = ('https://download.openmmlab.com/mmediting/' + 'restorers/dic/light_cnn_feature.pth') model_cfg_pre = dict(type='DIC', generator=dict(type='DICNet', in_channels=3, out_channels=3, mid_channels=48), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), align_loss...
def test_edvr_model(): model_cfg = dict(type='EDVR', generator=dict(type='EDVRNet', in_channels=3, out_channels=3, mid_channels=8, num_frames=5, deform_groups=2, num_blocks_extraction=1, num_blocks_reconstruction=1, center_frame_idx=2, with_tsa=False), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='su...
def test_esrgan(): model_cfg = dict(type='ESRGAN', generator=dict(type='MSRResNet', in_channels=3, out_channels=3, mid_channels=4, num_blocks=1, upscale_factor=4), discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), gan_loss=dic...
def test_glean(): model_cfg = dict(type='GLEAN', generator=dict(type='GLEANStyleGANv2', in_size=16, out_size=64, style_channels=512), discriminator=dict(type='StyleGAN2Discriminator', in_size=64), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), gan_loss=dict(type='GANLoss', gan_type='vanilla', ...
@COMPONENTS.register_module() class BP(nn.Module): 'A simple BP network for testing LIIF.\n\n Args:\n in_dim (int): Input dimension.\n out_dim (int): Output dimension.\n ' def __init__(self, in_dim, out_dim): super().__init__() self.layer = nn.Linear(in_dim, out_dim) ...
def test_liif(): model_cfg = dict(type='LIIF', generator=dict(type='LIIFEDSR', encoder=dict(type='EDSR', in_channels=3, out_channels=3, mid_channels=64, num_blocks=16), imnet=dict(type='MLPRefiner', in_dim=64, out_dim=3, hidden_list=[256, 256, 256, 256]), local_ensemble=True, feat_unfold=True, cell_decode=True, e...
def test_real_basicvsr(): model_cfg = dict(type='RealBasicVSR', generator=dict(type='RealBasicVSRNet'), discriminator=dict(type='UNetDiscriminatorWithSpectralNorm', in_channels=3, mid_channels=64, skip_connection=True), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), cleaning_loss=dict(type='L1...
def test_real_esrgan(): model_cfg = dict(type='RealESRGAN', generator=dict(type='MSRResNet', in_channels=3, out_channels=3, mid_channels=4, num_blocks=1, upscale_factor=4), discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), gan...
def test_srgan(): model_cfg = dict(type='SRGAN', generator=dict(type='MSRResNet', in_channels=3, out_channels=3, mid_channels=4, num_blocks=1, upscale_factor=4), discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'), gan_loss=dict(...
def test_tdan_model(): model_cfg = dict(type='TDAN', generator=dict(type='TDANNet', in_channels=3, mid_channels=64, out_channels=3, num_blocks_before_align=5, num_blocks_after_align=10), pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'), lq_pixel_loss=dict(type='MSELoss', loss_weight=1.0, reductio...
def test_sfe(): inputs = torch.rand(2, 3, 48, 48) sfe = SFE(3, 64, 16, 1.0) outputs = sfe(inputs) assert (outputs.shape == (2, 64, 48, 48))
def test_csfi(): inputs1 = torch.rand(2, 16, 24, 24) inputs2 = torch.rand(2, 16, 48, 48) inputs4 = torch.rand(2, 16, 96, 96) csfi2 = CSFI2(mid_channels=16) (out1, out2) = csfi2(inputs1, inputs2) assert (out1.shape == (2, 16, 24, 24)) assert (out2.shape == (2, 16, 48, 48)) csfi3 = CSFI3...
def test_merge_features(): inputs1 = torch.rand(2, 16, 24, 24) inputs2 = torch.rand(2, 16, 48, 48) inputs4 = torch.rand(2, 16, 96, 96) merge_features = MergeFeatures(mid_channels=16, out_channels=3) out = merge_features(inputs1, inputs2, inputs4) assert (out.shape == (2, 3, 96, 96))
def test_ttsr_net(): inputs = torch.rand(2, 3, 24, 24) soft_attention = torch.rand(2, 1, 24, 24) t_level3 = torch.rand(2, 64, 24, 24) t_level2 = torch.rand(2, 32, 48, 48) t_level1 = torch.rand(2, 16, 96, 96) ttsr_cfg = dict(type='TTSRNet', in_channels=3, out_channels=3, mid_channels=16, textur...
def test_ttsr(): model_cfg = dict(type='TTSR', generator=dict(type='TTSRNet', in_channels=3, out_channels=3, mid_channels=64, num_blocks=(16, 16, 8, 4)), extractor=dict(type='LTE', load_pretrained_vgg=False), transformer=dict(type='SearchTransformer'), discriminator=dict(type='TTSRDiscriminator', in_size=64), pix...
def test_cyclegan(): model_cfg = dict(type='CycleGAN', generator=dict(type='ResnetGenerator', in_channels=3, out_channels=3, base_channels=64, norm_cfg=dict(type='IN'), use_dropout=False, num_blocks=9, padding_mode='reflect', init_cfg=dict(type='normal', gain=0.02)), discriminator=dict(type='PatchDiscriminator', ...
def test_search_transformer(): model_cfg = dict(type='SearchTransformer') model = build_component(model_cfg) lr_pad_level3 = torch.randn((2, 32, 32, 32)) ref_pad_level3 = torch.randn((2, 32, 32, 32)) ref_level3 = torch.randn((2, 32, 32, 32)) ref_level2 = torch.randn((2, 16, 64, 64)) ref_le...
def test_cain(): model_cfg = dict(type='CAIN', generator=dict(type='CAINNet'), pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean')) train_cfg = None test_cfg = None restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg) assert (restorer.__class__.__name__ == 'CAIN'...
def test_init_random_seed(): init_random_seed(0, device='cpu') init_random_seed(device='cpu') if torch.cuda.is_available(): init_random_seed(0, device='cuda') init_random_seed(device='cuda')
def test_set_random_seed(): set_random_seed(0, deterministic=False) set_random_seed(0, deterministic=True)
@DATASETS.register_module() class ToyDataset(): def __init__(self, ann_file=None, cnt=0): self.ann_file = ann_file self.cnt = cnt def __item__(self, idx): return idx def __len__(self): return 100
@DATASETS.register_module() class ToyDatasetWithAnnFile(): def __init__(self, ann_file): self.ann_file = ann_file def __item__(self, idx): return idx def __len__(self): return 100
def test_build_dataset(): cfg = dict(type='ToyDataset') dataset = build_dataset(cfg) assert isinstance(dataset, ToyDataset) assert (dataset.cnt == 0) dataset = build_dataset(cfg, default_args=dict(cnt=1)) assert isinstance(dataset, ToyDataset) assert (dataset.cnt == 1) cfg = dict(type=...
def test_build_dataloader(): dataset = ToyDataset() samples_per_gpu = 3 dataloader = build_dataloader(dataset, samples_per_gpu=samples_per_gpu, workers_per_gpu=2) assert (dataloader.batch_size == samples_per_gpu) assert (len(dataloader) == int(math.ceil((len(dataset) / samples_per_gpu)))) asse...
class SimpleModule(nn.Module): def __init__(self): super().__init__() self.a = nn.Parameter(torch.tensor([1.0, 2.0])) if (version.parse(torch.__version__) >= version.parse('1.7.0')): self.register_buffer('b', torch.tensor([2.0, 3.0]), persistent=True) self.register...
class SimpleModel(nn.Module): def __init__(self) -> None: super().__init__() self.module_a = SimpleModule() self.module_b = SimpleModule() self.module_a_ema = SimpleModule() self.module_b_ema = SimpleModule()
class SimpleModelNoEMA(nn.Module): def __init__(self) -> None: super().__init__() self.module_a = SimpleModule() self.module_b = SimpleModule()
class SimpleRunner(): def __init__(self): self.model = SimpleModel() self.iter = 0
class TestEMA(): @classmethod def setup_class(cls): cls.default_config = dict(module_keys=('module_a_ema', 'module_b_ema'), interval=1, interp_cfg=dict(momentum=0.5)) cls.runner = SimpleRunner() @torch.no_grad() def test_ema_hook(self): cfg_ = deepcopy(self.default_config) ...
class ExampleDataset(Dataset): def __getitem__(self, idx): results = dict(imgs=torch.tensor([1])) return results def __len__(self): return 1
class ExampleModel(nn.Module): def __init__(self): super().__init__() self.test_cfg = None self.conv = nn.Conv2d(3, 3, 3) def forward(self, imgs, test_mode=False, **kwargs): return imgs def train_step(self, data_batch, optimizer): rlt = self.forward(data_batch) ...
def test_eval_hook(): with pytest.raises(TypeError): test_dataset = ExampleModel() data_loader = [DataLoader(test_dataset, batch_size=1, sampler=None, num_worker=0, shuffle=False)] EvalIterHook(data_loader) test_dataset = ExampleDataset() test_dataset.evaluate = MagicMock(return_va...
class ExampleModel(nn.Module): def __init__(self): super().__init__() self.model1 = nn.Conv2d(3, 8, kernel_size=3) self.model2 = nn.Conv2d(3, 4, kernel_size=3) def forward(self, x): return x
def test_build_optimizers(): base_lr = 0.0001 base_wd = 0.0002 momentum = 0.9 optimizer_cfg = dict(model1=dict(type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum), model2=dict(type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum)) model = ExampleModel() optimizers = bui...
def test_bbox_mask(): cfg = dict(img_shape=(256, 256), max_bbox_shape=100, max_bbox_delta=10, min_margin=10) bbox = random_bbox(**cfg) mask_bbox = bbox2mask(cfg['img_shape'], bbox) assert (mask_bbox.shape == (256, 256, 1)) zero_area = np.sum((mask_bbox == 0).astype(np.uint8)) ones_area = np.su...
def test_free_form_mask(): img_shape = (256, 256, 3) for _ in range(10): mask = brush_stroke_mask(img_shape) assert (mask.shape == (256, 256, 1)) img_shape = (256, 256, 3) mask = brush_stroke_mask(img_shape, num_vertices=8) assert (mask.shape == (256, 256, 1)) zero_area = np.su...
def test_irregular_mask(): img_shape = (256, 256) for _ in range(10): mask = get_irregular_mask(img_shape) assert (mask.shape == (256, 256, 1)) assert (0.15 < (np.sum(mask) / (img_shape[0] * img_shape[1])) < 0.5) zero_area = np.sum((mask == 0).astype(np.uint8)) ones_are...
def test_modify_args(): def _parse_args(): parser = argparse.ArgumentParser(description='Generation demo') parser.add_argument('--config-path', help='test config file path') args = parser.parse_args() return args with patch('argparse._sys.argv', ['test.py', '--config_path=conf...
@pytest.mark.skipif((torch.__version__ == 'parrots'), reason='skip parrots.') @pytest.mark.skipif((version.parse(torch.__version__) < version.parse('1.4.0')), reason='skip if torch=1.3.x') def test_restorer_wrapper(): try: import onnxruntime as ort from mmedit.core.export.wrappers import ONNXRunti...
@pytest.mark.skipif((torch.__version__ == 'parrots'), reason='skip parrots.') @pytest.mark.skipif((version.parse(torch.__version__) < version.parse('1.4.0')), reason='skip if torch=1.3.x') def test_mattor_wrapper(): try: import onnxruntime as ort from mmedit.core.export.wrappers import ONNXRuntime...
def test_pix2pix(): model_cfg = dict(type='Pix2Pix', generator=dict(type='UnetGenerator', in_channels=3, out_channels=3, num_down=8, base_channels=64, norm_cfg=dict(type='BN'), use_dropout=True, init_cfg=dict(type='normal', gain=0.02)), discriminator=dict(type='PatchDiscriminator', in_channels=6, base_channels=64...
def test_setup_multi_processes(): sys_start_mehod = mp.get_start_method(allow_none=True) sys_cv_threads = cv2.getNumThreads() sys_omp_threads = os.environ.pop('OMP_NUM_THREADS', default=None) sys_mkl_threads = os.environ.pop('MKL_NUM_THREADS', default=None) config = dict(data=dict(workers_per_gpu=...
def generate_json(data_root, seg_root, bg_root, all_data): 'Generate training json list for Background Matting video dataset.\n\n Args:\n data_root (str): Background Matting video data root.\n seg_root (str): Segmentation of Background Matting video data root.\n bg_root (str): Background v...
def parse_args(): parser = argparse.ArgumentParser(description='Prepare Background Matting video dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data_root', help='Background Matting video data root') parser.add_argument('--seg-root', help='Segmentation of Background ...
def main(): args = parse_args() if (not osp.exists(args.data_root)): raise FileNotFoundError(f'{args.data_root} does not exist!') print('generating Background Matting dataset annotation file...') generate_json(args.data_root, args.seg_root, args.bg_root, args.all_data) print('annotation fi...
def fix_png_file(filename, folder): "Fix png files in the target filename using pngfix.\n\n pngfix is a tool to fix PNG files. It's installed on Linux or MacOS by\n default.\n\n Args:\n filename (str): png file to run pngfix.\n " subprocess.call(f'pngfix --quiet --strip=color --prefix=fixed...
def join_first_contain(directories, filename, data_root): 'Join the first directory that contains the file.\n\n Args:\n directories (list[str]): Directories to search for the file.\n filename (str): The target filename.\n data_root (str): Root of the data path.\n ' for directory in ...
class ExtendFg(): def __init__(self, data_root, fg_dirs, alpha_dirs) -> None: self.data_root = data_root self.fg_dirs = fg_dirs self.alpha_dirs = alpha_dirs def extend(self, fg_name): fg_name = fg_name.strip() alpha_path = join_first_contain(self.alpha_dirs, fg_name, ...
def parse_args(): parser = argparse.ArgumentParser(description='Prepare Adobe composition 1k dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data_root', help='Adobe composition 1k dataset root') parser.add_argument('--nproc', type=int, default=4, help='number of proc...
def main(): args = parse_args() if (not osp.exists(args.data_root)): raise FileNotFoundError(f'{args.data_root} does not exist!') data_root = args.data_root print('preparing training data...') dir_prefix = 'Training_set' fname_prefix = 'training' fg_dirs = ['Training_set/Adobe-lice...
def generate_json(comp1k_json_path, target_list_path, save_json_path): data_infos = mmcv.load(comp1k_json_path) targets = mmcv.list_from_file(target_list_path) new_data_infos = [] for data_info in data_infos: for target in targets: if data_info['alpha_path'].endswith(target): ...
def parse_args(): parser = argparse.ArgumentParser(description='Filter composition-1k annotation file') parser.add_argument('comp1k_json_path', help='Path to the composition-1k dataset annotation file') parser.add_argument('target_list_path', help='Path to the file name list that need to filter out') ...
def main(): args = parse_args() if (not osp.exists(args.comp1k_json_path)): raise FileNotFoundError(f'{args.comp1k_json_path} does not exist!') if (not osp.exists(args.target_list_path)): raise FileNotFoundError(f'{args.target_list_path} does not exist!') generate_json(args.comp1k_json...
def fix_png_files(directory): "Fix png files in the target directory using pngfix.\n\n pngfix is a tool to fix PNG files. It's installed on Linux or MacOS by\n default.\n\n Args:\n directory (str): Directory to run pngfix.\n " subprocess.call('pngfix --quiet --strip=color --prefix=fixed_ *....
def fix_png_file(filename, folder): "Fix png files in the target filename using pngfix.\n\n pngfix is a tool to fix PNG files. It's installed on Linux or MacOS by\n default.\n\n Args:\n filename (str): png file to run pngfix.\n " subprocess.call(f'pngfix --quiet --strip=color --prefix=fixed...
def join_first_contain(directories, filename, data_root): 'Join the first directory that contains the file.\n\n Args:\n directories (list[str]): Directories to search for the file.\n filename (str): The target filename.\n data_root (str): Root of the data path.\n ' for directory in ...
def get_data_info(args): 'Function to process one piece of data.\n\n Args:\n args (tuple): Information needed to process one piece of data.\n\n Returns:\n dict: The processed data info.\n ' (name_with_postfix, source_bg_path, repeat_info, constant) = args (alpha, fg, alpha_path, fg_...
def generate_json(data_root, source_bg_dir, composite, nproc, mode): 'Generate training json list or test json list.\n\n It should be noted except for `source_bg_dir`, other strings are incomplete\n relative path. When using these strings to read from or write to disk, a\n data_root is added to form a co...
def parse_args(): modify_args() parser = argparse.ArgumentParser(description='Prepare Adobe composition 1k dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data_root', help='Adobe composition 1k dataset root') parser.add_argument('coco_root', help='COCO2014 or COC...
def main(): args = parse_args() if (not osp.exists(args.data_root)): raise FileNotFoundError(f'{args.data_root} does not exist!') if (not osp.exists(args.coco_root)): raise FileNotFoundError(f'{args.coco_root} does not exist!') if (not osp.exists(args.voc_root)): raise FileNotF...
def make_lmdb(mode, data_path, lmdb_path, batch=5000, compress_level=1): "Create lmdb for the REDS dataset.\n\n Contents of lmdb. The file structure is:\n example.lmdb\n β”œβ”€β”€ data.mdb\n β”œβ”€β”€ lock.mdb\n β”œβ”€β”€ meta_info.txt\n\n The data.mdb and lock.mdb are standard lmdb files and you can refer to\n ...
def merge_train_val(train_path, val_path): 'Merge the train and val datasets of REDS.\n\n Because the EDVR uses a different validation partition, so we merge train\n and val datasets in REDS for easy switching between REDS4 partition (used\n in EDVR) and the official validation partition.\n\n The orig...
def generate_anno_file(root_path, file_name='meta_info_REDS_GT.txt'): 'Generate anno file for REDS datasets from the ground-truth folder.\n\n Args:\n root_path (str): Root path for REDS datasets.\n ' print(f'Generate annotation files {file_name}...') txt_file = osp.join(root_path, file_name) ...
def unzip(zip_path): 'Unzip zip files. It will scan all zip files in zip_path and return unzip\n folder names.\n\n Args:\n zip_path (str): Path for zip files.\n\n Returns:\n list: unzip folder names.\n ' zip_files = mmcv.scandir(zip_path, suffix='zip', recursive=False) import shu...