Skip to content

Commit

Permalink
Inital Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ajithvcoder committed May 7, 2023
1 parent a0dbfac commit 5e50c27
Show file tree
Hide file tree
Showing 48 changed files with 3,293 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.idea
*.pyc
#fpn_inception.h5
#fpn_mobilenet.h5
*.h5
*__pyc*
58 changes: 58 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
Copyright (c) 2019, Orest Kupyn, Tetiana Martyniuk, Junru Wu and Zhangyang Wang
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


--------------------------- LICENSE FOR DeblurGANv2 --------------------------------
BSD License

For DeblurGANv2 software
Copyright (c) 2019, Orest Kupyn, Tetiana Martyniuk, Junru Wu and Zhangyang Wang
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

----------------------------- LICENSE FOR DCGAN --------------------------------
BSD License

For dcgan.torch software

Copyright (c) 2015, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
# DeblurGANv2_Customdataset
Using deblur GAN on custom dataset
# Using deblurv2 GAN on custom dataset



**Credits**

- [DeblurGANv2](https://github.com/VITA-Group/DeblurGANv2)
99 changes: 99 additions & 0 deletions adversarial_trainer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import torch
import copy


class GANFactory:
factories = {}

def __init__(self):
pass

def add_factory(gan_id, model_factory):
GANFactory.factories.put[gan_id] = model_factory

add_factory = staticmethod(add_factory)

# A Template Method:

def create_model(gan_id, net_d=None, criterion=None):
if gan_id not in GANFactory.factories:
GANFactory.factories[gan_id] = \
eval(gan_id + '.Factory()')
return GANFactory.factories[gan_id].create(net_d, criterion)

create_model = staticmethod(create_model)


class GANTrainer(object):
def __init__(self, net_d, criterion):
self.net_d = net_d
self.criterion = criterion

def loss_d(self, pred, gt):
pass

def loss_g(self, pred, gt):
pass

def get_params(self):
pass


class NoGAN(GANTrainer):
def __init__(self, net_d, criterion):
GANTrainer.__init__(self, net_d, criterion)

def loss_d(self, pred, gt):
return [0]

def loss_g(self, pred, gt):
return 0

def get_params(self):
return [torch.nn.Parameter(torch.Tensor(1))]

class Factory:
@staticmethod
def create(net_d, criterion): return NoGAN(net_d, criterion)


class SingleGAN(GANTrainer):
def __init__(self, net_d, criterion):
GANTrainer.__init__(self, net_d, criterion)
self.net_d = self.net_d.cuda()

def loss_d(self, pred, gt):
return self.criterion(self.net_d, pred, gt)

def loss_g(self, pred, gt):
return self.criterion.get_g_loss(self.net_d, pred, gt)

def get_params(self):
return self.net_d.parameters()

class Factory:
@staticmethod
def create(net_d, criterion): return SingleGAN(net_d, criterion)


class DoubleGAN(GANTrainer):
def __init__(self, net_d, criterion):
GANTrainer.__init__(self, net_d, criterion)
self.patch_d = net_d['patch'].cuda()
self.full_d = net_d['full'].cuda()
self.full_criterion = copy.deepcopy(criterion)

def loss_d(self, pred, gt):
return (self.criterion(self.patch_d, pred, gt) + self.full_criterion(self.full_d, pred, gt)) / 2

def loss_g(self, pred, gt):
return (self.criterion.get_g_loss(self.patch_d, pred, gt) + self.full_criterion.get_g_loss(self.full_d, pred,
gt)) / 2

def get_params(self):
return list(self.patch_d.parameters()) + list(self.full_d.parameters())

class Factory:
@staticmethod
def create(net_d, criterion): return DoubleGAN(net_d, criterion)

77 changes: 77 additions & 0 deletions aug.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from typing import List

import albumentations as albu


def get_transforms(size: int, scope: str = 'geometric', crop='random'):
augs = {'weak': albu.Compose([albu.HorizontalFlip(),
]),
'geometric': albu.OneOf([albu.HorizontalFlip(always_apply=True),
albu.ShiftScaleRotate(always_apply=True),
albu.Transpose(always_apply=True),
albu.OpticalDistortion(always_apply=True),
albu.ElasticTransform(always_apply=True),
])
}

aug_fn = augs[scope]
crop_fn = {'random': albu.RandomCrop(size, size, always_apply=True),
'center': albu.CenterCrop(size, size, always_apply=True)}[crop]
pad = albu.PadIfNeeded(size, size)

pipeline = albu.Compose([aug_fn, pad, crop_fn], additional_targets={'target': 'image'})

def process(a, b):
r = pipeline(image=a, target=b)
return r['image'], r['target']

return process


def get_normalize():
normalize = albu.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
normalize = albu.Compose([normalize], additional_targets={'target': 'image'})

def process(a, b):
r = normalize(image=a, target=b)
return r['image'], r['target']

return process


def _resolve_aug_fn(name):
d = {
'cutout': albu.Cutout,
'rgb_shift': albu.RGBShift,
'hsv_shift': albu.HueSaturationValue,
'motion_blur': albu.MotionBlur,
'median_blur': albu.MedianBlur,
'snow': albu.RandomSnow,
'shadow': albu.RandomShadow,
'fog': albu.RandomFog,
'brightness_contrast': albu.RandomBrightnessContrast,
'gamma': albu.RandomGamma,
'sun_flare': albu.RandomSunFlare,
'sharpen': albu.Sharpen,
'jpeg': albu.ImageCompression,
'gray': albu.ToGray,
'pixelize': albu.Downscale,
# ToDo: partial gray
}
return d[name]


def get_corrupt_function(config: List[dict]):
augs = []
for aug_params in config:
name = aug_params.pop('name')
cls = _resolve_aug_fn(name)
prob = aug_params.pop('prob') if 'prob' in aug_params else .5
augs.append(cls(p=prob, **aug_params))

augs = albu.OneOf(augs)

def process(x):
return augs(image=x)['image']

return process
74 changes: 74 additions & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
%%writefile config/config.yaml
---
project: deblur_gan
experiment_desc: fpn

train:
# files_a: &FILES_A /datasets/my_dataset/**/*.jpg
#Absolutepath can be used
files_a: &FILES_A /content/Licenseplate_blur_clear_dataset/train/blur/*.jpg
files_b: &FILES_B /content/Licenseplate_blur_clear_dataset/train/sharp/*.jpg
# files_a: &FILES_A ./dataset1/blur/*.png
# files_b: &FILES_B ./dataset1/sharp/*.png
size: &SIZE 256
crop: random
preload: &PRELOAD false
preload_size: &PRELOAD_SIZE 0
bounds: [0, .9]
scope: geometric
corrupt: &CORRUPT
- name: cutout
prob: 0.5
num_holes: 3
max_h_size: 25
max_w_size: 25
- name: jpeg
quality_lower: 70
quality_upper: 90
- name: motion_blur
- name: median_blur
- name: gamma
- name: rgb_shift
- name: hsv_shift
- name: sharpen

val:
files_a: &FILES_C /content/Licenseplate_blur_clear_dataset/valid/blur/*.jpg
files_b: &FILES_D /content/Licenseplate_blur_clear_dataset/valid/sharp/*.jpg
# files_a: &FILES_A
# files_b: &FILES_B
size: *SIZE
scope: geometric
crop: center
preload: *PRELOAD
preload_size: *PRELOAD_SIZE
bounds: [.9, 1]
corrupt: *CORRUPT

phase: train
warmup_num: 3
model:
g_name: fpn_inception
blocks: 9
d_name: double_gan # may be no_gan, patch_gan, double_gan, multi_scale
d_layers: 3
content_loss: perceptual
adv_lambda: 0.001
disc_loss: wgan-gp
learn_residual: True
norm_layer: instance
dropout: True

num_epochs: 20
train_batches_per_epoch: 102
val_batches_per_epoch: 100
batch_size: 16
image_size: [256, 256]

optimizer:
name: adam
lr: 0.01
scheduler:
name: linear
start_epoch: 20
min_lr: 0.0000001
Loading

0 comments on commit 5e50c27

Please sign in to comment.