Repository: Zj-BinXia/KDSR Branch: master Commit: c7c9e8110654 Files: 135 Total size: 425.7 KB Directory structure: gitextract_r69x67a9/ ├── KDSR-GAN/ │ ├── .gitignore │ ├── .pre-commit-config.yaml │ ├── CODE_OF_CONDUCT.md │ ├── Metric/ │ │ ├── DISTS/ │ │ │ ├── DISTS_pytorch/ │ │ │ │ ├── DISTS_pt.py │ │ │ │ └── weights.pt │ │ │ ├── DISTS_tensorflow/ │ │ │ │ └── DISTS_tf.py │ │ │ ├── LICENSE │ │ │ ├── requirements.txt │ │ │ └── weights/ │ │ │ └── alpha_beta.mat │ │ ├── LPIPS.py │ │ ├── PSNR.py │ │ ├── dists.py │ │ └── pip.sh │ ├── README.md │ ├── VERSION │ ├── docs/ │ │ ├── CONTRIBUTING.md │ │ ├── FAQ.md │ │ ├── Training.md │ │ ├── Training_CN.md │ │ ├── anime_comparisons.md │ │ ├── anime_comparisons_CN.md │ │ ├── anime_model.md │ │ ├── anime_video_model.md │ │ ├── feedback.md │ │ ├── model_zoo.md │ │ └── ncnn_conversion.md │ ├── kdsrgan/ │ │ ├── __init__.py │ │ ├── archs/ │ │ │ ├── ST_arch.py │ │ │ ├── TA_arch.py │ │ │ ├── __init__.py │ │ │ ├── common.py │ │ │ ├── discriminator_arch.py │ │ │ └── srvgg_arch.py │ │ ├── data/ │ │ │ ├── __init__.py │ │ │ ├── kdsrgan_dataset.py │ │ │ └── kdsrgan_paired_dataset.py │ │ ├── losses/ │ │ │ ├── __init__.py │ │ │ └── my_loss.py │ │ ├── models/ │ │ │ ├── __init__.py │ │ │ ├── kdsrgan_ST_model.py │ │ │ ├── kdsrgan_TA_model.py │ │ │ ├── kdsrnet_ST_model.py │ │ │ └── kdsrnet_TA_model.py │ │ ├── test.py │ │ ├── train.py │ │ ├── utils.py │ │ └── weights/ │ │ └── README.md │ ├── options/ │ │ ├── test_kdsrgan_x4ST.yml │ │ ├── test_kdsrnet_x4TA.yml │ │ ├── train_kdsrgan_x4ST.yml │ │ ├── train_kdsrgan_x4STV2.yml │ │ ├── train_kdsrnet_x4ST.yml │ │ └── train_kdsrnet_x4TA.yml │ ├── pip.sh │ ├── requirements.txt │ ├── scripts/ │ │ ├── extract_subimages.py │ │ ├── extract_subimages_DF2K.py │ │ ├── generate_meta_info.py │ │ ├── generate_meta_info_DF2K.py │ │ ├── generate_meta_info_OST.py │ │ ├── generate_meta_info_pairdata.py │ │ ├── generate_multiscale_DF2K.py │ │ └── pytorch2onnx.py │ ├── setup.cfg │ ├── setup.py │ ├── test.sh │ ├── tests/ │ │ ├── data/ │ │ │ ├── gt.lmdb/ │ │ │ │ ├── data.mdb │ │ │ │ ├── lock.mdb │ │ │ │ └── meta_info.txt │ │ │ ├── lq.lmdb/ │ │ │ │ ├── data.mdb │ │ │ │ ├── lock.mdb │ │ │ │ └── meta_info.txt │ │ │ ├── meta_info_gt.txt │ │ │ ├── meta_info_pair.txt │ │ │ ├── test_realesrgan_dataset.yml │ │ │ ├── test_realesrgan_model.yml │ │ │ ├── test_realesrgan_paired_dataset.yml │ │ │ └── test_realesrnet_model.yml │ │ ├── test_dataset.py │ │ ├── test_discriminator_arch.py │ │ ├── test_model.py │ │ └── test_utils.py │ ├── train_KDSRGAN_S.sh │ ├── train_KDSRNet_S.sh │ └── train_KDSRNet_T.sh ├── KDSR-classic/ │ ├── README.md │ ├── cal_parms.py │ ├── data/ │ │ ├── __init__.py │ │ ├── benchmark.py │ │ ├── common.py │ │ ├── common2.py │ │ ├── df2k.py │ │ ├── multiscalesrdata.py │ │ └── multiscalesrdata2.py │ ├── dataloader.py │ ├── loss/ │ │ ├── __init__.py │ │ ├── adversarial.py │ │ ├── discriminator.py │ │ └── vgg.py │ ├── main_anisonoise_KDSRsMx4_stage3.sh │ ├── main_anisonoise_KDSRsMx4_stage4.sh │ ├── main_anisonoise_stage3.py │ ├── main_anisonoise_stage4.py │ ├── main_iso_KDSRsLx4_stage3.sh │ ├── main_iso_KDSRsLx4_stage4.sh │ ├── main_iso_KDSRsMx4_stage3.sh │ ├── main_iso_KDSRsMx4_stage4.sh │ ├── main_iso_stage3.py │ ├── main_iso_stage4.py │ ├── model/ │ │ ├── __init__.py │ │ ├── blindsr.py │ │ └── common.py │ ├── model_ST/ │ │ ├── __init__.py │ │ ├── blindsr.py │ │ └── common.py │ ├── model_TA/ │ │ ├── __init__.py │ │ ├── blindsr.py │ │ └── common.py │ ├── option.py │ ├── template.py │ ├── test.py │ ├── test_anisonoise_KDSRsMx4.sh │ ├── test_iso_KDSRsLx4.sh │ ├── test_iso_KDSRsMx4.sh │ ├── trainer_anisonoise_stage3.py │ ├── trainer_anisonoise_stage4.py │ ├── trainer_iso_stage3.py │ ├── trainer_iso_stage4.py │ ├── utility.py │ ├── utility2.py │ ├── utility3.py │ └── utils/ │ ├── __init__.py │ ├── util.py │ └── util2.py └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: KDSR-GAN/.gitignore ================================================ # ignored folders datasets/* experiments/* results/* tb_logger/* wandb/* tmp/* realesrgan/weights/* version.py # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ ================================================ FILE: KDSR-GAN/.pre-commit-config.yaml ================================================ repos: # flake8 - repo: https://github.com/PyCQA/flake8 rev: 3.8.3 hooks: - id: flake8 args: ["--config=setup.cfg", "--ignore=W504, W503"] # modify known_third_party - repo: https://github.com/asottile/seed-isort-config rev: v2.2.0 hooks: - id: seed-isort-config # isort - repo: https://github.com/timothycrosley/isort rev: 5.2.2 hooks: - id: isort # yapf - repo: https://github.com/pre-commit/mirrors-yapf rev: v0.30.0 hooks: - id: yapf # codespell - repo: https://github.com/codespell-project/codespell rev: v2.1.0 hooks: - id: codespell # pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - id: trailing-whitespace # Trim trailing whitespace - id: check-yaml # Attempt to load all yaml files to verify syntax - id: check-merge-conflict # Check for files that contain merge conflict strings - id: double-quote-string-fixer # Replace double quoted strings with single quoted strings - id: end-of-file-fixer # Make sure files end in a newline and only a newline - id: requirements-txt-fixer # Sort entries in requirements.txt and remove incorrect entry for pkg-resources==0.0.0 - id: fix-encoding-pragma # Remove the coding pragma: # -*- coding: utf-8 -*- args: ["--remove"] - id: mixed-line-ending # Replace or check mixed line ending args: ["--fix=lf"] ================================================ FILE: KDSR-GAN/CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at xintao.wang@outlook.com or xintaowang@tencent.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: KDSR-GAN/Metric/DISTS/DISTS_pytorch/DISTS_pt.py ================================================ # This is a pytoch implementation of DISTS metric. # Requirements: python >= 3.6, pytorch >= 1.0 import numpy as np import os,sys import torch from torchvision import models,transforms import torch.nn as nn import torch.nn.functional as F class L2pooling(nn.Module): def __init__(self, filter_size=5, stride=2, channels=None, pad_off=0): super(L2pooling, self).__init__() self.padding = (filter_size - 2 )//2 self.stride = stride self.channels = channels a = np.hanning(filter_size)[1:-1] g = torch.Tensor(a[:,None]*a[None,:]) g = g/torch.sum(g) self.register_buffer('filter', g[None,None,:,:].repeat((self.channels,1,1,1))) def forward(self, input): input = input**2 out = F.conv2d(input, self.filter, stride=self.stride, padding=self.padding, groups=input.shape[1]) return (out+1e-12).sqrt() class DISTS(torch.nn.Module): def __init__(self, load_weights=True): super(DISTS, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=True).features self.stage1 = torch.nn.Sequential() self.stage2 = torch.nn.Sequential() self.stage3 = torch.nn.Sequential() self.stage4 = torch.nn.Sequential() self.stage5 = torch.nn.Sequential() for x in range(0,4): self.stage1.add_module(str(x), vgg_pretrained_features[x]) self.stage2.add_module(str(4), L2pooling(channels=64)) for x in range(5, 9): self.stage2.add_module(str(x), vgg_pretrained_features[x]) self.stage3.add_module(str(9), L2pooling(channels=128)) for x in range(10, 16): self.stage3.add_module(str(x), vgg_pretrained_features[x]) self.stage4.add_module(str(16), L2pooling(channels=256)) for x in range(17, 23): self.stage4.add_module(str(x), vgg_pretrained_features[x]) self.stage5.add_module(str(23), L2pooling(channels=512)) for x in range(24, 30): self.stage5.add_module(str(x), vgg_pretrained_features[x]) for param in self.parameters(): param.requires_grad = False self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1,-1,1,1)) self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1,-1,1,1)) self.chns = [3,64,128,256,512,512] self.register_parameter("alpha", nn.Parameter(torch.randn(1, sum(self.chns),1,1))) self.register_parameter("beta", nn.Parameter(torch.randn(1, sum(self.chns),1,1))) self.alpha.data.normal_(0.1,0.01) self.beta.data.normal_(0.1,0.01) if load_weights: # weights = torch.load(os.path.join(sys.prefix, 'weights.pt')) weights = torch.load('scripts/metrics/DISTS/DISTS_pytorch/weights.pt') self.alpha.data = weights['alpha'] self.beta.data = weights['beta'] def forward_once(self, x): h = (x-self.mean)/self.std h = self.stage1(h) h_relu1_2 = h h = self.stage2(h) h_relu2_2 = h h = self.stage3(h) h_relu3_3 = h h = self.stage4(h) h_relu4_3 = h h = self.stage5(h) h_relu5_3 = h return [x,h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3] def forward(self, x, y, require_grad=False, batch_average=False): if require_grad: feats0 = self.forward_once(x) feats1 = self.forward_once(y) else: with torch.no_grad(): feats0 = self.forward_once(x) feats1 = self.forward_once(y) dist1 = 0 dist2 = 0 c1 = 1e-6 c2 = 1e-6 w_sum = self.alpha.sum() + self.beta.sum() alpha = torch.split(self.alpha/w_sum, self.chns, dim=1) beta = torch.split(self.beta/w_sum, self.chns, dim=1) for k in range(len(self.chns)): x_mean = feats0[k].mean([2,3], keepdim=True) y_mean = feats1[k].mean([2,3], keepdim=True) S1 = (2*x_mean*y_mean+c1)/(x_mean**2+y_mean**2+c1) dist1 = dist1+(alpha[k]*S1).sum(1,keepdim=True) x_var = ((feats0[k]-x_mean)**2).mean([2,3], keepdim=True) y_var = ((feats1[k]-y_mean)**2).mean([2,3], keepdim=True) xy_cov = (feats0[k]*feats1[k]).mean([2,3],keepdim=True) - x_mean*y_mean S2 = (2*xy_cov+c2)/(x_var+y_var+c2) dist2 = dist2+(beta[k]*S2).sum(1,keepdim=True) score = 1 - (dist1+dist2).squeeze() if batch_average: return score.mean() else: return score def prepare_image(image, resize=True): if resize and min(image.size) > 256: image = transforms.functional.resize(image, 256) image = transforms.ToTensor()(image) return image.unsqueeze(0) if __name__ == '__main__': from PIL import Image import glob os.environ['CUDA_VISIBLE_DEVICES'] = '0' # others # data_root = '/data1/liangjie/BasicSR_ALL/results/' # ref_root = '/data1/liangjie/BasicSR_ALL/datasets/' # ref_dirs = ['SISR_Test_matlab/Set5mod12', 'SISR_Test_matlab/Set14mod12', 'SISR_Test_matlab/Manga109mod12', 'SISR_Test_matlab/BSDS100mod12', 'SISR_Test_matlab/General100mod12', 'SISR_Test/Urban100', 'DIV2K/DIV2K_valid_HR/'] # datasets = ['Set5', 'Set14', 'Manga109', 'BSDS100', 'General100', 'Urban100', 'DIV2K100'] # img_dirs = ['SRGAN_official', 'ESRGAN_official', 'NatSR_official', 'USRGAN_official', 'SPSR_official', 'SPSR_DF2K', 'ESRGAN_ours_DIV2K', 'ESRGAN_ours_DIV2K_ema', 'ESRGAN_ours_DF2K', 'ESRGAN_ours_DF2K_ema'] # SFTGAN # data_root = '/data1/liangjie/BasicSR_ALL/results' # ref_root = '/data1/liangjie/BasicSR_ALL/results/SFTGAN_official' # ref_dirs = ['GT'] * 7 # datasets = ['Set5', 'Set14', 'Manga109', 'BSDS100', 'General100', 'Urban100', 'DIV2K100'] # img_dirs = ['SFTGAN_official'] # new data_root = 'results/' ref_root = 'datasets/' ref_dirs = ['DIV2K/DIV2K_valid_HR/'] datasets = ['DIV2K100'] img_dirs = ['ESRGAN_ours_DISTS_300k/visualization/'] logoverall_path = 'results/table_logs/' + 'DISTS_orisize_DISTStrain225k.txt' for index in range(len(ref_dirs)): ref_dir = os.path.join(ref_root, ref_dirs[index]) for method in img_dirs: img_dir = os.path.join(data_root, method, datasets[index]) img_list = sorted(glob.glob(os.path.join(img_dir, '*'))) log_path = 'results/table_logs/' + img_dir.replace('/', '_') + '_DISTS_orisize.txt' DISTS_all = [] for i, img_path in enumerate(img_list): file_name = img_path.split('/')[-1] if 'DIV2K100' in img_dir and 'SFTGAN' not in img_dir: gt_path = os.path.join(ref_dir, file_name[:4] + '.png') elif 'Urban100' in img_dir and 'SFTGAN' not in img_dir: gt_path = os.path.join(ref_dir, file_name[:7] + '.png') elif 'SFTGAN' in img_dir: gt_path = os.path.join(ref_dir, file_name.split('_')[0] + '_gt.png') if 'Urban100' in img_dir: gt_path = os.path.join(ref_dir, file_name.split('_')[0] + '_' + file_name.split('_')[1] + '_gt.png') else: if '_' in file_name: gt_path = os.path.join(ref_dir, file_name.split('_')[0] + '.png') else: gt_path = os.path.join(ref_dir, file_name) ref = prepare_image(Image.open(gt_path).convert("RGB"), resize=False) dist = prepare_image(Image.open(img_path).convert("RGB"), resize=False) assert ref.shape == dist.shape device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = DISTS().to(device) ref = ref.to(device) dist = dist.to(device) score = model(ref, dist) DISTS_all.append(score.item()) log = f'{i + 1:3d}: {file_name:25}. \tDISTS: {score.item():.6f}.' with open(log_path, 'a') as f: f.write(log + '\n') # print(log) log = f'Average: DISTS: {sum(DISTS_all) / len(DISTS_all):.6f}' with open(log_path, 'a') as f: f.write(log + '\n') log_overall = method + '__' + datasets[index] + '__' + log with open(logoverall_path, 'a') as f: f.write(log_overall + '\n') print(log_overall) ================================================ FILE: KDSR-GAN/Metric/DISTS/DISTS_tensorflow/DISTS_tf.py ================================================ # This is a tensorflow implementation of DISTS metric. # Requirements: python >= 3.6, tensorflow-gpu >= 1.15 import tensorflow.compat.v1 as tf import numpy as np import time import scipy.io as scio from PIL import Image import argparse # tf.enable_eager_execution() tf.disable_eager_execution() class DISTS(): def __init__(self): self.parameters = scio.loadmat('../weights/net_param.mat') self.chns = [3,64,128,256,512,512] self.mean = tf.constant(self.parameters['vgg_mean'], dtype=tf.float32, shape=(1,1,1,3),name="img_mean") self.std = tf.constant(self.parameters['vgg_std'], dtype=tf.float32, shape=(1,1,1,3),name="img_std") # self.alpha = tf.Variable(tf.random_normal(shape=(1,1,1,sum(self.chns)), mean=0.1, stddev=0.01),name="alpha") # self.beta = tf.Variable(tf.random_normal(shape=(1,1,1,sum(self.chns)), mean=0.1, stddev=0.01),name="beta") self.weights = scio.loadmat('../weights/alpha_beta.mat') self.alpha = tf.constant(np.reshape(self.weights['alpha'],(1,1,1,sum(self.chns))),name="alpha") self.beta = tf.constant(np.reshape(self.weights['beta'],(1,1,1,sum(self.chns))),name="beta") def get_features(self, img): x = (img - self.mean)/self.std self.conv1_1 = self.conv_layer(x, "conv1_1") self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2") self.pool1 = self.pool_layer(self.conv1_2, name="pool_1") self.conv2_1 = self.conv_layer(self.pool1, "conv2_1") self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2") self.pool2 = self.pool_layer(self.conv2_2, name="pool_2") self.conv3_1 = self.conv_layer(self.pool2, "conv3_1") self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2") self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3") self.pool3 = self.pool_layer(self.conv3_3, name="pool_3") self.conv4_1 = self.conv_layer(self.pool3, "conv4_1") self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2") self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3") self.pool4 = self.pool_layer(self.conv4_3, name="pool_4") self.conv5_1 = self.conv_layer(self.pool4, "conv5_1") self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2") self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3") return [img, self.conv1_2,self.conv2_2,self.conv3_3,self.conv4_3,self.conv5_3] def conv_layer(self, input, name): with tf.variable_scope(name) as _: filter = self.get_conv_filter(name) conv = tf.nn.conv2d(input, filter, strides=1, padding="SAME") bias = self.get_bias(name) conv = tf.nn.relu(tf.nn.bias_add(conv, bias)) return conv def pool_layer(self, input, name): # return tf.nn.max_pool(input, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME") with tf.variable_scope(name) as _: filter = tf.squeeze(tf.constant(self.parameters['L2'+name], name = "filter"),3) conv = tf.nn.conv2d(input**2, filter, strides=2, padding=[[0, 0], [1, 0], [1, 0], [0, 0]]) return tf.sqrt(tf.maximum(conv, 1e-12)) def get_conv_filter(self, name): return tf.constant(self.parameters[name+'_weight'], name = "filter") def get_bias(self, name): return tf.constant(np.squeeze(self.parameters[name+'_bias']), name = "bias") def get_score(self, img1, img2): feats0 = self.get_features(img1) feats1 = self.get_features(img2) dist1 = 0 dist2 = 0 c1 = 1e-6 c2 = 1e-6 w_sum = tf.reduce_sum(self.alpha) + tf.reduce_sum(self.beta) alpha = tf.split(self.alpha/w_sum, self.chns, axis=3) beta = tf.split(self.beta/w_sum, self.chns, axis=3) for k in range(len(self.chns)): x_mean = tf.reduce_mean(feats0[k],[1,2], keepdims=True) y_mean = tf.reduce_mean(feats1[k],[1,2], keepdims=True) S1 = (2*x_mean*y_mean+c1)/(x_mean**2+y_mean**2+c1) dist1 = dist1+tf.reduce_sum(alpha[k]*S1, 3, keepdims=True) x_var = tf.reduce_mean((feats0[k]-x_mean)**2,[1,2], keepdims=True) y_var = tf.reduce_mean((feats1[k]-y_mean)**2,[1,2], keepdims=True) xy_cov = tf.reduce_mean(feats0[k]*feats1[k],[1,2], keepdims=True) - x_mean*y_mean S2 = (2*xy_cov+c2)/(x_var+y_var+c2) dist2 = dist2+tf.reduce_sum(beta[k]*S2, 3, keepdims=True) dist = 1-tf.squeeze(dist1+dist2) return dist if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--ref', type=str, default='../images/r0.png') parser.add_argument('--dist', type=str, default='../images/r1.png') args = parser.parse_args() model = DISTS() ref = np.array(Image.open(args.ref).convert("RGB")) ref = np.expand_dims(ref,axis=0)/255. dist = np.array(Image.open(args.dist).convert("RGB")) dist = np.expand_dims(dist,axis=0)/255. x = tf.placeholder(dtype=tf.float32, shape=ref.shape, name= "ref") y = tf.placeholder(dtype=tf.float32, shape=dist.shape, name= "dist") score = model.get_score(x,y) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) score = sess.run(score, feed_dict={x: ref, y: dist}) print(score) ================================================ FILE: KDSR-GAN/Metric/DISTS/LICENSE ================================================ MIT License Copyright (c) 2020 Keyan Ding Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: KDSR-GAN/Metric/DISTS/requirements.txt ================================================ torch>=1.0 ================================================ FILE: KDSR-GAN/Metric/LPIPS.py ================================================ import cv2 import glob import numpy as np import os.path as osp from torchvision.transforms.functional import normalize from basicsr.utils import img2tensor import lpips import argparse def main(): # Configurations parser = argparse.ArgumentParser() parser.add_argument('--folder_gt', type=str, default='/root/datasets/NTIRE2020-Track1/track1-valid-gt') parser.add_argument('--folder_restored', type=str, default='/root/results/NTIRE2020-Track1') args = parser.parse_args() loss_fn_vgg = lpips.LPIPS(net='vgg').cuda(0) lpips_all = [] img_list = sorted(glob.glob(osp.join(args.folder_gt, '*.png'))) lr_list = sorted(glob.glob(osp.join(args.folder_restored, '*.png'))) mean = [0.5, 0.5, 0.5] std = [0.5, 0.5, 0.5] for i, (img_path, lr_path) in enumerate(zip(img_list,lr_list)): basename, ext = osp.splitext(osp.basename(img_path)) img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255. img_restored = cv2.imread(osp.join(lr_path), cv2.IMREAD_UNCHANGED).astype( np.float32) / 255. img_gt, img_restored = img2tensor([img_gt, img_restored], bgr2rgb=True, float32=True) # norm to [-1, 1] normalize(img_gt, mean, std, inplace=True) normalize(img_restored, mean, std, inplace=True) # calculate lpips lpips_val = loss_fn_vgg(img_restored.unsqueeze(0).cuda(0), img_gt.unsqueeze(0).cuda(0)).cpu().data.numpy()[0,0,0,0] # print(lpips_val) lpips_all.append(lpips_val) print(f'Average: LPIPS: {sum(lpips_all) / len(lpips_all):.6f}') if __name__ == '__main__': main() ================================================ FILE: KDSR-GAN/Metric/PSNR.py ================================================ import cv2 import glob import numpy as np import os.path as osp from torchvision.transforms.functional import normalize from basicsr.utils import img2tensor import lpips import argparse from basicsr.metrics import calculate_psnr, calculate_ssim def main(): # Configurations parser = argparse.ArgumentParser() parser.add_argument('--folder_gt', type=str, default='/root/datasets/NTIRE2020-Track1/track1-valid-gt') parser.add_argument('--folder_restored', type=str, default='/root/results/NTIRE2020-Track1') args = parser.parse_args() psnr_all = [] ssim_all = [] img_list = sorted(glob.glob(osp.join(args.folder_gt, '*.png'))) lr_list = sorted(glob.glob(osp.join(args.folder_restored, '*.png'))) for i, (img_path, lr_path) in enumerate(zip(img_list,lr_list)): basename, ext = osp.splitext(osp.basename(img_path)) img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) img_restored = cv2.imread(osp.join(lr_path), cv2.IMREAD_UNCHANGED) psnr=calculate_psnr(img_restored, img_gt, crop_border=4, test_y_channel=True) ssim=calculate_ssim(img_restored, img_gt, crop_border=4, test_y_channel=True) psnr_all.append(psnr) ssim_all.append(ssim) print(f'Average: PSNR: {sum(psnr_all) / len(psnr_all):.6f}') print(f'Average: SSIM: {sum(ssim_all) / len(ssim_all):.6f}') if __name__ == '__main__': main() ================================================ FILE: KDSR-GAN/Metric/dists.py ================================================ # This is a pytoch implementation of DISTS metric. # Requirements: python >= 3.6, pytorch >= 1.0 import numpy as np import os,sys import torch from torchvision import models,transforms import torch.nn as nn import torch.nn.functional as F import argparse import os.path as osp class L2pooling(nn.Module): def __init__(self, filter_size=5, stride=2, channels=None, pad_off=0): super(L2pooling, self).__init__() self.padding = (filter_size - 2 )//2 self.stride = stride self.channels = channels a = np.hanning(filter_size)[1:-1] g = torch.Tensor(a[:,None]*a[None,:]) g = g/torch.sum(g) self.register_buffer('filter', g[None,None,:,:].repeat((self.channels,1,1,1))) def forward(self, input): input = input**2 out = F.conv2d(input, self.filter, stride=self.stride, padding=self.padding, groups=input.shape[1]) return (out+1e-12).sqrt() class DISTS(torch.nn.Module): def __init__(self, load_weights=True): super(DISTS, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=True).features self.stage1 = torch.nn.Sequential() self.stage2 = torch.nn.Sequential() self.stage3 = torch.nn.Sequential() self.stage4 = torch.nn.Sequential() self.stage5 = torch.nn.Sequential() for x in range(0,4): self.stage1.add_module(str(x), vgg_pretrained_features[x]) self.stage2.add_module(str(4), L2pooling(channels=64)) for x in range(5, 9): self.stage2.add_module(str(x), vgg_pretrained_features[x]) self.stage3.add_module(str(9), L2pooling(channels=128)) for x in range(10, 16): self.stage3.add_module(str(x), vgg_pretrained_features[x]) self.stage4.add_module(str(16), L2pooling(channels=256)) for x in range(17, 23): self.stage4.add_module(str(x), vgg_pretrained_features[x]) self.stage5.add_module(str(23), L2pooling(channels=512)) for x in range(24, 30): self.stage5.add_module(str(x), vgg_pretrained_features[x]) for param in self.parameters(): param.requires_grad = False self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1,-1,1,1)) self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1,-1,1,1)) self.chns = [3,64,128,256,512,512] self.register_parameter("alpha", nn.Parameter(torch.randn(1, sum(self.chns),1,1))) self.register_parameter("beta", nn.Parameter(torch.randn(1, sum(self.chns),1,1))) self.alpha.data.normal_(0.1,0.01) self.beta.data.normal_(0.1,0.01) if load_weights: # weights = torch.load(os.path.join(sys.prefix, 'weights.pt')) weights = torch.load('DISTS/DISTS_pytorch/weights.pt') self.alpha.data = weights['alpha'] self.beta.data = weights['beta'] def forward_once(self, x): h = (x-self.mean)/self.std h = self.stage1(h) h_relu1_2 = h h = self.stage2(h) h_relu2_2 = h h = self.stage3(h) h_relu3_3 = h h = self.stage4(h) h_relu4_3 = h h = self.stage5(h) h_relu5_3 = h return [x,h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3] def forward(self, x, y, require_grad=False, batch_average=False): if require_grad: feats0 = self.forward_once(x) feats1 = self.forward_once(y) else: with torch.no_grad(): feats0 = self.forward_once(x) feats1 = self.forward_once(y) dist1 = 0 dist2 = 0 c1 = 1e-6 c2 = 1e-6 w_sum = self.alpha.sum() + self.beta.sum() alpha = torch.split(self.alpha/w_sum, self.chns, dim=1) beta = torch.split(self.beta/w_sum, self.chns, dim=1) for k in range(len(self.chns)): x_mean = feats0[k].mean([2,3], keepdim=True) y_mean = feats1[k].mean([2,3], keepdim=True) S1 = (2*x_mean*y_mean+c1)/(x_mean**2+y_mean**2+c1) dist1 = dist1+(alpha[k]*S1).sum(1,keepdim=True) x_var = ((feats0[k]-x_mean)**2).mean([2,3], keepdim=True) y_var = ((feats1[k]-y_mean)**2).mean([2,3], keepdim=True) xy_cov = (feats0[k]*feats1[k]).mean([2,3],keepdim=True) - x_mean*y_mean S2 = (2*xy_cov+c2)/(x_var+y_var+c2) dist2 = dist2+(beta[k]*S2).sum(1,keepdim=True) score = 1 - (dist1+dist2).squeeze() if batch_average: return score.mean() else: return score def prepare_image(image, resize=True): if resize and min(image.size) > 256: image = transforms.functional.resize(image, 256) image = transforms.ToTensor()(image) return image.unsqueeze(0) if __name__ == '__main__': from PIL import Image import glob os.environ['CUDA_VISIBLE_DEVICES'] = '0' parser = argparse.ArgumentParser() parser.add_argument('--folder_gt', type=str, default='/root/datasets/NTIRE2020-Track1/track1-valid-gt') parser.add_argument('--folder_restored', type=str, default='/root/results/NTIRE2020-Track1') args = parser.parse_args() img_list = sorted(glob.glob(osp.join(args.folder_gt, '*.png'))) lr_list = sorted(glob.glob(osp.join(args.folder_restored, '*.png'))) DISTS_all = [] for i, (gt_path, lr_path) in enumerate(zip(img_list,lr_list)): ref = prepare_image(Image.open(gt_path).convert("RGB"), resize=False) dist = prepare_image(Image.open(lr_path).convert("RGB"), resize=False) assert ref.shape == dist.shape device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = DISTS().to(device) ref = ref.to(device) dist = dist.to(device) score = model(ref, dist) DISTS_all.append(score.item()) log = f'{i + 1:3d}:\tDISTS: {score.item():.6f}.' print(log) # with open(log_path, 'a') as f: # f.write(log + '\n') # # print(log) print(f'Average: DISTS: {sum(DISTS_all) / len(DISTS_all):.6f}') ================================================ FILE: KDSR-GAN/Metric/pip.sh ================================================ pip install lpips --index-url http://pypi.douban.com/simple --trusted-host pypi.douban.com pip install basicsr --index-url http://pypi.douban.com/simple --trusted-host pypi.douban.com ================================================ FILE: KDSR-GAN/README.md ================================================ # KDSR-GAN This project is the official implementation of 'Knowledge Distillation based Degradation Estimation for Blind Super-Resolution', ICLR2023 > **Knowledge Distillation based Degradation Estimation for Blind Super-Resolution [[Paper](https://arxiv.org/pdf/2211.16928.pdf)] [[Project](https://github.com/Zj-BinXia/KDSR)]** This is code for KDSR-GAN (for Real-world SR)

--- ## Dependencies and Installation - Python >= 3.8 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html)) - [PyTorch >= 1.10](https://pytorch.org/) ### Installation Install dependent packages pip install basicsr pip install -r requirements.txt pip install pandas sudo python3 setup.py develop --- ## Dataset Preparation We use the same training datasets as [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) (DF2K+OST). --- ## Training (8 V100 GPUs) 1. We train KDSRNet_T (only using L1 loss) ```bash CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=3309 kdsrgan/train.py -opt options/train_kdsrnet_x4TA.yml --launcher pytorch ``` 2. we train KDSRNet_S (only using L1 loss and KD loss). **It is notable that modify the ''pretrain_network_TA'' and ''pretrain_network_g'' of options/train_kdsrnet_x4ST.yml to the path of trained KDSRNet_T checkpoint.** Then, we run ```bash CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=4349 kdsrgan/train.py -opt options/train_kdsrnet_x4ST.yml --launcher pytorch ``` 3. we train KDSRGAN_S ( using L1 loss, perceptual loss, adversial loss and KD loss). **It is notable that modify the ''pretrain_network_TA'' and ''pretrain_network_g'' of options/train_kdsrnet_x4ST.yml or options/train_kdsrnet_x4STV2.yml to the path of trained KDSRNet_T and KDSRNet_S checkpoint, respectively.** Then, we run ```bash CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=4397 kdsrgan/train.py -opt options/train_kdsrgan_x4ST.yml --launcher pytorch ``` or ```bash CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=4397 kdsrgan/train.py -opt options/train_kdsrgan_x4STV2.yml --launcher pytorch ``` --- ## :european_castle: Model Zoo Please download checkpoints from [Google Drive](https://drive.google.com/drive/folders/1QlOz4F9Mtp9DFXoaHYbnMnRSonR9YFJA). --- ## Testing You can download NTIRE2020 Track1 and NTIRE2020 Track2 and AIM2019 Track2 from [official link](https://competitions.codalab.org/competitions/22220) or [Google Drive](https://drive.google.com/drive/folders/1P5x8wuty3IVj7aKoDe6uZy9pA19S9rrQ?usp=sharing). ```bash python3 kdsrgan/test.py -opt options/test_kdsrgan_x4ST.yml ``` calculate metric ```bash python3 Metric/PSNR.py --folder_gt PathtoGT --folder_restored PathtoSR ``` ```bash python3 Metric/LPIPS.py --folder_gt PathtoGT --folder_restored PathtoSR ``` --- ## Results

--- ## BibTeX @InProceedings{xia2022knowledge, title={Knowledge Distillation based Degradation Estimation for Blind Super-Resolution}, author={Xia, Bin and Zhang, Yulun and Wang, Yitong and Tian, Yapeng and Yang, Wenming and Timofte, Radu and Van Gool, Luc}, journal={ICLR}, year={2023} } ## 📧 Contact If you have any question, please email `zjbinxia@gmail.com`. ================================================ FILE: KDSR-GAN/VERSION ================================================ 0.2.5.0 ================================================ FILE: KDSR-GAN/docs/CONTRIBUTING.md ================================================ # Contributing to Real-ESRGAN :art: Real-ESRGAN needs your contributions. Any contributions are welcome, such as new features/models/typo fixes/suggestions/maintenance, *etc*. See [CONTRIBUTING.md](docs/CONTRIBUTING.md). All contributors are list [here](README.md#hugs-acknowledgement). We like open-source and want to develop practical algorithms for general image restoration. However, individual strength is limited. So, any kinds of contributions are welcome, such as: - New features - New models (your fine-tuned models) - Bug fixes - Typo fixes - Suggestions - Maintenance - Documents - *etc* ## Workflow 1. Fork and pull the latest Real-ESRGAN repository 1. Checkout a new branch (do not use master branch for PRs) 1. Commit your changes 1. Create a PR **Note**: 1. Please check the code style and linting 1. The style configuration is specified in [setup.cfg](setup.cfg) 1. If you use VSCode, the settings are configured in [.vscode/settings.json](.vscode/settings.json) 1. Strongly recommend using `pre-commit hook`. It will check your code style and linting before your commit. 1. In the root path of project folder, run `pre-commit install` 1. The pre-commit configuration is listed in [.pre-commit-config.yaml](.pre-commit-config.yaml) 1. Better to [open a discussion](https://github.com/xinntao/Real-ESRGAN/discussions) before large changes. 1. Welcome to discuss :sunglasses:. I will try my best to join the discussion. ## TODO List :zero: The most straightforward way of improving model performance is to fine-tune on some specific datasets. Here are some TODOs: - [ ] optimize for human faces - [ ] optimize for texts - [ ] support controllable restoration strength :one: There are also [several issues](https://github.com/xinntao/Real-ESRGAN/issues) that require helpers to improve. If you can help, please let me know :smile: ================================================ FILE: KDSR-GAN/docs/FAQ.md ================================================ # FAQ 1. **Q: How to select models?**
A: Please refer to [docs/model_zoo.md](docs/model_zoo.md) 1. **Q: Can `face_enhance` be used for anime images/animation videos?**
A: No, it can only be used for real faces. It is recommended not to use this option for anime images/animation videos to save GPU memory. 1. **Q: Error "slow_conv2d_cpu" not implemented for 'Half'**
A: In order to save GPU memory consumption and speed up inference, Real-ESRGAN uses half precision (fp16) during inference by default. However, some operators for half inference are not implemented in CPU mode. You need to add **`--fp32` option** for the commands. For example, `python inference_realesrgan.py -n RealESRGAN_x4plus.pth -i inputs --fp32`. ================================================ FILE: KDSR-GAN/docs/Training.md ================================================ # :computer: How to Train/Finetune Real-ESRGAN - [Train Real-ESRGAN](#train-real-esrgan) - [Overview](#overview) - [Dataset Preparation](#dataset-preparation) - [Train Real-ESRNet](#Train-Real-ESRNet) - [Train Real-ESRGAN](#Train-Real-ESRGAN) - [Finetune Real-ESRGAN on your own dataset](#Finetune-Real-ESRGAN-on-your-own-dataset) - [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) - [Use paired training data](#use-your-own-paired-data) [English](Training.md) **|** [简体中文](Training_CN.md) ## Train Real-ESRGAN ### Overview The training has been divided into two stages. These two stages have the same data synthesis process and training pipeline, except for the loss functions. Specifically, 1. We first train Real-ESRNet with L1 loss from the pre-trained model ESRGAN. 1. We then use the trained Real-ESRNet model as an initialization of the generator, and train the Real-ESRGAN with a combination of L1 loss, perceptual loss and GAN loss. ### Dataset Preparation We use DF2K (DIV2K and Flickr2K) + OST datasets for our training. Only HR images are required.
You can download from : 1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip 2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar 3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip Here are steps for data preparation. #### Step 1: [Optional] Generate multi-scale images For the DF2K dataset, we use a multi-scale strategy, *i.e.*, we downsample HR images to obtain several Ground-Truth images with different scales.
You can use the [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) script to generate multi-scale images.
Note that this step can be omitted if you just want to have a fast try. ```bash python scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale ``` #### Step 2: [Optional] Crop to sub-images We then crop DF2K images into sub-images for faster IO and processing.
This step is optional if your IO is enough or your disk space is limited. You can use the [scripts/extract_subimages.py](scripts/extract_subimages.py) script. Here is the example: ```bash python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200 ``` #### Step 3: Prepare a txt for meta information You need to prepare a txt file containing the image paths. The following are some examples in `meta_info_DF2Kmultiscale+OST_sub.txt` (As different users may have different sub-images partitions, this file is not suitable for your purpose and you need to prepare your own txt file): ```txt DF2K_HR_sub/000001_s001.png DF2K_HR_sub/000001_s002.png DF2K_HR_sub/000001_s003.png ... ``` You can use the [scripts/generate_meta_info.py](scripts/generate_meta_info.py) script to generate the txt file.
You can merge several folders into one meta_info txt. Here is the example: ```bash python scripts/generate_meta_info.py --input datasets/DF2K/DF2K_HR datasets/DF2K/DF2K_multiscale --root datasets/DF2K datasets/DF2K --meta_info datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt ``` ### Train Real-ESRNet 1. Download pre-trained model [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) into `experiments/pretrained_models`. ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models ``` 1. Modify the content in the option file `options/train_realesrnet_x4plus.yml` accordingly: ```yml train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: datasets/DF2K # modify to the root path of your folder meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt io_backend: type: disk ``` 1. If you want to perform validation during training, uncomment those lines and modify accordingly: ```yml # Uncomment these for validation # val: # name: validation # type: PairedImageDataset # dataroot_gt: path_to_gt # dataroot_lq: path_to_lq # io_backend: # type: disk ... # Uncomment these for validation # validation settings # val: # val_freq: !!float 5e3 # save_img: True # metrics: # psnr: # metric name, can be arbitrary # type: calculate_psnr # crop_border: 4 # test_y_channel: false ``` 1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug ``` Train with **a single GPU** in the *debug* mode: ```bash python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug ``` 1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume ``` Train with **a single GPU**: ```bash python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume ``` ### Train Real-ESRGAN 1. After the training of Real-ESRNet, you now have the file `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth`. If you need to specify the pre-trained path to other files, modify the `pretrain_network_g` value in the option file `train_realesrgan_x4plus.yml`. 1. Modify the option file `train_realesrgan_x4plus.yml` accordingly. Most modifications are similar to those listed above. 1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug ``` Train with **a single GPU** in the *debug* mode: ```bash python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug ``` 1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume ``` Train with **a single GPU**: ```bash python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume ``` ## Finetune Real-ESRGAN on your own dataset You can finetune Real-ESRGAN on your own dataset. Typically, the fine-tuning process can be divided into two cases: 1. [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) 1. [Use your own **paired** data](#Use-paired-training-data) ### Generate degraded images on the fly Only high-resolution images are required. The low-quality images are generated with the degradation process described in Real-ESRGAN during trainig. **1. Prepare dataset** See [this section](#dataset-preparation) for more details. **2. Download pre-trained models** Download pre-trained models into `experiments/pretrained_models`. - *RealESRGAN_x4plus.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models ``` - *RealESRGAN_x4plus_netD.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models ``` **3. Finetune** Modify [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) accordingly, especially the `datasets` part: ```yml train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: datasets/DF2K # modify to the root path of your folder meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt io_backend: type: disk ``` We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume ``` Finetune with **a single GPU**: ```bash python realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume ``` ### Use your own paired data You can also finetune RealESRGAN with your own paired data. It is more similar to fine-tuning ESRGAN. **1. Prepare dataset** Assume that you already have two folders: - **gt folder** (Ground-truth, high-resolution images): *datasets/DF2K/DIV2K_train_HR_sub* - **lq folder** (Low quality, low-resolution images): *datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub* Then, you can prepare the meta_info txt file using the script [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py): ```bash python scripts/generate_meta_info_pairdata.py --input datasets/DF2K/DIV2K_train_HR_sub datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub --meta_info datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt ``` **2. Download pre-trained models** Download pre-trained models into `experiments/pretrained_models`. - *RealESRGAN_x4plus.pth* ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models ``` - *RealESRGAN_x4plus_netD.pth* ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models ``` **3. Finetune** Modify [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) accordingly, especially the `datasets` part: ```yml train: name: DIV2K type: RealESRGANPairedDataset dataroot_gt: datasets/DF2K # modify to the root path of your folder dataroot_lq: datasets/DF2K # modify to the root path of your folder meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt # modify to your own generate meta info txt io_backend: type: disk ``` We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --launcher pytorch --auto_resume ``` Finetune with **a single GPU**: ```bash python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume ``` ================================================ FILE: KDSR-GAN/docs/Training_CN.md ================================================ # :computer: 如何训练/微调 Real-ESRGAN - [训练 Real-ESRGAN](#训练-real-esrgan) - [概述](#概述) - [准备数据集](#准备数据集) - [训练 Real-ESRNet 模型](#训练-real-esrnet-模型) - [训练 Real-ESRGAN 模型](#训练-real-esrgan-模型) - [用自己的数据集微调 Real-ESRGAN](#用自己的数据集微调-real-esrgan) - [动态生成降级图像](#动态生成降级图像) - [使用已配对的数据](#使用已配对的数据) [English](Training.md) **|** [简体中文](Training_CN.md) ## 训练 Real-ESRGAN ### 概述 训练分为两个步骤。除了 loss 函数外,这两个步骤拥有相同数据合成以及训练的一条龙流程。具体点说: 1. 首先使用 L1 loss 训练 Real-ESRNet 模型,其中 L1 loss 来自预先训练的 ESRGAN 模型。 2. 然后我们将 Real-ESRNet 模型作为生成器初始化,结合L1 loss、感知 loss、GAN loss 三者的参数对 Real-ESRGAN 进行训练。 ### 准备数据集 我们使用 DF2K ( DIV2K 和 Flickr2K ) + OST 数据集进行训练。只需要HR图像!
下面是网站链接: 1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip 2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar 3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip 以下是数据的准备步骤。 #### 第1步:【可选】生成多尺寸图片 针对 DF2K 数据集,我们使用多尺寸缩放策略,*换言之*,我们对 HR 图像进行下采样,就能获得多尺寸的标准参考(Ground-Truth)图像。
您可以使用这个 [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) 脚本快速生成多尺寸的图像。
注意:如果您只想简单试试,那么可以跳过此步骤。 ```bash python scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale ``` #### 第2步:【可选】裁切为子图像 我们可以将 DF2K 图像裁切为子图像,以加快 IO 和处理速度。
如果你的 IO 够好或储存空间有限,那么此步骤是可选的。
您可以使用脚本 [scripts/extract_subimages.py](scripts/extract_subimages.py)。这是使用示例: ```bash python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200 ``` #### 第3步:准备元信息 txt 您需要准备一个包含图像路径的 txt 文件。下面是 `meta_info_DF2Kmultiscale+OST_sub.txt` 中的部分展示(由于各个用户可能有截然不同的子图像划分,这个文件不适合你的需求,你得准备自己的 txt 文件): ```txt DF2K_HR_sub/000001_s001.png DF2K_HR_sub/000001_s002.png DF2K_HR_sub/000001_s003.png ... ``` 你可以使用该脚本 [scripts/generate_meta_info.py](scripts/generate_meta_info.py) 生成包含图像路径的 txt 文件。
你还可以合并多个文件夹的图像路径到一个元信息(meta_info)txt。这是使用示例: ```bash python scripts/generate_meta_info.py --input datasets/DF2K/DF2K_HR, datasets/DF2K/DF2K_multiscale --root datasets/DF2K, datasets/DF2K --meta_info datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt ``` ### 训练 Real-ESRNet 模型 1. 下载预先训练的模型 [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth),放到 `experiments/pretrained_models`目录下。 ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models ``` 2. 相应地修改选项文件 `options/train_realesrnet_x4plus.yml` 中的内容: ```yml train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: datasets/DF2K # 修改为你的数据集文件夹根目录 meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # 修改为你自己生成的元信息txt io_backend: type: disk ``` 3. 如果你想在训练过程中执行验证,就取消注释这些内容并进行相应的修改: ```yml # 取消注释这些以进行验证 # val: # name: validation # type: PairedImageDataset # dataroot_gt: path_to_gt # dataroot_lq: path_to_lq # io_backend: # type: disk ... # 取消注释这些以进行验证 # 验证设置 # val: # val_freq: !!float 5e3 # save_img: True # metrics: # psnr: # 指标名称,可以是任意的 # type: calculate_psnr # crop_border: 4 # test_y_channel: false ``` 4. 正式训练之前,你可以用 `--debug` 模式检查是否正常运行。我们用了4个GPU进行训练: ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug ``` 用 **1个GPU** 训练的 debug 模式示例: ```bash python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug ``` 5. 正式训练开始。我们用了4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume ``` 用 **1个GPU** 训练: ```bash python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume ``` ### 训练 Real-ESRGAN 模型 1. 训练 Real-ESRNet 模型后,您得到了这个 `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth` 文件。如果需要指定预训练路径到其他文件,请修改选项文件 `train_realesrgan_x4plus.yml` 中 `pretrain_network_g` 的值。 1. 修改选项文件 `train_realesrgan_x4plus.yml` 的内容。大多数修改与上节提到的类似。 1. 正式训练之前,你可以以 `--debug` 模式检查是否正常运行。我们使用了4个GPU进行训练: ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug ``` 用 **1个GPU** 训练的 debug 模式示例: ```bash python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug ``` 1. 正式训练开始。我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume ``` 用 **1个GPU** 训练: ```bash python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume ``` ## 用自己的数据集微调 Real-ESRGAN 你可以用自己的数据集微调 Real-ESRGAN。一般地,微调(Fine-Tune)程序可以分为两种类型: 1. [动态生成降级图像](#动态生成降级图像) 2. [使用**已配对**的数据](#使用已配对的数据) ### 动态生成降级图像 只需要高分辨率图像。在训练过程中,使用 Real-ESRGAN 描述的降级模型生成低质量图像。 **1. 准备数据集** 完整信息请参见[本节](#准备数据集)。 **2. 下载预训练模型** 下载预先训练的模型到 `experiments/pretrained_models` 目录下。 - *RealESRGAN_x4plus.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models ``` - *RealESRGAN_x4plus_netD.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models ``` **3. 微调** 修改选项文件 [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) ,特别是 `datasets` 部分: ```yml train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: datasets/DF2K # 修改为你的数据集文件夹根目录 meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # 修改为你自己生成的元信息txt io_backend: type: disk ``` 我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume ``` 用 **1个GPU** 训练: ```bash python realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume ``` ### 使用已配对的数据 你还可以用自己已经配对的数据微调 RealESRGAN。这个过程更类似于微调 ESRGAN。 **1. 准备数据集** 假设你已经有两个文件夹(folder): - **gt folder**(标准参考,高分辨率图像):*datasets/DF2K/DIV2K_train_HR_sub* - **lq folder**(低质量,低分辨率图像):*datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub* 然后,您可以使用脚本 [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py) 生成元信息(meta_info)txt 文件。 ```bash python scripts/generate_meta_info_pairdata.py --input datasets/DF2K/DIV2K_train_HR_sub datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub --meta_info datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt ``` **2. 下载预训练模型** 下载预先训练的模型到 `experiments/pretrained_models` 目录下。 - *RealESRGAN_x4plus.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models ``` - *RealESRGAN_x4plus_netD.pth*: ```bash wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models ``` **3. 微调** 修改选项文件 [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) ,特别是 `datasets` 部分: ```yml train: name: DIV2K type: RealESRGANPairedDataset dataroot_gt: datasets/DF2K # 修改为你的 gt folder 文件夹根目录 dataroot_lq: datasets/DF2K # 修改为你的 lq folder 文件夹根目录 meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt # 修改为你自己生成的元信息txt io_backend: type: disk ``` 我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 ```bash CUDA_VISIBLE_DEVICES=0,1,2,3 \ python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --launcher pytorch --auto_resume ``` 用 **1个GPU** 训练: ```bash python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume ``` ================================================ FILE: KDSR-GAN/docs/anime_comparisons.md ================================================ # Comparisons among different anime models [English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md) ## Update News - 2022/04/24: Release **AnimeVideo-v3**. We have made the following improvements: - **better naturalness** - **Fewer artifacts** - **more faithful to the original colors** - **better texture restoration** - **better background restoration** ## Comparisons We have compared our RealESRGAN-AnimeVideo-v3 with the following methods. Our RealESRGAN-AnimeVideo-v3 can achieve better results with faster inference speed. - [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) with the hyperparameters: `tile=0`, `noiselevel=2` - [Real-CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN): we use the [20220227](https://github.com/bilibili/ailab/releases/tag/Real-CUGAN-add-faster-low-memory-mode) version, the hyperparameters are: `cache_mode=0`, `tile=0`, `alpha=1`. - our RealESRGAN-AnimeVideo-v3 ## Results You may need to **zoom in** for comparing details, or **click the image** to see in the full size. Please note that the images in the table below are the resized and cropped patches from the original images, you can download the original inputs and outputs from [Google Drive](https://drive.google.com/drive/folders/1bc_Hje1Nqop9NDkUvci2VACSjL7HZMRp?usp=sharing) . **More natural results, better background restoration** | Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![157083983-bec52c67-9a5e-4eed-afef-01fe6cd2af85_patch](https://user-images.githubusercontent.com/11482921/164452769-5d8cb4f8-1708-42d2-b941-f44a6f136feb.png) | ![](https://user-images.githubusercontent.com/11482921/164452767-c825cdec-f721-4ff1-aef1-fec41f146c4c.png) | ![](https://user-images.githubusercontent.com/11482921/164452755-3be50895-e3d4-432d-a7b9-9085c2a8e771.png) | ![](https://user-images.githubusercontent.com/11482921/164452771-be300656-379a-4323-a755-df8025a8c451.png) | |![a0010_patch](https://user-images.githubusercontent.com/11482921/164454047-22eeb493-3fa9-4142-9fc2-6f2a1c074cd5.png) | ![](https://user-images.githubusercontent.com/11482921/164454046-d5e79f8f-00a0-4b55-bc39-295d0d69747a.png) | ![](https://user-images.githubusercontent.com/11482921/164454040-87886b11-9d08-48bd-862f-0d4aed72eb19.png) | ![](https://user-images.githubusercontent.com/11482921/164454055-73dc9f02-286e-4d5c-8f70-c13742e08f42.png) | |![00000044_patch](https://user-images.githubusercontent.com/11482921/164451232-bacf64fc-e55a-44db-afbb-6b31ab0f8973.png) | ![](https://user-images.githubusercontent.com/11482921/164451318-f309b61a-75b8-4b74-b5f3-595725f1cf0b.png) | ![](https://user-images.githubusercontent.com/11482921/164451348-994f8a35-adbe-4a4b-9c61-feaa294af06a.png) | ![](https://user-images.githubusercontent.com/11482921/164451361-9b7d376e-6f75-4648-b752-542b44845d1c.png) | **Fewer artifacts, better detailed textures** | Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![00000053_patch](https://user-images.githubusercontent.com/11482921/164448411-148a7e5c-cfcd-4504-8bc7-e318eb883bb6.png) | ![](https://user-images.githubusercontent.com/11482921/164448633-dfc15224-b6d2-4403-a3c9-4bb819979364.png) | ![](https://user-images.githubusercontent.com/11482921/164448771-0d359509-5293-4d4c-8e3c-86a2a314ea88.png) | ![](https://user-images.githubusercontent.com/11482921/164448848-1a4ff99e-075b-4458-9db7-2c89e8160aa0.png) | |![Disney_v4_22_018514_s2_patch](https://user-images.githubusercontent.com/11482921/164451898-83311cdf-bd3e-450f-b9f6-34d7fea3ab79.png) | ![](https://user-images.githubusercontent.com/11482921/164451894-6c56521c-6561-40d6-a3a5-8dde2c167b8a.png) | ![](https://user-images.githubusercontent.com/11482921/164451888-af9b47e3-39dc-4f3e-b0d7-d372d8191e2a.png) | ![](https://user-images.githubusercontent.com/11482921/164451901-31ca4dd4-9847-4baa-8cde-ad50f4053dcf.png) | |![Japan_v2_0_007261_s2_patch](https://user-images.githubusercontent.com/11482921/164454578-73c77392-77de-49c5-b03c-c36631723192.png) | ![](https://user-images.githubusercontent.com/11482921/164454574-b1ede5f0-4520-4eaa-8f59-086751a34e62.png) | ![](https://user-images.githubusercontent.com/11482921/164454567-4cb3fdd8-6a2d-4016-85b2-a305a8ff80e4.png) | ![](https://user-images.githubusercontent.com/11482921/164454583-7f243f20-eca3-4500-ac43-eb058a4a101a.png) | |![huluxiongdi_2_patch](https://user-images.githubusercontent.com/11482921/164453482-0726c842-337e-40ec-bf6c-f902ee956a8b.png) | ![](https://user-images.githubusercontent.com/11482921/164453480-71d5e091-5bfa-4c77-9c57-4e37f66ca0a3.png) | ![](https://user-images.githubusercontent.com/11482921/164453468-c295d3c9-3661-45f0-9ecd-406a1877f76e.png) | ![](https://user-images.githubusercontent.com/11482921/164453486-3091887c-587c-450e-b6fe-905cb518d57e.png) | **Other better results** | Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![Japan_v2_1_128525_s1_patch](https://user-images.githubusercontent.com/11482921/164454933-67697f7c-b6ef-47dc-bfca-822a78af8acf.png) | ![](https://user-images.githubusercontent.com/11482921/164454931-9450de7c-f0b3-4638-9c1e-0668e0c41ef0.png) | ![](https://user-images.githubusercontent.com/11482921/164454926-ed746976-786d-41c5-8a83-7693cd774c3a.png) | ![](https://user-images.githubusercontent.com/11482921/164454936-8abdf0f0-fb30-40eb-8281-3b46c0bcb9ae.png) | |![tianshuqitan_2_patch](https://user-images.githubusercontent.com/11482921/164456948-807c1476-90b6-4507-81da-cb986d01600c.png) | ![](https://user-images.githubusercontent.com/11482921/164456943-25e89de9-d7e5-4f61-a2e1-96786af6ae9e.png) | ![](https://user-images.githubusercontent.com/11482921/164456954-b468c447-59f5-4594-9693-3683e44ba3e6.png) | ![](https://user-images.githubusercontent.com/11482921/164456957-640f910c-3b04-407c-ac20-044d72e19735.png) | |![00000051_patch](https://user-images.githubusercontent.com/11482921/164456044-e9a6b3fa-b24e-4eb7-acf9-1f7746551b1e.png) ![00000051_patch](https://user-images.githubusercontent.com/11482921/164456421-b67245b0-767d-4250-9105-80bbe507ecfc.png) | ![](https://user-images.githubusercontent.com/11482921/164456040-85763cf2-cb28-4ba3-abb6-1dbb48c55713.png) ![](https://user-images.githubusercontent.com/11482921/164456419-59cf342e-bc1e-4044-868c-e1090abad313.png) | ![](https://user-images.githubusercontent.com/11482921/164456031-4244bb7b-8649-4e01-86f4-40c2099c5afd.png) ![](https://user-images.githubusercontent.com/11482921/164456411-b6afcbe9-c054-448d-a6df-96d3ba3047f8.png) | ![](https://user-images.githubusercontent.com/11482921/164456035-12e270be-fd52-46d4-b18a-3d3b680731fe.png) ![](https://user-images.githubusercontent.com/11482921/164456417-dcaa8b62-f497-427d-b2d2-f390f1200fb9.png) | |![00000099_patch](https://user-images.githubusercontent.com/11482921/164455312-6411b6e1-5823-4131-a4b0-a6be8a9ae89f.png) | ![](https://user-images.githubusercontent.com/11482921/164455310-f2b99646-3a22-47a4-805b-dc451ac86ddb.png) | ![](https://user-images.githubusercontent.com/11482921/164455294-35471b42-2826-4451-b7ec-6de01344954c.png) | ![](https://user-images.githubusercontent.com/11482921/164455305-fa4c9758-564a-4081-8b4e-f11057a0404d.png) | |![00000016_patch](https://user-images.githubusercontent.com/11482921/164455672-447353c9-2da2-4fcb-ba4a-7dd6b94c19c1.png) | ![](https://user-images.githubusercontent.com/11482921/164455669-df384631-baaa-42f8-9150-40f658471558.png) | ![](https://user-images.githubusercontent.com/11482921/164455657-68006bf0-138d-4981-aaca-8aa927d2f78a.png) | ![](https://user-images.githubusercontent.com/11482921/164455664-0342b93e-a62a-4b36-a90e-7118f3f1e45d.png) | ## Inference Speed ### PyTorch Note that we only report the **model** time, and ignore the IO time. | GPU | Input Resolution | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3 | :---: | :---: | :---: | :---: | :---: | | V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps | | V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps | | V100 | 640 x 480 | - | 24.4 fps | **65.9** fps | ### ncnn - [ ] TODO ================================================ FILE: KDSR-GAN/docs/anime_comparisons_CN.md ================================================ # 动漫视频模型比较 [English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md) ## 更新 - 2022/04/24: 发布 **AnimeVideo-v3**. 主要做了以下更新: - **更自然** - **更少瑕疵** - **颜色保持得更好** - **更好的纹理恢复** - **虚化背景处理** ## 比较 我们将 RealESRGAN-AnimeVideo-v3 与以下方法进行了比较。我们的 RealESRGAN-AnimeVideo-v3 可以以更快的推理速度获得更好的结果。 - [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). 超参数: `tile=0`, `noiselevel=2` - [Real-CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN): 我们使用了[20220227](https://github.com/bilibili/ailab/releases/tag/Real-CUGAN-add-faster-low-memory-mode)版本, 超参: `cache_mode=0`, `tile=0`, `alpha=1`. - 我们的 RealESRGAN-AnimeVideo-v3 ## 结果 您可能需要**放大**以比较详细信息, 或者**单击图像**以查看完整尺寸。 请注意下面表格的图片是从原图里裁剪patch并且resize后的结果,您可以从 [Google Drive](https://drive.google.com/drive/folders/1bc_Hje1Nqop9NDkUvci2VACSjL7HZMRp?usp=sharing) 里下载原始的输入和输出。 **更自然的结果,更好的虚化背景恢复** | 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![157083983-bec52c67-9a5e-4eed-afef-01fe6cd2af85_patch](https://user-images.githubusercontent.com/11482921/164452769-5d8cb4f8-1708-42d2-b941-f44a6f136feb.png) | ![](https://user-images.githubusercontent.com/11482921/164452767-c825cdec-f721-4ff1-aef1-fec41f146c4c.png) | ![](https://user-images.githubusercontent.com/11482921/164452755-3be50895-e3d4-432d-a7b9-9085c2a8e771.png) | ![](https://user-images.githubusercontent.com/11482921/164452771-be300656-379a-4323-a755-df8025a8c451.png) | |![a0010_patch](https://user-images.githubusercontent.com/11482921/164454047-22eeb493-3fa9-4142-9fc2-6f2a1c074cd5.png) | ![](https://user-images.githubusercontent.com/11482921/164454046-d5e79f8f-00a0-4b55-bc39-295d0d69747a.png) | ![](https://user-images.githubusercontent.com/11482921/164454040-87886b11-9d08-48bd-862f-0d4aed72eb19.png) | ![](https://user-images.githubusercontent.com/11482921/164454055-73dc9f02-286e-4d5c-8f70-c13742e08f42.png) | |![00000044_patch](https://user-images.githubusercontent.com/11482921/164451232-bacf64fc-e55a-44db-afbb-6b31ab0f8973.png) | ![](https://user-images.githubusercontent.com/11482921/164451318-f309b61a-75b8-4b74-b5f3-595725f1cf0b.png) | ![](https://user-images.githubusercontent.com/11482921/164451348-994f8a35-adbe-4a4b-9c61-feaa294af06a.png) | ![](https://user-images.githubusercontent.com/11482921/164451361-9b7d376e-6f75-4648-b752-542b44845d1c.png) | **更少瑕疵,更好的细节纹理** | 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![00000053_patch](https://user-images.githubusercontent.com/11482921/164448411-148a7e5c-cfcd-4504-8bc7-e318eb883bb6.png) | ![](https://user-images.githubusercontent.com/11482921/164448633-dfc15224-b6d2-4403-a3c9-4bb819979364.png) | ![](https://user-images.githubusercontent.com/11482921/164448771-0d359509-5293-4d4c-8e3c-86a2a314ea88.png) | ![](https://user-images.githubusercontent.com/11482921/164448848-1a4ff99e-075b-4458-9db7-2c89e8160aa0.png) | |![Disney_v4_22_018514_s2_patch](https://user-images.githubusercontent.com/11482921/164451898-83311cdf-bd3e-450f-b9f6-34d7fea3ab79.png) | ![](https://user-images.githubusercontent.com/11482921/164451894-6c56521c-6561-40d6-a3a5-8dde2c167b8a.png) | ![](https://user-images.githubusercontent.com/11482921/164451888-af9b47e3-39dc-4f3e-b0d7-d372d8191e2a.png) | ![](https://user-images.githubusercontent.com/11482921/164451901-31ca4dd4-9847-4baa-8cde-ad50f4053dcf.png) | |![Japan_v2_0_007261_s2_patch](https://user-images.githubusercontent.com/11482921/164454578-73c77392-77de-49c5-b03c-c36631723192.png) | ![](https://user-images.githubusercontent.com/11482921/164454574-b1ede5f0-4520-4eaa-8f59-086751a34e62.png) | ![](https://user-images.githubusercontent.com/11482921/164454567-4cb3fdd8-6a2d-4016-85b2-a305a8ff80e4.png) | ![](https://user-images.githubusercontent.com/11482921/164454583-7f243f20-eca3-4500-ac43-eb058a4a101a.png) | |![huluxiongdi_2_patch](https://user-images.githubusercontent.com/11482921/164453482-0726c842-337e-40ec-bf6c-f902ee956a8b.png) | ![](https://user-images.githubusercontent.com/11482921/164453480-71d5e091-5bfa-4c77-9c57-4e37f66ca0a3.png) | ![](https://user-images.githubusercontent.com/11482921/164453468-c295d3c9-3661-45f0-9ecd-406a1877f76e.png) | ![](https://user-images.githubusercontent.com/11482921/164453486-3091887c-587c-450e-b6fe-905cb518d57e.png) | **其他更好的结果** | 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | | :---: | :---: | :---: | :---: | |![Japan_v2_1_128525_s1_patch](https://user-images.githubusercontent.com/11482921/164454933-67697f7c-b6ef-47dc-bfca-822a78af8acf.png) | ![](https://user-images.githubusercontent.com/11482921/164454931-9450de7c-f0b3-4638-9c1e-0668e0c41ef0.png) | ![](https://user-images.githubusercontent.com/11482921/164454926-ed746976-786d-41c5-8a83-7693cd774c3a.png) | ![](https://user-images.githubusercontent.com/11482921/164454936-8abdf0f0-fb30-40eb-8281-3b46c0bcb9ae.png) | |![tianshuqitan_2_patch](https://user-images.githubusercontent.com/11482921/164456948-807c1476-90b6-4507-81da-cb986d01600c.png) | ![](https://user-images.githubusercontent.com/11482921/164456943-25e89de9-d7e5-4f61-a2e1-96786af6ae9e.png) | ![](https://user-images.githubusercontent.com/11482921/164456954-b468c447-59f5-4594-9693-3683e44ba3e6.png) | ![](https://user-images.githubusercontent.com/11482921/164456957-640f910c-3b04-407c-ac20-044d72e19735.png) | |![00000051_patch](https://user-images.githubusercontent.com/11482921/164456044-e9a6b3fa-b24e-4eb7-acf9-1f7746551b1e.png) ![00000051_patch](https://user-images.githubusercontent.com/11482921/164456421-b67245b0-767d-4250-9105-80bbe507ecfc.png) | ![](https://user-images.githubusercontent.com/11482921/164456040-85763cf2-cb28-4ba3-abb6-1dbb48c55713.png) ![](https://user-images.githubusercontent.com/11482921/164456419-59cf342e-bc1e-4044-868c-e1090abad313.png) | ![](https://user-images.githubusercontent.com/11482921/164456031-4244bb7b-8649-4e01-86f4-40c2099c5afd.png) ![](https://user-images.githubusercontent.com/11482921/164456411-b6afcbe9-c054-448d-a6df-96d3ba3047f8.png) | ![](https://user-images.githubusercontent.com/11482921/164456035-12e270be-fd52-46d4-b18a-3d3b680731fe.png) ![](https://user-images.githubusercontent.com/11482921/164456417-dcaa8b62-f497-427d-b2d2-f390f1200fb9.png) | |![00000099_patch](https://user-images.githubusercontent.com/11482921/164455312-6411b6e1-5823-4131-a4b0-a6be8a9ae89f.png) | ![](https://user-images.githubusercontent.com/11482921/164455310-f2b99646-3a22-47a4-805b-dc451ac86ddb.png) | ![](https://user-images.githubusercontent.com/11482921/164455294-35471b42-2826-4451-b7ec-6de01344954c.png) | ![](https://user-images.githubusercontent.com/11482921/164455305-fa4c9758-564a-4081-8b4e-f11057a0404d.png) | |![00000016_patch](https://user-images.githubusercontent.com/11482921/164455672-447353c9-2da2-4fcb-ba4a-7dd6b94c19c1.png) | ![](https://user-images.githubusercontent.com/11482921/164455669-df384631-baaa-42f8-9150-40f658471558.png) | ![](https://user-images.githubusercontent.com/11482921/164455657-68006bf0-138d-4981-aaca-8aa927d2f78a.png) | ![](https://user-images.githubusercontent.com/11482921/164455664-0342b93e-a62a-4b36-a90e-7118f3f1e45d.png) | ## 推理速度比较 ### PyTorch 请注意,我们只报告了**模型推理**的时间, 而忽略了读写硬盘的时间. | GPU | 输入尺寸 | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3 | :---: | :---: | :---: | :---: | :---: | | V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps | | V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps | | V100 | 640 x 480 | - | 24.4 fps | **65.9** fps | ### ncnn - [ ] TODO ================================================ FILE: KDSR-GAN/docs/anime_model.md ================================================ # Anime Model :white_check_mark: We add [*RealESRGAN_x4plus_anime_6B.pth*](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth), which is optimized for **anime** images with much smaller model size. - [How to Use](#how-to-use) - [PyTorch Inference](#pytorch-inference) - [ncnn Executable File](#ncnn-executable-file) - [Comparisons with waifu2x](#comparisons-with-waifu2x) - [Comparisons with Sliding Bars](#comparisons-with-sliding-bars)

The following is a video comparison with sliding bar. You may need to use the full-screen mode for better visual quality, as the original image is large; otherwise, you may encounter aliasing issue. ## How to Use ### PyTorch Inference Pre-trained models: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) ```bash # download model wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P experiments/pretrained_models # inference python inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs ``` ### ncnn Executable File Download the latest portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU**. Taking the Windows as example, run: ```bash ./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n realesrgan-x4plus-anime ``` ## Comparisons with waifu2x We compare Real-ESRGAN-anime with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). We use the `-n 2 -s 4` for waifu2x.

## Comparisons with Sliding Bars The following are video comparisons with sliding bar. You may need to use the full-screen mode for better visual quality, as the original image is large; otherwise, you may encounter aliasing issue. ================================================ FILE: KDSR-GAN/docs/anime_video_model.md ================================================ # Anime Video Models :white_check_mark: We add small models that are optimized for anime videos :-)
More comparisons can be found in [anime_comparisons.md](anime_comparisons.md) - [How to Use](#how-to-use) - [PyTorch Inference](#pytorch-inference) - [ncnn Executable File](#ncnn-executable-file) - [Step 1: Use ffmpeg to extract frames from video](#step-1-use-ffmpeg-to-extract-frames-from-video) - [Step 2: Inference with Real-ESRGAN executable file](#step-2-inference-with-real-esrgan-executable-file) - [Step 3: Merge the enhanced frames back into a video](#step-3-merge-the-enhanced-frames-back-into-a-video) - [More Demos](#more-demos) | Models | Scale | Description | | ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- | | [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X4 1 | Anime video model with XS size | Note:
1 This model can also be used for X1, X2, X3. --- The following are some demos (best view in the full screen mode). ## How to Use ### PyTorch Inference ```bash # download model wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P realesrgan/weights # single gpu and single process inference CUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 # single gpu and multi process inference (you can use multi-processing to improve GPU utilization) CUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2 # multi gpu and multi process inference CUDA_VISIBLE_DEVICES=0,1,2,3 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2 ``` ```console Usage: --num_process_per_gpu The total number of process is num_gpu * num_process_per_gpu. The bottleneck of the program lies on the IO, so the GPUs are usually not fully utilized. To alleviate this issue, you can use multi-processing by setting this parameter. As long as it does not exceed the CUDA memory --extract_frame_first If you encounter ffmpeg error when using multi-processing, you can turn this option on. ``` ### NCNN Executable File #### Step 1: Use ffmpeg to extract frames from video ```bash ffmpeg -i onepiece_demo.mp4 -qscale:v 1 -qmin 1 -qmax 1 -vsync 0 tmp_frames/frame%08d.png ``` - Remember to create the folder `tmp_frames` ahead #### Step 2: Inference with Real-ESRGAN executable file 1. Download the latest portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU** 1. Taking the Windows as example, run: ```bash ./realesrgan-ncnn-vulkan.exe -i tmp_frames -o out_frames -n realesr-animevideov3 -s 2 -f jpg ``` - Remember to create the folder `out_frames` ahead #### Step 3: Merge the enhanced frames back into a video 1. First obtain fps from input videos by ```bash ffmpeg -i onepiece_demo.mp4 ``` ```console Usage: -i input video path ``` You will get the output similar to the following screenshot.

2. Merge frames ```bash ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -c:v libx264 -r 23.98 -pix_fmt yuv420p output.mp4 ``` ```console Usage: -i input video path -c:v video encoder (usually we use libx264) -r fps, remember to modify it to meet your needs -pix_fmt pixel format in video ``` If you also want to copy audio from the input videos, run: ```bash ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -i onepiece_demo.mp4 -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r 23.98 -pix_fmt yuv420p output_w_audio.mp4 ``` ```console Usage: -i input video path, here we use two input streams -c:v video encoder (usually we use libx264) -r fps, remember to modify it to meet your needs -pix_fmt pixel format in video ``` ## More Demos - Input video for One Piece: - Out video for One Piece **More comparisons** ================================================ FILE: KDSR-GAN/docs/feedback.md ================================================ # Feedback 反馈 ## 动漫插画模型 1. 视频处理不了: 目前的模型,不是针对视频的,所以视频效果很很不好。我们在探究针对视频的模型了 1. 景深虚化有问题: 现在的模型把一些景深 和 特意的虚化 都复原了,感觉不好。这个后面我们会考虑把这个信息结合进入。一个简单的做法是识别景深和虚化,然后作为条件告诉神经网络,哪些地方复原强一些,哪些地方复原要弱一些 1. 不可以调节: 像 Waifu2X 可以调节。可以根据自己的喜好,做调整,但是 Real-ESRGAN-anime 并不可以。导致有些恢复效果过了 1. 把原来的风格改变了: 不同的动漫插画都有自己的风格,现在的 Real-ESRGAN-anime 倾向于恢复成一种风格(这是受到训练数据集影响的)。风格是动漫很重要的一个要素,所以要尽可能保持 1. 模型太大: 目前的模型处理太慢,能够更快。这个我们有相关的工作在探究,希望能够尽快有结果,并应用到 Real-ESRGAN 这一系列的模型上 Thanks for the [detailed and valuable feedbacks/suggestions](https://github.com/xinntao/Real-ESRGAN/issues/131) by [2ji3150](https://github.com/2ji3150). ================================================ FILE: KDSR-GAN/docs/model_zoo.md ================================================ # :european_castle: Model Zoo - [For General Images](#for-general-images) - [For Anime Images](#for-anime-images) - [For Anime Videos](#for-anime-videos) --- ## For General Images | Models | Scale | Description | | ------------------------------------------------------------------------------------------------------------------------------- | :---- | :------------------------------------------- | | [RealESRGAN_x4plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth) | X4 | X4 model for general images | | [RealESRGAN_x2plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth) | X2 | X2 model for general images | | [RealESRNet_x4plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth) | X4 | X4 model with MSE loss (over-smooth effects) | | [official ESRGAN_x4](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) | X4 | official ESRGAN model | The following models are **discriminators**, which are usually used for fine-tuning. | Models | Corresponding model | | ---------------------------------------------------------------------------------------------------------------------- | :------------------ | | [RealESRGAN_x4plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth) | RealESRGAN_x4plus | | [RealESRGAN_x2plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x2plus_netD.pth) | RealESRGAN_x2plus | ## For Anime Images / Illustrations | Models | Scale | Description | | ------------------------------------------------------------------------------------------------------------------------------ | :---- | :---------------------------------------------------------- | | [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) | X4 | Optimized for anime images; 6 RRDB blocks (smaller network) | The following models are **discriminators**, which are usually used for fine-tuning. | Models | Corresponding model | | ---------------------------------------------------------------------------------------------------------------------------------------- | :------------------------- | | [RealESRGAN_x4plus_anime_6B_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B_netD.pth) | RealESRGAN_x4plus_anime_6B | ## For Animation Videos | Models | Scale | Description | | ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- | | [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X41 | Anime video model with XS size | Note:
1 This model can also be used for X1, X2, X3. The following models are **discriminators**, which are usually used for fine-tuning. TODO ================================================ FILE: KDSR-GAN/docs/ncnn_conversion.md ================================================ # Instructions on converting to NCNN models 1. Convert to onnx model with `scripts/pytorch2onnx.py`. Remember to modify codes accordingly 1. Convert onnx model to ncnn model 1. `cd ncnn-master\ncnn\build\tools\onnx` 1. `onnx2ncnn.exe realesrgan-x4.onnx realesrgan-x4-raw.param realesrgan-x4-raw.bin` 1. Optimize ncnn model 1. fp16 mode 1. `cd ncnn-master\ncnn\build\tools` 1. `ncnnoptimize.exe realesrgan-x4-raw.param realesrgan-x4-raw.bin realesrgan-x4.param realesrgan-x4.bin 1` 1. Modify the blob name in `realesrgan-x4.param`: `data` and `output` ================================================ FILE: KDSR-GAN/kdsrgan/__init__.py ================================================ # flake8: noqa from .losses import * from .archs import * from .data import * from .models import * from .utils import * from .version import * ================================================ FILE: KDSR-GAN/kdsrgan/archs/ST_arch.py ================================================ from basicsr.utils.registry import ARCH_REGISTRY from torch.nn import functional as F import torch from torch import nn import kdsrgan.archs.common as common class IDR_DDC(nn.Module): def __init__(self, channels_in, channels_out, kernel_size, reduction): super(IDR_DDC, self).__init__() self.channels_out = channels_out self.channels_in = channels_in self.kernel_size = kernel_size self.kernel = nn.Sequential( nn.Linear(channels_in, channels_in, bias=False), nn.LeakyReLU(0.1, True), nn.Linear(channels_in, channels_in * self.kernel_size * self.kernel_size, bias=False) ) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' b, c, h, w = x[0].size() # branch 1 kernel = self.kernel(x[1]).view(-1, 1, self.kernel_size, self.kernel_size) out = F.conv2d(x[0].view(1, -1, h, w), kernel, groups=b*c, padding=(self.kernel_size-1)//2) out = out.view(b, -1, h, w) return out class IDR_DCRB(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction): super(IDR_DCRB, self).__init__() self.da_conv1 = IDR_DDC(n_feat, n_feat, kernel_size, reduction) self.conv1 = conv(n_feat, n_feat, kernel_size) self.relu = nn.LeakyReLU(0.1, True) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' out = self.relu(self.da_conv1(x)) out = self.conv1(out) out = out + x[0] return out class DAG(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction, n_blocks): super(DAG, self).__init__() self.n_blocks = n_blocks modules_body = [ IDR_DCRB(conv, n_feat, kernel_size, reduction) \ for _ in range(n_blocks) ] # modules_body.append(conv(n_feat, n_feat, kernel_size)) self.body = nn.Sequential(*modules_body) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' res = x[0] for i in range(self.n_blocks): res = self.body[i]([res, x[1]]) return res class KDSR(nn.Module): def __init__(self, n_feats=128, scale=4,n_sr_blocks = 42, rgb_range=1,reduction = 8, conv=common.default_conv): super(KDSR, self).__init__() kernel_size = 3 # RGB mean for DIV2K rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std) self.add_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std, 1) # head module modules_head = [conv(3, n_feats, kernel_size)] self.head = nn.Sequential(*modules_head) # body modules_body = [ DAG(common.default_conv, n_feats, kernel_size, reduction, n_sr_blocks) ] modules_body.append(conv(n_feats, n_feats, kernel_size)) self.body = nn.Sequential(*modules_body) # tail modules_tail = [common.Upsampler(conv, scale, n_feats, act=False), conv(n_feats, 3, kernel_size)] self.tail = nn.Sequential(*modules_tail) def forward(self, x, k_v): # sub mean x = self.sub_mean(x) # head x = self.head(x) # body res = x res = self.body[0]([res, k_v]) res = self.body[-1](res) res = res + x # tail x = self.tail(res) # add mean x = self.add_mean(x) return x class KD_IDE(nn.Module): def __init__(self,n_feats = 128, n_encoder_res = 6): super(KD_IDE, self).__init__() E1=[nn.Conv2d(3, n_feats, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True)] E2=[ common.ResBlock( common.default_conv, n_feats, kernel_size=3 ) for _ in range(n_encoder_res) ] E3=[ nn.Conv2d(n_feats, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 4, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.AdaptiveAvgPool2d(1), ] E=E1+E2+E3 self.E = nn.Sequential( *E ) self.mlp = nn.Sequential( nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True), nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True) ) self.compress = nn.Sequential( nn.Linear(n_feats*4, n_feats), nn.LeakyReLU(0.1, True) ) def forward(self, x): fea = self.E(x).squeeze(-1).squeeze(-1) S_fea = [] fea1 = self.mlp(fea) fea = self.compress(fea1) S_fea.append(fea1) return fea,S_fea @ARCH_REGISTRY.register() class BlindSR_ST(nn.Module): def __init__(self, n_feats=128, n_encoder_res=6, scale=4,n_sr_blocks=42 ): super(BlindSR_ST, self).__init__() # Generator self.G = KDSR(n_feats=n_feats, scale=scale,n_sr_blocks=n_sr_blocks) self.E_st = KD_IDE(n_feats=n_feats, n_encoder_res=n_encoder_res) self.pixel_unshuffle = nn.PixelUnshuffle(scale) def forward(self, x): if self.training: # degradation-aware represenetion learning deg_repre, S_fea = self.E_st(x) # degradation-aware SR sr = self.G(x, deg_repre) return sr, S_fea else: # degradation-aware represenetion learning deg_repre, _ = self.E_st(x) # degradation-aware SR sr = self.G(x, deg_repre) return sr ================================================ FILE: KDSR-GAN/kdsrgan/archs/TA_arch.py ================================================ from basicsr.utils.registry import ARCH_REGISTRY from torch.nn import functional as F import torch from torch import nn import kdsrgan.archs.common as common class IDR_DDC(nn.Module): def __init__(self, channels_in, channels_out, kernel_size, reduction): super(IDR_DDC, self).__init__() self.channels_out = channels_out self.channels_in = channels_in self.kernel_size = kernel_size self.kernel = nn.Sequential( nn.Linear(channels_in, channels_in, bias=False), nn.LeakyReLU(0.1, True), nn.Linear(channels_in, channels_in * self.kernel_size * self.kernel_size, bias=False) ) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' b, c, h, w = x[0].size() # branch 1 kernel = self.kernel(x[1]).view(-1, 1, self.kernel_size, self.kernel_size) out = F.conv2d(x[0].view(1, -1, h, w), kernel, groups=b*c, padding=(self.kernel_size-1)//2) out = out.view(b, -1, h, w) return out class IDR_DCRB(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction): super(IDR_DCRB, self).__init__() self.da_conv1 = IDR_DDC(n_feat, n_feat, kernel_size, reduction) self.conv1 = conv(n_feat, n_feat, kernel_size) self.relu = nn.LeakyReLU(0.1, True) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' out = self.relu(self.da_conv1(x)) out = self.conv1(out) out = out + x[0] return out class DAG(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction, n_blocks): super(DAG, self).__init__() self.n_blocks = n_blocks modules_body = [ IDR_DCRB(conv, n_feat, kernel_size, reduction) \ for _ in range(n_blocks) ] # modules_body.append(conv(n_feat, n_feat, kernel_size)) self.body = nn.Sequential(*modules_body) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' res = x[0] for i in range(self.n_blocks): res = self.body[i]([res, x[1]]) # res = self.body[-1](res) #res = res + x[0] return res class KDSR(nn.Module): def __init__(self, n_feats=128, scale=4,n_sr_blocks = 42, rgb_range=1,reduction = 8, conv=common.default_conv): super(KDSR, self).__init__() kernel_size = 3 # RGB mean for DIV2K rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std) self.add_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std, 1) # head module modules_head = [conv(3, n_feats, kernel_size)] self.head = nn.Sequential(*modules_head) # body modules_body = [ DAG(common.default_conv, n_feats, kernel_size, reduction, n_sr_blocks) ] modules_body.append(conv(n_feats, n_feats, kernel_size)) self.body = nn.Sequential(*modules_body) # tail modules_tail = [common.Upsampler(conv, scale, n_feats, act=False), conv(n_feats, 3, kernel_size)] self.tail = nn.Sequential(*modules_tail) def forward(self, x, k_v): # sub mean x = self.sub_mean(x) # head x = self.head(x) # body res = x res = self.body[0]([res, k_v]) res = self.body[-1](res) res = res + x # tail x = self.tail(res) # add mean x = self.add_mean(x) return x class KD_IDE(nn.Module): def __init__(self,n_feats = 128, n_encoder_res = 6): super(KD_IDE, self).__init__() E1=[nn.Conv2d(51, n_feats, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True)] E2=[ common.ResBlock( common.default_conv, n_feats, kernel_size=3 ) for _ in range(n_encoder_res) ] E3=[ nn.Conv2d(n_feats, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 4, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.AdaptiveAvgPool2d(1), ] E=E1+E2+E3 self.E = nn.Sequential( *E ) self.mlp = nn.Sequential( nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True), nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True) ) self.compress = nn.Sequential( nn.Linear(n_feats*4, n_feats), nn.LeakyReLU(0.1, True) ) def forward(self, x): fea = self.E(x).squeeze(-1).squeeze(-1) T_fea = [] fea1 = self.mlp(fea) fea = self.compress(fea1) T_fea.append(fea1) return fea,T_fea @ARCH_REGISTRY.register() class BlindSR_TA(nn.Module): def __init__(self, n_feats=128, n_encoder_res=6, scale=4,n_sr_blocks=42 ): super(BlindSR_TA, self).__init__() # Generator self.G = KDSR(n_feats=n_feats, scale=scale,n_sr_blocks=n_sr_blocks) self.E = KD_IDE(n_feats=n_feats, n_encoder_res=n_encoder_res) self.pixel_unshuffle = nn.PixelUnshuffle(scale) def forward(self, x, gt): if self.training: hr = self.pixel_unshuffle(gt) deg_repre = torch.cat([x, hr], dim=1) # degradation-aware represenetion learning deg_repre, T_fea = self.E(deg_repre) # degradation-aware SR sr = self.G(x, deg_repre) return sr, T_fea else: # degradation-aware represenetion learning hr = self.pixel_unshuffle(gt) deg_repre = torch.cat([x, hr], dim=1) deg_repre, _ = self.E(deg_repre) # degradation-aware SR sr = self.G(x, deg_repre) return sr ================================================ FILE: KDSR-GAN/kdsrgan/archs/__init__.py ================================================ import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import arch modules for registry # scan all the files that end with '_arch.py' under the archs folder arch_folder = osp.dirname(osp.abspath(__file__)) arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')] # import all the arch modules _arch_modules = [importlib.import_module(f'kdsrgan.archs.{file_name}') for file_name in arch_filenames] ================================================ FILE: KDSR-GAN/kdsrgan/archs/common.py ================================================ import math import torch import torch.nn as nn import torch.nn.functional as F def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class ResBlock(nn.Module): def __init__( self, conv, n_feats, kernel_size, bias=True, bn=False, act=nn.LeakyReLU(0.1, inplace=True), res_scale=1): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(conv(n_feats, n_feats, kernel_size, bias=bias)) if bn: m.append(nn.BatchNorm2d(n_feats)) if i == 0: m.append(act) self.body = nn.Sequential(*m) # self.res_scale = res_scale def forward(self, x): res = self.body(x) res += x return res class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, act=False, bias=True): m = [] if (int(scale) & (int(scale) - 1)) == 0: # Is scale = 2^n? for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, 4 * n_feat, 3, bias)) m.append(nn.PixelShuffle(2)) if act: m.append(act()) elif scale == 3: m.append(conv(n_feat, 9 * n_feat, 3, bias)) m.append(nn.PixelShuffle(3)) if act: m.append(act()) else: raise NotImplementedError super(Upsampler, self).__init__(*m) ================================================ FILE: KDSR-GAN/kdsrgan/archs/discriminator_arch.py ================================================ from basicsr.utils.registry import ARCH_REGISTRY from torch import nn as nn from torch.nn import functional as F from torch.nn.utils import spectral_norm @ARCH_REGISTRY.register() class UNetDiscriminatorSN(nn.Module): """Defines a U-Net discriminator with spectral normalization (SN) It is used in Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. Arg: num_in_ch (int): Channel number of inputs. Default: 3. num_feat (int): Channel number of base intermediate features. Default: 64. skip_connection (bool): Whether to use skip connections between U-Net. Default: True. """ def __init__(self, num_in_ch, num_feat=64, skip_connection=True): super(UNetDiscriminatorSN, self).__init__() self.skip_connection = skip_connection norm = spectral_norm # the first convolution self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1) # downsample self.conv1 = norm(nn.Conv2d(num_feat, num_feat * 2, 4, 2, 1, bias=False)) self.conv2 = norm(nn.Conv2d(num_feat * 2, num_feat * 4, 4, 2, 1, bias=False)) self.conv3 = norm(nn.Conv2d(num_feat * 4, num_feat * 8, 4, 2, 1, bias=False)) # upsample self.conv4 = norm(nn.Conv2d(num_feat * 8, num_feat * 4, 3, 1, 1, bias=False)) self.conv5 = norm(nn.Conv2d(num_feat * 4, num_feat * 2, 3, 1, 1, bias=False)) self.conv6 = norm(nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1, bias=False)) # extra convolutions self.conv7 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False)) self.conv8 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False)) self.conv9 = nn.Conv2d(num_feat, 1, 3, 1, 1) def forward(self, x): # downsample x0 = F.leaky_relu(self.conv0(x), negative_slope=0.2, inplace=True) x1 = F.leaky_relu(self.conv1(x0), negative_slope=0.2, inplace=True) x2 = F.leaky_relu(self.conv2(x1), negative_slope=0.2, inplace=True) x3 = F.leaky_relu(self.conv3(x2), negative_slope=0.2, inplace=True) # upsample x3 = F.interpolate(x3, scale_factor=2, mode='bilinear', align_corners=False) x4 = F.leaky_relu(self.conv4(x3), negative_slope=0.2, inplace=True) if self.skip_connection: x4 = x4 + x2 x4 = F.interpolate(x4, scale_factor=2, mode='bilinear', align_corners=False) x5 = F.leaky_relu(self.conv5(x4), negative_slope=0.2, inplace=True) if self.skip_connection: x5 = x5 + x1 x5 = F.interpolate(x5, scale_factor=2, mode='bilinear', align_corners=False) x6 = F.leaky_relu(self.conv6(x5), negative_slope=0.2, inplace=True) if self.skip_connection: x6 = x6 + x0 # extra convolutions out = F.leaky_relu(self.conv7(x6), negative_slope=0.2, inplace=True) out = F.leaky_relu(self.conv8(out), negative_slope=0.2, inplace=True) out = self.conv9(out) return out ================================================ FILE: KDSR-GAN/kdsrgan/archs/srvgg_arch.py ================================================ from basicsr.utils.registry import ARCH_REGISTRY from torch import nn as nn from torch.nn import functional as F @ARCH_REGISTRY.register() class SRVGGNetCompact(nn.Module): """A compact VGG-style network structure for super-resolution. It is a compact network structure, which performs upsampling in the last layer and no convolution is conducted on the HR feature space. Args: num_in_ch (int): Channel number of inputs. Default: 3. num_out_ch (int): Channel number of outputs. Default: 3. num_feat (int): Channel number of intermediate features. Default: 64. num_conv (int): Number of convolution layers in the body network. Default: 16. upscale (int): Upsampling factor. Default: 4. act_type (str): Activation type, options: 'relu', 'prelu', 'leakyrelu'. Default: prelu. """ def __init__(self, num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu'): super(SRVGGNetCompact, self).__init__() self.num_in_ch = num_in_ch self.num_out_ch = num_out_ch self.num_feat = num_feat self.num_conv = num_conv self.upscale = upscale self.act_type = act_type self.body = nn.ModuleList() # the first conv self.body.append(nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)) # the first activation if act_type == 'relu': activation = nn.ReLU(inplace=True) elif act_type == 'prelu': activation = nn.PReLU(num_parameters=num_feat) elif act_type == 'leakyrelu': activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) self.body.append(activation) # the body structure for _ in range(num_conv): self.body.append(nn.Conv2d(num_feat, num_feat, 3, 1, 1)) # activation if act_type == 'relu': activation = nn.ReLU(inplace=True) elif act_type == 'prelu': activation = nn.PReLU(num_parameters=num_feat) elif act_type == 'leakyrelu': activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) self.body.append(activation) # the last conv self.body.append(nn.Conv2d(num_feat, num_out_ch * upscale * upscale, 3, 1, 1)) # upsample self.upsampler = nn.PixelShuffle(upscale) def forward(self, x): out = x for i in range(0, len(self.body)): out = self.body[i](out) out = self.upsampler(out) # add the nearest upsampled image, so that the network learns the residual base = F.interpolate(x, scale_factor=self.upscale, mode='nearest') out += base return out ================================================ FILE: KDSR-GAN/kdsrgan/data/__init__.py ================================================ import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import dataset modules for registry # scan all the files that end with '_dataset.py' under the data folder data_folder = osp.dirname(osp.abspath(__file__)) dataset_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(data_folder) if v.endswith('_dataset.py')] # import all the dataset modules _dataset_modules = [importlib.import_module(f'kdsrgan.data.{file_name}') for file_name in dataset_filenames] ================================================ FILE: KDSR-GAN/kdsrgan/data/kdsrgan_dataset.py ================================================ import cv2 import math import numpy as np import os import os.path as osp import random import time import torch from basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels from basicsr.data.transforms import augment from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor from basicsr.utils.registry import DATASET_REGISTRY from torch.utils import data as data @DATASET_REGISTRY.register() class KDSRGANDataset(data.Dataset): """Dataset used for KDSRGAN model: KDSRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. It loads gt (Ground-Truth) images, and augments them. It also generates blur kernels and sinc kernels for generating low-quality images. Note that the low-quality images are processed in tensors on GPUS for faster processing. Args: opt (dict): Config for train datasets. It contains the following keys: dataroot_gt (str): Data root path for gt. meta_info (str): Path for meta information file. io_backend (dict): IO backend type and other kwarg. use_hflip (bool): Use horizontal flips. use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). Please see more options in the codes. """ def __init__(self, opt): super(KDSRGANDataset, self).__init__() self.opt = opt self.file_client = None self.io_backend_opt = opt['io_backend'] self.gt_folder = opt['dataroot_gt'] # file client (lmdb io backend) if self.io_backend_opt['type'] == 'lmdb': self.io_backend_opt['db_paths'] = [self.gt_folder] self.io_backend_opt['client_keys'] = ['gt'] if not self.gt_folder.endswith('.lmdb'): raise ValueError(f"'dataroot_gt' should end with '.lmdb', but received {self.gt_folder}") with open(osp.join(self.gt_folder, 'meta_info.txt')) as fin: self.paths = [line.split('.')[0] for line in fin] else: # disk backend with meta_info # Each line in the meta_info describes the relative path to an image with open(self.opt['meta_info']) as fin: paths = [line.strip().split(' ')[0] for line in fin] self.paths = [os.path.join(self.gt_folder, v) for v in paths] # blur settings for the first degradation self.blur_kernel_size = opt['blur_kernel_size'] self.kernel_list = opt['kernel_list'] self.kernel_prob = opt['kernel_prob'] # a list for each kernel probability self.blur_sigma = opt['blur_sigma'] self.betag_range = opt['betag_range'] # betag used in generalized Gaussian blur kernels self.betap_range = opt['betap_range'] # betap used in plateau blur kernels self.sinc_prob = opt['sinc_prob'] # the probability for sinc filters # blur settings for the second degradation self.blur_kernel_size2 = opt['blur_kernel_size2'] self.kernel_list2 = opt['kernel_list2'] self.kernel_prob2 = opt['kernel_prob2'] self.blur_sigma2 = opt['blur_sigma2'] self.betag_range2 = opt['betag_range2'] self.betap_range2 = opt['betap_range2'] self.sinc_prob2 = opt['sinc_prob2'] # a final sinc filter self.final_sinc_prob = opt['final_sinc_prob'] self.kernel_range = [2 * v + 1 for v in range(3, 11)] # kernel size ranges from 7 to 21 # TODO: kernel range is now hard-coded, should be in the configure file self.pulse_tensor = torch.zeros(21, 21).float() # convolving with pulse tensor brings no blurry effect self.pulse_tensor[10, 10] = 1 def __getitem__(self, index): if self.file_client is None: self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt) # -------------------------------- Load gt images -------------------------------- # # Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32. gt_path = self.paths[index] # avoid errors caused by high latency in reading files retry = 3 while retry > 0: try: img_bytes = self.file_client.get(gt_path, 'gt') except (IOError, OSError) as e: logger = get_root_logger() logger.warn(f'File client error: {e}, remaining retry times: {retry - 1}') # change another file to read index = random.randint(0, self.__len__()) gt_path = self.paths[index] time.sleep(1) # sleep 1s for occasional server congestion else: break finally: retry -= 1 img_gt = imfrombytes(img_bytes, float32=True) # -------------------- Do augmentation for training: flip, rotation -------------------- # img_gt = augment(img_gt, self.opt['use_hflip'], self.opt['use_rot']) # crop or pad to 400 # TODO: 400 is hard-coded. You may change it accordingly h, w = img_gt.shape[0:2] crop_pad_size = 400 # pad if h < crop_pad_size or w < crop_pad_size: pad_h = max(0, crop_pad_size - h) pad_w = max(0, crop_pad_size - w) img_gt = cv2.copyMakeBorder(img_gt, 0, pad_h, 0, pad_w, cv2.BORDER_REFLECT_101) # crop if img_gt.shape[0] > crop_pad_size or img_gt.shape[1] > crop_pad_size: h, w = img_gt.shape[0:2] # randomly choose top and left coordinates top = random.randint(0, h - crop_pad_size) left = random.randint(0, w - crop_pad_size) img_gt = img_gt[top:top + crop_pad_size, left:left + crop_pad_size, ...] # ------------------------ Generate kernels (used in the first degradation) ------------------------ # kernel_size = random.choice(self.kernel_range) if np.random.uniform() < self.opt['sinc_prob']: # this sinc filter setting is for kernels ranging from [7, 21] if kernel_size < 13: omega_c = np.random.uniform(np.pi / 3, np.pi) else: omega_c = np.random.uniform(np.pi / 5, np.pi) kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) else: kernel = random_mixed_kernels( self.kernel_list, self.kernel_prob, kernel_size, self.blur_sigma, self.blur_sigma, [-math.pi, math.pi], self.betag_range, self.betap_range, noise_range=None) # pad kernel pad_size = (21 - kernel_size) // 2 kernel = np.pad(kernel, ((pad_size, pad_size), (pad_size, pad_size))) # ------------------------ Generate kernels (used in the second degradation) ------------------------ # kernel_size = random.choice(self.kernel_range) if np.random.uniform() < self.opt['sinc_prob2']: if kernel_size < 13: omega_c = np.random.uniform(np.pi / 3, np.pi) else: omega_c = np.random.uniform(np.pi / 5, np.pi) kernel2 = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) else: kernel2 = random_mixed_kernels( self.kernel_list2, self.kernel_prob2, kernel_size, self.blur_sigma2, self.blur_sigma2, [-math.pi, math.pi], self.betag_range2, self.betap_range2, noise_range=None) # pad kernel pad_size = (21 - kernel_size) // 2 kernel2 = np.pad(kernel2, ((pad_size, pad_size), (pad_size, pad_size))) # ------------------------------------- the final sinc kernel ------------------------------------- # if np.random.uniform() < self.opt['final_sinc_prob']: kernel_size = random.choice(self.kernel_range) omega_c = np.random.uniform(np.pi / 3, np.pi) sinc_kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=21) sinc_kernel = torch.FloatTensor(sinc_kernel) else: sinc_kernel = self.pulse_tensor # BGR to RGB, HWC to CHW, numpy to tensor img_gt = img2tensor([img_gt], bgr2rgb=True, float32=True)[0] kernel = torch.FloatTensor(kernel) kernel2 = torch.FloatTensor(kernel2) return_d = {'gt': img_gt, 'kernel1': kernel, 'kernel2': kernel2, 'sinc_kernel': sinc_kernel, 'gt_path': gt_path} return return_d def __len__(self): return len(self.paths) ================================================ FILE: KDSR-GAN/kdsrgan/data/kdsrgan_paired_dataset.py ================================================ import os from basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, imfrombytes, img2tensor from basicsr.utils.registry import DATASET_REGISTRY from torch.utils import data as data from torchvision.transforms.functional import normalize @DATASET_REGISTRY.register() class KDSRGANPairedDataset(data.Dataset): """Paired image dataset for image restoration. Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, noisy, etc) and GT image pairs. There are three modes: 1. 'lmdb': Use lmdb files. If opt['io_backend'] == lmdb. 2. 'meta_info': Use meta information file to generate paths. If opt['io_backend'] != lmdb and opt['meta_info'] is not None. 3. 'folder': Scan folders to generate paths. The rest. Args: opt (dict): Config for train datasets. It contains the following keys: dataroot_gt (str): Data root path for gt. dataroot_lq (str): Data root path for lq. meta_info (str): Path for meta information file. io_backend (dict): IO backend type and other kwarg. filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. Default: '{}'. gt_size (int): Cropped patched size for gt patches. use_hflip (bool): Use horizontal flips. use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). scale (bool): Scale, which will be added automatically. phase (str): 'train' or 'val'. """ def __init__(self, opt): super(KDSRGANPairedDataset, self).__init__() self.opt = opt self.file_client = None self.io_backend_opt = opt['io_backend'] # mean and std for normalizing the input images self.mean = opt['mean'] if 'mean' in opt else None self.std = opt['std'] if 'std' in opt else None self.gt_folder, self.lq_folder = opt['dataroot_gt'], opt['dataroot_lq'] self.filename_tmpl = opt['filename_tmpl'] if 'filename_tmpl' in opt else '{}' # file client (lmdb io backend) if self.io_backend_opt['type'] == 'lmdb': self.io_backend_opt['db_paths'] = [self.lq_folder, self.gt_folder] self.io_backend_opt['client_keys'] = ['lq', 'gt'] self.paths = paired_paths_from_lmdb([self.lq_folder, self.gt_folder], ['lq', 'gt']) elif 'meta_info' in self.opt and self.opt['meta_info'] is not None: # disk backend with meta_info # Each line in the meta_info describes the relative path to an image with open(self.opt['meta_info']) as fin: paths = [line.strip() for line in fin] self.paths = [] for path in paths: gt_path, lq_path = path.split(', ') gt_path = os.path.join(self.gt_folder, gt_path) lq_path = os.path.join(self.lq_folder, lq_path) self.paths.append(dict([('gt_path', gt_path), ('lq_path', lq_path)])) else: # disk backend # it will scan the whole folder to get meta info # it will be time-consuming for folders with too many files. It is recommended using an extra meta txt file self.paths = paired_paths_from_folder([self.lq_folder, self.gt_folder], ['lq', 'gt'], self.filename_tmpl) def __getitem__(self, index): if self.file_client is None: self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt) scale = self.opt['scale'] # Load gt and lq images. Dimension order: HWC; channel order: BGR; # image range: [0, 1], float32. gt_path = self.paths[index]['gt_path'] img_bytes = self.file_client.get(gt_path, 'gt') img_gt = imfrombytes(img_bytes, float32=True) lq_path = self.paths[index]['lq_path'] img_bytes = self.file_client.get(lq_path, 'lq') img_lq = imfrombytes(img_bytes, float32=True) # augmentation for training if self.opt['phase'] == 'train': gt_size = self.opt['gt_size'] # random crop img_gt, img_lq = paired_random_crop(img_gt, img_lq, gt_size, scale, gt_path) # flip, rotation img_gt, img_lq = augment([img_gt, img_lq], self.opt['use_hflip'], self.opt['use_rot']) # BGR to RGB, HWC to CHW, numpy to tensor img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True) # normalize if self.mean is not None or self.std is not None: normalize(img_lq, self.mean, self.std, inplace=True) normalize(img_gt, self.mean, self.std, inplace=True) return {'lq': img_lq, 'gt': img_gt, 'lq_path': lq_path, 'gt_path': gt_path} def __len__(self): return len(self.paths) ================================================ FILE: KDSR-GAN/kdsrgan/losses/__init__.py ================================================ import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import arch modules for registry # scan all the files that end with '_arch.py' under the archs folder arch_folder = osp.dirname(osp.abspath(__file__)) arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_loss.py')] # import all the arch modules _arch_modules = [importlib.import_module(f'kdsrgan.losses.{file_name}') for file_name in arch_filenames] ================================================ FILE: KDSR-GAN/kdsrgan/losses/my_loss.py ================================================ import torch from torch import nn as nn from torch.nn import functional as F from basicsr.utils.registry import LOSS_REGISTRY @LOSS_REGISTRY.register() class KDLoss(nn.Module): """Knowledge distillation loss. Args: loss_weight (float): Loss weight for KD loss. Default: 1.0. """ def __init__(self, loss_weight=1.0, temperature = 0.15): super(KDLoss, self).__init__() self.loss_weight = loss_weight self.temperature = temperature def forward(self, T_fea, S_fea): """ Args: T_fea (List): contain shape (N, L) vector of BlindSR_TA. S_fea (List): contain shape (N, L) vector of BlindSR_ST. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ loss_distill_dis = 0 for i in range(len(T_fea)): student_distance = F.log_softmax(S_fea[i] / self.temperature, dim=1) teacher_distance = F.softmax(T_fea[i].detach()/ self.temperature, dim=1) loss_distill_dis += F.kl_div( student_distance, teacher_distance, reduction='batchmean') #loss_distill_abs += nn.L1Loss()(S_fea[i], T_fea[i].detach()) return self.loss_weight * loss_distill_dis ================================================ FILE: KDSR-GAN/kdsrgan/models/__init__.py ================================================ import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import model modules for registry # scan all the files that end with '_model.py' under the model folder model_folder = osp.dirname(osp.abspath(__file__)) model_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(model_folder) if v.endswith('_model.py')] # import all the model modules _model_modules = [importlib.import_module(f'kdsrgan.models.{file_name}') for file_name in model_filenames] ================================================ FILE: KDSR-GAN/kdsrgan/models/kdsrgan_ST_model.py ================================================ import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.srgan_model import SRGANModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_util import filter2D from basicsr.utils.registry import MODEL_REGISTRY from collections import OrderedDict from torch.nn import functional as F from basicsr.archs import build_network from basicsr.utils import get_root_logger from basicsr.losses import build_loss from torch import nn @MODEL_REGISTRY.register() class KDSRGANSTModel(SRGANModel): """ It mainly performs: 1. randomly synthesize LQ images in GPU tensors 2. optimize the networks with GAN training. """ def __init__(self, opt): super(KDSRGANSTModel, self).__init__(opt) self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts self.usm_sharpener = USMSharp().cuda() # do usm sharpening self.queue_size = opt.get('queue_size', 180) self.net_g_TA = build_network(opt['network_TA']) self.net_g_TA = self.model_to_device(self.net_g_TA) load_path = self.opt['path'].get('pretrain_network_TA', None) if load_path is not None: param_key = self.opt['path'].get('param_key_g', 'params') self.load_network(self.net_g_TA, load_path, True, param_key) self.net_g_TA.eval() if self.opt['dist']: self.model_Est = self.net_g.module.E_st self.model_Eta = self.net_g_TA.module.E else: self.model_Est = self.net_g.E_st self.model_Eta = self.net_g_TA.E self.pixel_unshuffle = nn.PixelUnshuffle(opt["scale"]) if self.is_train: self.encoder_iter = opt["train"]["encoder_iter"] self.lr_encoder = opt["train"]["lr_encoder"] self.lr_sr = opt["train"]["lr_sr"] self.gamma_encoder = opt["train"]["gamma_encoder"] self.gamma_sr = opt["train"]["gamma_sr"] self.lr_decay_encoder = opt["train"]["lr_decay_encoder"] self.lr_decay_sr = opt["train"]["lr_decay_sr"] def init_training_settings(self): train_opt = self.opt['train'] if train_opt.get('kd_opt'): self.cri_kd = build_loss(train_opt['kd_opt']).to(self.device) else: self.cri_kd = None super(KDSRGANSTModel, self).init_training_settings() @torch.no_grad() def _dequeue_and_enqueue(self): """It is the training pair pool for increasing the diversity in a batch. Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a batch could not have different resize scaling factors. Therefore, we employ this training pair pool to increase the degradation diversity in a batch. """ # initialize b, c, h, w = self.lq.size() if not hasattr(self, 'queue_lr'): assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}' self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() _, c, h, w = self.gt.size() self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() self.queue_ptr = 0 if self.queue_ptr == self.queue_size: # the pool is full # do dequeue and enqueue # shuffle idx = torch.randperm(self.queue_size) self.queue_lr = self.queue_lr[idx] self.queue_gt = self.queue_gt[idx] # get first b samples lq_dequeue = self.queue_lr[0:b, :, :, :].clone() gt_dequeue = self.queue_gt[0:b, :, :, :].clone() # update the queue self.queue_lr[0:b, :, :, :] = self.lq.clone() self.queue_gt[0:b, :, :, :] = self.gt.clone() self.lq = lq_dequeue self.gt = gt_dequeue else: # only do enqueue self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone() self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone() self.queue_ptr = self.queue_ptr + b @torch.no_grad() def feed_data(self, data): """Accept data from dataloader, and then add two-order degradations to obtain LQ images. """ if self.is_train and self.opt.get('high_order_degradation', True): # training data synthesis self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) self.kernel1 = data['kernel1'].to(self.device) self.kernel2 = data['kernel2'].to(self.device) self.sinc_kernel = data['sinc_kernel'].to(self.device) ori_h, ori_w = self.gt.size()[2:4] # ----------------------- The first degradation process ----------------------- # # blur out = filter2D(self.gt, self.kernel1) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, scale_factor=scale, mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob'] if np.random.uniform() < self.opt['gaussian_noise_prob']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range']) out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts out = self.jpeger(out, quality=jpeg_p) # ----------------------- The second degradation process ----------------------- # # blur if np.random.uniform() < self.opt['second_blur_prob']: out = filter2D(out, self.kernel2) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range2'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range2'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate( out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob2'] if np.random.uniform() < self.opt['gaussian_noise_prob2']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range2'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression + the final sinc filter # We also need to resize images to desired sizes. We group [resize back + sinc filter] together # as one operation. # We consider two orders: # 1. [resize back + sinc filter] + JPEG compression # 2. JPEG compression + [resize back + sinc filter] # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. if np.random.uniform() < 0.5: # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) else: # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # clamp and round self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255. # random crop gt_size = self.opt['gt_size'] (self.gt, self.gt_usm), self.lq = paired_random_crop([self.gt, self.gt_usm], self.lq, gt_size, self.opt['scale']) # training pair pool self._dequeue_and_enqueue() # sharpen self.gt again, as we have changed the self.gt with self._dequeue_and_enqueue self.gt_usm = self.usm_sharpener(self.gt) self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract else: # for paired training or validation self.lq = data['lq'].to(self.device) if 'gt' in data: self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): # do not use the synthetic process during validation self.is_train = False super(KDSRGANSTModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img) self.is_train = True def test(self): if hasattr(self, 'net_g_ema'): self.net_g_ema.eval() with torch.no_grad(): self.output = self.net_g_ema(self.lq) else: self.net_g.eval() with torch.no_grad(): self.output = self.net_g(self.lq) self.net_g.train() def optimize_parameters(self, current_iter): lr = self.lr_sr * (self.gamma_sr ** ((current_iter ) // self.lr_decay_sr)) for param_group in self.optimizer_g.param_groups: param_group['lr'] = lr l1_gt = self.gt_usm percep_gt = self.gt_usm gan_gt = self.gt_usm if self.opt['l1_gt_usm'] is False: l1_gt = self.gt if self.opt['percep_gt_usm'] is False: percep_gt = self.gt if self.opt['gan_gt_usm'] is False: gan_gt = self.gt hr2 = self.pixel_unshuffle(l1_gt) _, T_fea = self.model_Eta(torch.cat([self.lq,hr2],dim=1)) # optimize net_g for p in self.net_d.parameters(): p.requires_grad = False self.optimizer_g.zero_grad() self.output,S_fea = self.net_g(self.lq) l_g_total = 0 loss_dict = OrderedDict() if (current_iter % self.net_d_iters == 0 and current_iter > self.net_d_init_iters): # pixel loss if self.cri_pix: l_g_pix = self.cri_pix(self.output, self.gt) l_g_total += l_g_pix loss_dict['l_g_pix'] = l_g_pix if self.cri_kd: l_kd = self.cri_kd(T_fea, S_fea) l_g_total += l_kd loss_dict['l_kd'] = l_kd # perceptual loss if self.cri_perceptual: l_g_percep, l_g_style = self.cri_perceptual(self.output, self.gt) if l_g_percep is not None: l_g_total += l_g_percep loss_dict['l_g_percep'] = l_g_percep if l_g_style is not None: l_g_total += l_g_style loss_dict['l_g_style'] = l_g_style # gan loss fake_g_pred = self.net_d(self.output) l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False) l_g_total += l_g_gan loss_dict['l_g_gan'] = l_g_gan l_g_total.backward() self.optimizer_g.step() # optimize net_d for p in self.net_d.parameters(): p.requires_grad = True self.optimizer_d.zero_grad() # real real_d_pred = self.net_d(self.gt) l_d_real = self.cri_gan(real_d_pred, True, is_disc=True) loss_dict['l_d_real'] = l_d_real loss_dict['out_d_real'] = torch.mean(real_d_pred.detach()) l_d_real.backward() # fake fake_d_pred = self.net_d(self.output.detach().clone()) # clone for pt1.9 l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True) loss_dict['l_d_fake'] = l_d_fake loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach()) l_d_fake.backward() self.optimizer_d.step() if self.ema_decay > 0: self.model_ema(decay=self.ema_decay) self.log_dict = self.reduce_loss_dict(loss_dict) ================================================ FILE: KDSR-GAN/kdsrgan/models/kdsrgan_TA_model.py ================================================ import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.srgan_model import SRGANModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_util import filter2D from basicsr.utils.registry import MODEL_REGISTRY from collections import OrderedDict from torch.nn import functional as F @MODEL_REGISTRY.register() class KDSRGANTAModel(SRGANModel): """ It mainly performs: 1. randomly synthesize LQ images in GPU tensors 2. optimize the networks with GAN training. """ def __init__(self, opt): super(KDSRGANTAModel, self).__init__(opt) self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts self.usm_sharpener = USMSharp().cuda() # do usm sharpening self.queue_size = opt.get('queue_size', 180) @torch.no_grad() def _dequeue_and_enqueue(self): """It is the training pair pool for increasing the diversity in a batch. Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a batch could not have different resize scaling factors. Therefore, we employ this training pair pool to increase the degradation diversity in a batch. """ # initialize b, c, h, w = self.lq.size() if not hasattr(self, 'queue_lr'): assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}' self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() _, c, h, w = self.gt.size() self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() self.queue_ptr = 0 if self.queue_ptr == self.queue_size: # the pool is full # do dequeue and enqueue # shuffle idx = torch.randperm(self.queue_size) self.queue_lr = self.queue_lr[idx] self.queue_gt = self.queue_gt[idx] # get first b samples lq_dequeue = self.queue_lr[0:b, :, :, :].clone() gt_dequeue = self.queue_gt[0:b, :, :, :].clone() # update the queue self.queue_lr[0:b, :, :, :] = self.lq.clone() self.queue_gt[0:b, :, :, :] = self.gt.clone() self.lq = lq_dequeue self.gt = gt_dequeue else: # only do enqueue self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone() self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone() self.queue_ptr = self.queue_ptr + b @torch.no_grad() def feed_data(self, data): """Accept data from dataloader, and then add two-order degradations to obtain LQ images. """ if self.is_train and self.opt.get('high_order_degradation', True): # training data synthesis self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) self.kernel1 = data['kernel1'].to(self.device) self.kernel2 = data['kernel2'].to(self.device) self.sinc_kernel = data['sinc_kernel'].to(self.device) ori_h, ori_w = self.gt.size()[2:4] # ----------------------- The first degradation process ----------------------- # # blur out = filter2D(self.gt_usm, self.kernel1) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, scale_factor=scale, mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob'] if np.random.uniform() < self.opt['gaussian_noise_prob']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range']) out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts out = self.jpeger(out, quality=jpeg_p) # ----------------------- The second degradation process ----------------------- # # blur if np.random.uniform() < self.opt['second_blur_prob']: out = filter2D(out, self.kernel2) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range2'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range2'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate( out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob2'] if np.random.uniform() < self.opt['gaussian_noise_prob2']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range2'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression + the final sinc filter # We also need to resize images to desired sizes. We group [resize back + sinc filter] together # as one operation. # We consider two orders: # 1. [resize back + sinc filter] + JPEG compression # 2. JPEG compression + [resize back + sinc filter] # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. if np.random.uniform() < 0.5: # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) else: # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # clamp and round self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255. # random crop gt_size = self.opt['gt_size'] (self.gt, self.gt_usm), self.lq = paired_random_crop([self.gt, self.gt_usm], self.lq, gt_size, self.opt['scale']) # training pair pool self._dequeue_and_enqueue() # sharpen self.gt again, as we have changed the self.gt with self._dequeue_and_enqueue self.gt_usm = self.usm_sharpener(self.gt) self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract else: # for paired training or validation self.lq = data['lq'].to(self.device) if 'gt' in data: self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): # do not use the synthetic process during validation self.is_train = False super(KDSRGANTAModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img) self.is_train = True def optimize_parameters(self, current_iter): # optimize net_g for p in self.net_d.parameters(): p.requires_grad = False self.optimizer_g.zero_grad() self.output = self.net_g(self.lq) l_g_total = 0 loss_dict = OrderedDict() if (current_iter % self.net_d_iters == 0 and current_iter > self.net_d_init_iters): # pixel loss if self.cri_pix: l_g_pix = self.cri_pix(self.output, self.gt) l_g_total += l_g_pix loss_dict['l_g_pix'] = l_g_pix # perceptual loss if self.cri_perceptual: l_g_percep, l_g_style = self.cri_perceptual(self.output, self.gt) if l_g_percep is not None: l_g_total += l_g_percep loss_dict['l_g_percep'] = l_g_percep if l_g_style is not None: l_g_total += l_g_style loss_dict['l_g_style'] = l_g_style # gan loss fake_g_pred = self.net_d(self.output) l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False) l_g_total += l_g_gan loss_dict['l_g_gan'] = l_g_gan l_g_total.backward() self.optimizer_g.step() # optimize net_d for p in self.net_d.parameters(): p.requires_grad = True self.optimizer_d.zero_grad() # real real_d_pred = self.net_d(self.gt) l_d_real = self.cri_gan(real_d_pred, True, is_disc=True) loss_dict['l_d_real'] = l_d_real loss_dict['out_d_real'] = torch.mean(real_d_pred.detach()) l_d_real.backward() # fake fake_d_pred = self.net_d(self.output.detach().clone()) # clone for pt1.9 l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True) loss_dict['l_d_fake'] = l_d_fake loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach()) l_d_fake.backward() self.optimizer_d.step() if self.ema_decay > 0: self.model_ema(decay=self.ema_decay) self.log_dict = self.reduce_loss_dict(loss_dict) ================================================ FILE: KDSR-GAN/kdsrgan/models/kdsrnet_ST_model.py ================================================ import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.sr_model import SRModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_util import filter2D from basicsr.utils.registry import MODEL_REGISTRY from torch.nn import functional as F from collections import OrderedDict from basicsr.archs import build_network from basicsr.utils import get_root_logger from basicsr.losses import build_loss from torch import nn from basicsr.models import lr_scheduler as lr_scheduler @MODEL_REGISTRY.register() class KDSRNetSTModel(SRModel): """ It is trained without GAN losses. It mainly performs: 1. randomly synthesize LQ images in GPU tensors 2. optimize the networks with GAN training. """ def __init__(self, opt): super(KDSRNetSTModel, self).__init__(opt) self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts self.usm_sharpener = USMSharp().cuda() # do usm sharpening self.queue_size = opt.get('queue_size', 180) self.net_g_TA = build_network(opt['network_TA']) self.net_g_TA = self.model_to_device(self.net_g_TA) # load pretrained models load_path = self.opt['path'].get('pretrain_network_TA', None) if load_path is not None: param_key = self.opt['path'].get('param_key_g', 'params') self.load_network(self.net_g_TA, load_path, True, param_key) self.net_g_TA.eval() if self.opt['dist']: self.model_Est = self.net_g.module.E_st self.model_Eta = self.net_g_TA.module.E else: self.model_Est = self.net_g.E_st self.model_Eta = self.net_g_TA.E self.pixel_unshuffle = nn.PixelUnshuffle(opt["scale"]) self.encoder_iter = opt["train"]["encoder_iter"] self.lr_encoder = opt["train"]["lr_encoder"] self.lr_sr = opt["train"]["lr_sr"] self.gamma_encoder = opt["train"]["gamma_encoder"] self.gamma_sr = opt["train"]["gamma_sr"] self.lr_decay_encoder = opt["train"]["lr_decay_encoder"] self.lr_decay_sr = opt["train"]["lr_decay_sr"] def setup_optimizers(self): train_opt = self.opt['train'] optim_params = [] for k, v in self.net_g.named_parameters(): if v.requires_grad: optim_params.append(v) else: logger = get_root_logger() logger.warning(f'Params {k} will not be optimized in the second stage.') optim_type = train_opt['optim_g'].pop('type') self.optimizer_g = self.get_optimizer(optim_type, optim_params, **train_opt['optim_g']) self.optimizers.append(self.optimizer_g) def setup_schedulers(self): """Set up schedulers.""" train_opt = self.opt['train'] scheduler_type = train_opt['scheduler'].pop('type') if scheduler_type in ['MultiStepLR', 'MultiStepRestartLR']: self.schedulers.append(lr_scheduler.MultiStepRestartLR(self.optimizer_g, **train_opt['scheduler'])) elif scheduler_type == 'CosineAnnealingRestartLR': self.schedulers.append(lr_scheduler.CosineAnnealingRestartLR(self.optimizer_g, **train_opt['scheduler'])) else: raise NotImplementedError(f'Scheduler {scheduler_type} is not implemented yet.') def init_training_settings(self): self.net_g.train() train_opt = self.opt['train'] self.ema_decay = train_opt.get('ema_decay', 0) if self.ema_decay > 0: logger = get_root_logger() logger.info(f'Use Exponential Moving Average with decay: {self.ema_decay}') # define network net_g with Exponential Moving Average (EMA) # net_g_ema is used only for testing on one GPU and saving # There is no need to wrap with DistributedDataParallel self.net_g_ema = build_network(self.opt['network_g']).to(self.device) # load pretrained model load_path = self.opt['path'].get('pretrain_network_g', None) if load_path is not None: self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema') else: self.model_ema(0) # copy net_g weight self.net_g_ema.eval() # define losses if train_opt.get('pixel_opt'): self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device) else: self.cri_pix = None if train_opt.get('perceptual_opt'): self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device) else: self.cri_perceptual = None if train_opt.get('kd_opt'): self.cri_kd = build_loss(train_opt['kd_opt']).to(self.device) else: self.cri_kd = None if self.cri_pix is None and self.cri_perceptual is None: raise ValueError('Both pixel and perceptual losses are None.') # set up optimizers and schedulers self.setup_optimizers() self.setup_schedulers() @torch.no_grad() def _dequeue_and_enqueue(self): """It is the training pair pool for increasing the diversity in a batch. Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a batch could not have different resize scaling factors. Therefore, we employ this training pair pool to increase the degradation diversity in a batch. """ # initialize b, c, h, w = self.lq.size() if not hasattr(self, 'queue_lr'): assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}' self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() _, c, h, w = self.gt.size() self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() self.queue_ptr = 0 if self.queue_ptr == self.queue_size: # the pool is full # do dequeue and enqueue # shuffle idx = torch.randperm(self.queue_size) self.queue_lr = self.queue_lr[idx] self.queue_gt = self.queue_gt[idx] # get first b samples lq_dequeue = self.queue_lr[0:b, :, :, :].clone() gt_dequeue = self.queue_gt[0:b, :, :, :].clone() # update the queue self.queue_lr[0:b, :, :, :] = self.lq.clone() self.queue_gt[0:b, :, :, :] = self.gt.clone() self.lq = lq_dequeue self.gt = gt_dequeue else: # only do enqueue self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone() self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone() self.queue_ptr = self.queue_ptr + b @torch.no_grad() def feed_data(self, data): """Accept data from dataloader, and then add two-order degradations to obtain LQ images. """ if self.is_train and self.opt.get('high_order_degradation', True): # training data synthesis self.gt = data['gt'].to(self.device) # USM sharpen the GT images if self.opt['gt_usm'] is True: self.gt = self.usm_sharpener(self.gt) self.kernel1 = data['kernel1'].to(self.device) self.kernel2 = data['kernel2'].to(self.device) self.sinc_kernel = data['sinc_kernel'].to(self.device) ori_h, ori_w = self.gt.size()[2:4] # ----------------------- The first degradation process ----------------------- # # blur out = filter2D(self.gt, self.kernel1) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, scale_factor=scale, mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob'] if np.random.uniform() < self.opt['gaussian_noise_prob']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range']) out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts out = self.jpeger(out, quality=jpeg_p) # ----------------------- The second degradation process ----------------------- # # blur if np.random.uniform() < self.opt['second_blur_prob']: out = filter2D(out, self.kernel2) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range2'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range2'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate( out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob2'] if np.random.uniform() < self.opt['gaussian_noise_prob2']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range2'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression + the final sinc filter # We also need to resize images to desired sizes. We group [resize back + sinc filter] together # as one operation. # We consider two orders: # 1. [resize back + sinc filter] + JPEG compression # 2. JPEG compression + [resize back + sinc filter] # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. if np.random.uniform() < 0.5: # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) else: # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # clamp and round self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255. # random crop gt_size = self.opt['gt_size'] self.gt, self.lq = paired_random_crop(self.gt, self.lq, gt_size, self.opt['scale']) # training pair pool self._dequeue_and_enqueue() self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract else: # for paired training or validation self.lq = data['lq'].to(self.device) if 'gt' in data: self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): # do not use the synthetic process during validation self.is_train = False super(KDSRNetSTModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img) self.is_train = True def test(self): if hasattr(self, 'net_g_ema'): self.net_g_ema.eval() with torch.no_grad(): self.output = self.net_g_ema(self.lq) else: self.net_g.eval() with torch.no_grad(): self.output = self.net_g(self.lq) self.net_g.train() def optimize_parameters(self, current_iter): lr = self.lr_sr * (self.gamma_sr ** ((current_iter ) // self.lr_decay_sr)) for param_group in self.optimizer_g.param_groups: param_group['lr'] = lr l_total = 0 loss_dict = OrderedDict() hr2 = self.pixel_unshuffle(self.gt) _, T_fea = self.model_Eta(torch.cat([self.lq,hr2],dim=1)) self.optimizer_g.zero_grad() self.output, S_fea = self.net_g(self.lq) l_pix = self.cri_pix(self.output, self.gt) l_total += l_pix loss_dict['l_pix'] = l_pix l_kd = self.cri_kd(T_fea, S_fea) l_total += l_kd loss_dict['l_kd'] = l_kd l_total.backward() self.optimizer_g.step() self.log_dict = self.reduce_loss_dict(loss_dict) if self.ema_decay > 0: self.model_ema(decay=self.ema_decay) ================================================ FILE: KDSR-GAN/kdsrgan/models/kdsrnet_TA_model.py ================================================ import numpy as np import random import torch from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt from basicsr.data.transforms import paired_random_crop from basicsr.models.sr_model import SRModel from basicsr.utils import DiffJPEG, USMSharp from basicsr.utils.img_process_util import filter2D from basicsr.utils.registry import MODEL_REGISTRY from torch.nn import functional as F from collections import OrderedDict @MODEL_REGISTRY.register() class KDSRNetTAModel(SRModel): """ It is trained without GAN losses. It mainly performs: 1. randomly synthesize LQ images in GPU tensors 2. optimize the networks with GAN training. """ def __init__(self, opt): super(KDSRNetTAModel, self).__init__(opt) self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts self.usm_sharpener = USMSharp().cuda() # do usm sharpening self.queue_size = opt.get('queue_size', 180) @torch.no_grad() def _dequeue_and_enqueue(self): """It is the training pair pool for increasing the diversity in a batch. Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a batch could not have different resize scaling factors. Therefore, we employ this training pair pool to increase the degradation diversity in a batch. """ # initialize b, c, h, w = self.lq.size() if not hasattr(self, 'queue_lr'): assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}' self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() _, c, h, w = self.gt.size() self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() self.queue_ptr = 0 if self.queue_ptr == self.queue_size: # the pool is full # do dequeue and enqueue # shuffle idx = torch.randperm(self.queue_size) self.queue_lr = self.queue_lr[idx] self.queue_gt = self.queue_gt[idx] # get first b samples lq_dequeue = self.queue_lr[0:b, :, :, :].clone() gt_dequeue = self.queue_gt[0:b, :, :, :].clone() # update the queue self.queue_lr[0:b, :, :, :] = self.lq.clone() self.queue_gt[0:b, :, :, :] = self.gt.clone() self.lq = lq_dequeue self.gt = gt_dequeue else: # only do enqueue self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone() self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone() self.queue_ptr = self.queue_ptr + b @torch.no_grad() def feed_data(self, data): """Accept data from dataloader, and then add two-order degradations to obtain LQ images. """ if self.is_train and self.opt.get('high_order_degradation', True): # training data synthesis self.gt = data['gt'].to(self.device) # USM sharpen the GT images if self.opt['gt_usm'] is True: self.gt = self.usm_sharpener(self.gt) self.kernel1 = data['kernel1'].to(self.device) self.kernel2 = data['kernel2'].to(self.device) self.sinc_kernel = data['sinc_kernel'].to(self.device) ori_h, ori_w = self.gt.size()[2:4] # ----------------------- The first degradation process ----------------------- # # blur out = filter2D(self.gt, self.kernel1) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, scale_factor=scale, mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob'] if np.random.uniform() < self.opt['gaussian_noise_prob']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range']) out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts out = self.jpeger(out, quality=jpeg_p) # ----------------------- The second degradation process ----------------------- # # blur if np.random.uniform() < self.opt['second_blur_prob']: out = filter2D(out, self.kernel2) # random resize updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0] if updown_type == 'up': scale = np.random.uniform(1, self.opt['resize_range2'][1]) elif updown_type == 'down': scale = np.random.uniform(self.opt['resize_range2'][0], 1) else: scale = 1 mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate( out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode) # add noise gray_noise_prob = self.opt['gray_noise_prob2'] if np.random.uniform() < self.opt['gaussian_noise_prob2']: out = random_add_gaussian_noise_pt( out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob) else: out = random_add_poisson_noise_pt( out, scale_range=self.opt['poisson_scale_range2'], gray_prob=gray_noise_prob, clip=True, rounds=False) # JPEG compression + the final sinc filter # We also need to resize images to desired sizes. We group [resize back + sinc filter] together # as one operation. # We consider two orders: # 1. [resize back + sinc filter] + JPEG compression # 2. JPEG compression + [resize back + sinc filter] # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. if np.random.uniform() < 0.5: # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) else: # JPEG compression jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) out = torch.clamp(out, 0, 1) out = self.jpeger(out, quality=jpeg_p) # resize back + the final sinc filter mode = random.choice(['area', 'bilinear', 'bicubic']) out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) out = filter2D(out, self.sinc_kernel) # clamp and round self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255. # random crop gt_size = self.opt['gt_size'] self.gt, self.lq = paired_random_crop(self.gt, self.lq, gt_size, self.opt['scale']) # training pair pool self._dequeue_and_enqueue() self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract else: # for paired training or validation self.lq = data['lq'].to(self.device) if 'gt' in data: self.gt = data['gt'].to(self.device) self.gt_usm = self.usm_sharpener(self.gt) # self.gt = self.usm_sharpener(self.gt) def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): # do not use the synthetic process during validation self.is_train = False super(KDSRNetTAModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img) self.is_train = True def test(self): if hasattr(self, 'net_g_ema'): self.net_g_ema.eval() with torch.no_grad(): self.output = self.net_g_ema(self.lq, self.gt) else: self.net_g.eval() with torch.no_grad(): # self.output = self.net_g(self.lq, self.gt) self.output = self.net_g(self.lq, self.gt) self.net_g.train() def optimize_parameters(self, current_iter): self.optimizer_g.zero_grad() self.output, _ = self.net_g(self.lq, self.gt) l_total = 0 loss_dict = OrderedDict() # pixel loss if self.cri_pix: l_pix = self.cri_pix(self.output, self.gt) l_total += l_pix loss_dict['l_pix'] = l_pix # perceptual loss if self.cri_perceptual: l_percep, l_style = self.cri_perceptual(self.output, self.gt) if l_percep is not None: l_total += l_percep loss_dict['l_percep'] = l_percep if l_style is not None: l_total += l_style loss_dict['l_style'] = l_style l_total.backward() self.optimizer_g.step() self.log_dict = self.reduce_loss_dict(loss_dict) if self.ema_decay > 0: self.model_ema(decay=self.ema_decay) ================================================ FILE: KDSR-GAN/kdsrgan/test.py ================================================ # flake8: noqa import os.path as osp from basicsr.test import test_pipeline import kdsrgan.archs import kdsrgan.data import kdsrgan.models if __name__ == '__main__': root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) test_pipeline(root_path) ================================================ FILE: KDSR-GAN/kdsrgan/train.py ================================================ # flake8: noqa import os.path as osp from basicsr.train import train_pipeline import kdsrgan.archs import kdsrgan.data import kdsrgan.models import kdsrgan.losses import warnings warnings.filterwarnings("ignore") if __name__ == '__main__': root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) train_pipeline(root_path) ================================================ FILE: KDSR-GAN/kdsrgan/utils.py ================================================ import cv2 import math import numpy as np import os import queue import threading import torch from basicsr.utils.download_util import load_file_from_url from torch.nn import functional as F ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class RealESRGANer(): """A helper class for upsampling images with RealESRGAN. Args: scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4. model_path (str): The path to the pretrained model. It can be urls (will first download it automatically). model (nn.Module): The defined network. Default: None. tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop input images into tiles, and then process each of them. Finally, they will be merged into one image. 0 denotes for do not use tile. Default: 0. tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10. pre_pad (int): Pad the input images to avoid border artifacts. Default: 10. half (float): Whether to use half precision during inference. Default: False. """ def __init__(self, scale, model_path, model=None, tile=0, tile_pad=10, pre_pad=10, half=False, device=None, gpu_id=None): self.scale = scale self.tile_size = tile self.tile_pad = tile_pad self.pre_pad = pre_pad self.mod_scale = None self.half = half # initialize model if gpu_id: self.device = torch.device( f'cuda:{gpu_id}' if torch.cuda.is_available() else 'cpu') if device is None else device else: self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device # if the model_path starts with https, it will first download models to the folder: realesrgan/weights if model_path.startswith('https://'): model_path = load_file_from_url( url=model_path, model_dir=os.path.join(ROOT_DIR, 'realesrgan/weights'), progress=True, file_name=None) loadnet = torch.load(model_path, map_location=torch.device('cpu')) # prefer to use params_ema if 'params_ema' in loadnet: keyname = 'params_ema' else: keyname = 'params' model.load_state_dict(loadnet[keyname], strict=True) model.eval() self.model = model.to(self.device) if self.half: self.model = self.model.half() def pre_process(self, img): """Pre-process, such as pre-pad and mod pad, so that the images can be divisible """ img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float() self.img = img.unsqueeze(0).to(self.device) if self.half: self.img = self.img.half() # pre_pad if self.pre_pad != 0: self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), 'reflect') # mod pad for divisible borders if self.scale == 2: self.mod_scale = 2 elif self.scale == 1: self.mod_scale = 4 if self.mod_scale is not None: self.mod_pad_h, self.mod_pad_w = 0, 0 _, _, h, w = self.img.size() if (h % self.mod_scale != 0): self.mod_pad_h = (self.mod_scale - h % self.mod_scale) if (w % self.mod_scale != 0): self.mod_pad_w = (self.mod_scale - w % self.mod_scale) self.img = F.pad(self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), 'reflect') def process(self): # model inference self.output = self.model(self.img) def tile_process(self): """It will first crop input images to tiles, and then process each tile. Finally, all the processed tiles are merged into one images. Modified from: https://github.com/ata4/esrgan-launcher """ batch, channel, height, width = self.img.shape output_height = height * self.scale output_width = width * self.scale output_shape = (batch, channel, output_height, output_width) # start with black image self.output = self.img.new_zeros(output_shape) tiles_x = math.ceil(width / self.tile_size) tiles_y = math.ceil(height / self.tile_size) # loop over all tiles for y in range(tiles_y): for x in range(tiles_x): # extract tile from input image ofs_x = x * self.tile_size ofs_y = y * self.tile_size # input tile area on total image input_start_x = ofs_x input_end_x = min(ofs_x + self.tile_size, width) input_start_y = ofs_y input_end_y = min(ofs_y + self.tile_size, height) # input tile area on total image with padding input_start_x_pad = max(input_start_x - self.tile_pad, 0) input_end_x_pad = min(input_end_x + self.tile_pad, width) input_start_y_pad = max(input_start_y - self.tile_pad, 0) input_end_y_pad = min(input_end_y + self.tile_pad, height) # input tile dimensions input_tile_width = input_end_x - input_start_x input_tile_height = input_end_y - input_start_y tile_idx = y * tiles_x + x + 1 input_tile = self.img[:, :, input_start_y_pad:input_end_y_pad, input_start_x_pad:input_end_x_pad] # upscale tile try: with torch.no_grad(): output_tile = self.model(input_tile) except RuntimeError as error: print('Error', error) print(f'\tTile {tile_idx}/{tiles_x * tiles_y}') # output tile area on total image output_start_x = input_start_x * self.scale output_end_x = input_end_x * self.scale output_start_y = input_start_y * self.scale output_end_y = input_end_y * self.scale # output tile area without padding output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale output_end_x_tile = output_start_x_tile + input_tile_width * self.scale output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale output_end_y_tile = output_start_y_tile + input_tile_height * self.scale # put tile into output image self.output[:, :, output_start_y:output_end_y, output_start_x:output_end_x] = output_tile[:, :, output_start_y_tile:output_end_y_tile, output_start_x_tile:output_end_x_tile] def post_process(self): # remove extra pad if self.mod_scale is not None: _, _, h, w = self.output.size() self.output = self.output[:, :, 0:h - self.mod_pad_h * self.scale, 0:w - self.mod_pad_w * self.scale] # remove prepad if self.pre_pad != 0: _, _, h, w = self.output.size() self.output = self.output[:, :, 0:h - self.pre_pad * self.scale, 0:w - self.pre_pad * self.scale] return self.output @torch.no_grad() def enhance(self, img, outscale=None, alpha_upsampler='realesrgan'): h_input, w_input = img.shape[0:2] # img: numpy img = img.astype(np.float32) if np.max(img) > 256: # 16-bit image max_range = 65535 print('\tInput is a 16-bit image') else: max_range = 255 img = img / max_range if len(img.shape) == 2: # gray image img_mode = 'L' img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) elif img.shape[2] == 4: # RGBA image with alpha channel img_mode = 'RGBA' alpha = img[:, :, 3] img = img[:, :, 0:3] img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) if alpha_upsampler == 'realesrgan': alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2RGB) else: img_mode = 'RGB' img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # ------------------- process image (without the alpha channel) ------------------- # self.pre_process(img) if self.tile_size > 0: self.tile_process() else: self.process() output_img = self.post_process() output_img = output_img.data.squeeze().float().cpu().clamp_(0, 1).numpy() output_img = np.transpose(output_img[[2, 1, 0], :, :], (1, 2, 0)) if img_mode == 'L': output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY) # ------------------- process the alpha channel if necessary ------------------- # if img_mode == 'RGBA': if alpha_upsampler == 'realesrgan': self.pre_process(alpha) if self.tile_size > 0: self.tile_process() else: self.process() output_alpha = self.post_process() output_alpha = output_alpha.data.squeeze().float().cpu().clamp_(0, 1).numpy() output_alpha = np.transpose(output_alpha[[2, 1, 0], :, :], (1, 2, 0)) output_alpha = cv2.cvtColor(output_alpha, cv2.COLOR_BGR2GRAY) else: # use the cv2 resize for alpha channel h, w = alpha.shape[0:2] output_alpha = cv2.resize(alpha, (w * self.scale, h * self.scale), interpolation=cv2.INTER_LINEAR) # merge the alpha channel output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2BGRA) output_img[:, :, 3] = output_alpha # ------------------------------ return ------------------------------ # if max_range == 65535: # 16-bit image output = (output_img * 65535.0).round().astype(np.uint16) else: output = (output_img * 255.0).round().astype(np.uint8) if outscale is not None and outscale != float(self.scale): output = cv2.resize( output, ( int(w_input * outscale), int(h_input * outscale), ), interpolation=cv2.INTER_LANCZOS4) return output, img_mode class PrefetchReader(threading.Thread): """Prefetch images. Args: img_list (list[str]): A image list of image paths to be read. num_prefetch_queue (int): Number of prefetch queue. """ def __init__(self, img_list, num_prefetch_queue): super().__init__() self.que = queue.Queue(num_prefetch_queue) self.img_list = img_list def run(self): for img_path in self.img_list: img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) self.que.put(img) self.que.put(None) def __next__(self): next_item = self.que.get() if next_item is None: raise StopIteration return next_item def __iter__(self): return self class IOConsumer(threading.Thread): def __init__(self, opt, que, qid): super().__init__() self._queue = que self.qid = qid self.opt = opt def run(self): while True: msg = self._queue.get() if isinstance(msg, str) and msg == 'quit': break output = msg['output'] save_path = msg['save_path'] cv2.imwrite(save_path, output) print(f'IO worker {self.qid} is done.') ================================================ FILE: KDSR-GAN/kdsrgan/weights/README.md ================================================ # Weights Put the downloaded weights to this folder. ================================================ FILE: KDSR-GAN/options/test_kdsrgan_x4ST.yml ================================================ # general settings name: test_KDSRGANx4STplus_400k_B12G4 model_type: KDSRGANSTModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRGANModel ----------------- # # dataset and data loader settings datasets: # Uncomment these for validation val_1: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk # network structures network_g: type: BlindSR_ST n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # network structures network_TA: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 network_d: type: UNetDiscriminatorSN num_in_ch: 3 num_feat: 64 skip_connection: True # path path: # use the pre-trained Real-ESRNet model pretrain_network_TA: experiments/KDSRT-rec.pth pretrain_network_g: experiments/KDSRS-GAN.pth # pretrain_network_g: experiments/KDSRS-GANV2.pth param_key_g: params_ema strict_load_g: False ignore_resume_networks: network_TA val: save_img: True suffix: ~ # add suffix to saved images, if None, use exp name metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true ================================================ FILE: KDSR-GAN/options/test_kdsrnet_x4TA.yml ================================================ # general settings name: train_KDSRNetTAx4plus_1000k_B12G4 model_type: KDSRNetTAModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRNetModel ----------------- # gt_usm: True # USM the ground-truth # dataset and data loader settings datasets: # Uncomment these for validation test_1: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk # network structures network_g: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # path path: pretrain_network_g: ./experiments/KDSRT-rec.pth param_key_g: params_ema strict_load_g: true # Uncomment these for validation # validation settings val: save_img: True suffix: ~ # add suffix to saved images, if None, use exp name metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true ssim: type: calculate_ssim crop_border: 4 test_y_channel: true ================================================ FILE: KDSR-GAN/options/train_kdsrgan_x4ST.yml ================================================ # general settings name: train_KDSRGANx4STplus_400k_B12G4 model_type: KDSRGANSTModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRGANModel ----------------- # l1_gt_usm: False percep_gt_usm: False gan_gt_usm: False # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 0.5 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 0.4 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 0.8 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 0.5 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 0.4 jpeg_range2: [30, 95] gt_size: 256 queue_size: 180 # dataset and data loader settings datasets: train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: /root/dataset meta_info: datasets/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt io_backend: type: disk blur_kernel_size: 21 kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob: 0.1 blur_sigma: [0.2, 3] betag_range: [0.5, 4] betap_range: [1, 2] blur_kernel_size2: 21 kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob2: 0.1 blur_sigma2: [0.2, 1.5] betag_range2: [0.5, 4] betap_range2: [1, 2] final_sinc_prob: 0.8 gt_size: 256 use_hflip: True use_rot: False # data loader use_shuffle: true num_worker_per_gpu: 6 batch_size_per_gpu: 9 dataset_enlarge_ratio: 1 prefetch_mode: ~ # Uncomment these for validation val_1: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk val_2: name: AIM2019-Track2 type: PairedImageDataset dataroot_gt: /root/dataset/AIM2019-Track2/valid-gt-clean dataroot_lq: /root/dataset/AIM2019-Track2/valid-input-noisy io_backend: type: disk val_3: name: RealSR type: PairedImageDataset dataroot_lq: /root/dataset/RealSR/Canon/Test/4/LR dataroot_gt: /root/dataset/RealSR/Canon/Test/4/HR io_backend: type: disk # network structures network_g: type: BlindSR_ST n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # network structures network_TA: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 network_d: type: UNetDiscriminatorSN num_in_ch: 3 num_feat: 64 skip_connection: True # path path: # use the pre-trained Real-ESRNet model pretrain_network_TA: experiments/KDSRT-rec.pth pretrain_network_g: experiments/KDSRS-rec.pth param_key_g: params_ema strict_load_g: True resume_state: ~ ignore_resume_networks: network_TA # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] optim_d: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [400000] gamma: 0.5 encoder_iter: 100000 total_iter: 400000 lr_encoder: !!float 2e-4 lr_sr: !!float 1e-4 gamma_encoder: 0.1 gamma_sr: 0.5 lr_decay_encoder: 60000 lr_decay_sr: 400000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean # perceptual loss (content and style losses) perceptual_opt: type: PerceptualLoss layer_weights: # before relu 'conv1_2': 0.1 'conv2_2': 0.1 'conv3_4': 1 'conv4_4': 1 'conv5_4': 1 vgg_type: vgg19 use_input_norm: true perceptual_weight: !!float 1.0 style_weight: 0 range_norm: false criterion: l1 # gan loss gan_opt: type: GANLoss gan_type: vanilla real_label_val: 1.0 fake_label_val: 0.0 loss_weight: !!float 1.0 kd_opt: type: KDLoss loss_weight: 1 temperature: 0.15 net_d_iters: 1 net_d_init_iters: 0 # Uncomment these for validation # validation settings val: val_freq: !!float 1e4 save_img: False metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true # logging settings logger: print_freq: 100 save_checkpoint_freq: !!float 1e4 use_tb_logger: true wandb: project: ~ resume_id: ~ # dist training settings dist_params: backend: nccl port: 29500 ================================================ FILE: KDSR-GAN/options/train_kdsrgan_x4STV2.yml ================================================ # general settings name: train_KDSRGANx4STplus_400k_V2 model_type: KDSRGANSTModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRGANModel ----------------- # l1_gt_usm: True percep_gt_usm: True gan_gt_usm: False # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 0.5 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 0.4 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 0.8 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 0.5 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 0.4 jpeg_range2: [30, 95] gt_size: 256 queue_size: 180 # dataset and data loader settings datasets: train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: /root/dataset meta_info: datasets/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt io_backend: type: disk blur_kernel_size: 21 kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob: 0.1 blur_sigma: [0.2, 3] betag_range: [0.5, 4] betap_range: [1, 2] blur_kernel_size2: 21 kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob2: 0.1 blur_sigma2: [0.2, 1.5] betag_range2: [0.5, 4] betap_range2: [1, 2] final_sinc_prob: 0.8 gt_size: 256 use_hflip: True use_rot: False # data loader use_shuffle: true num_worker_per_gpu: 6 batch_size_per_gpu: 9 dataset_enlarge_ratio: 1 prefetch_mode: ~ # Uncomment these for validation val_1: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk val_2: name: AIM2019-Track2 type: PairedImageDataset dataroot_gt: /root/dataset/AIM2019-Track2/valid-gt-clean dataroot_lq: /root/dataset/AIM2019-Track2/valid-input-noisy io_backend: type: disk val_3: name: RealSR type: PairedImageDataset dataroot_lq: /root/dataset/RealSR/Canon/Test/4/LR dataroot_gt: /root/dataset/RealSR/Canon/Test/4/HR io_backend: type: disk # network structures network_g: type: BlindSR_ST n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # network structures network_TA: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 network_d: type: UNetDiscriminatorSN num_in_ch: 3 num_feat: 64 skip_connection: True # path path: # use the pre-trained Real-ESRNet model pretrain_network_TA: experiments/KDSRT-rec.pth pretrain_network_g: experiments/KDSRS-rec.pth param_key_g: params_ema strict_load_g: True resume_state: ~ ignore_resume_networks: network_TA # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] optim_d: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [400000] gamma: 0.5 encoder_iter: 100000 total_iter: 400000 lr_encoder: !!float 2e-4 lr_sr: !!float 1e-4 gamma_encoder: 0.1 gamma_sr: 0.5 lr_decay_encoder: 60000 lr_decay_sr: 400000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean # perceptual loss (content and style losses) perceptual_opt: type: PerceptualLoss layer_weights: # before relu 'conv1_2': 0.1 'conv2_2': 0.1 'conv3_4': 1 'conv4_4': 1 'conv5_4': 1 vgg_type: vgg19 use_input_norm: true perceptual_weight: !!float 1.0 style_weight: 0 range_norm: false criterion: l1 # gan loss gan_opt: type: GANLoss gan_type: vanilla real_label_val: 1.0 fake_label_val: 0.0 loss_weight: !!float 1.0 kd_opt: type: KDLoss loss_weight: 1 temperature: 0.15 net_d_iters: 1 net_d_init_iters: 0 # Uncomment these for validation # validation settings val: val_freq: !!float 1e4 save_img: False metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true # logging settings logger: print_freq: 100 save_checkpoint_freq: !!float 1e4 use_tb_logger: true wandb: project: ~ resume_id: ~ # dist training settings dist_params: backend: nccl port: 29500 ================================================ FILE: KDSR-GAN/options/train_kdsrnet_x4ST.yml ================================================ # general settings name: train_KDSRNetSTx4_1000k model_type: KDSRNetSTModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRNetModel ----------------- # gt_usm: False # USM the ground-truth # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 0.5 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 0.4 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 0.8 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 0.5 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 0.4 jpeg_range2: [30, 95] gt_size: 256 queue_size: 180 # dataset and data loader settings datasets: train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: /root/dataset meta_info: datasets/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt io_backend: type: disk blur_kernel_size: 21 kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob: 0.1 blur_sigma: [0.2, 3] betag_range: [0.5, 4] betap_range: [1, 2] blur_kernel_size2: 21 kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob2: 0.1 blur_sigma2: [0.2, 1.5] betag_range2: [0.5, 4] betap_range2: [1, 2] final_sinc_prob: 0.8 gt_size: 256 use_hflip: True use_rot: False # data loader use_shuffle: true num_worker_per_gpu: 6 batch_size_per_gpu: 9 dataset_enlarge_ratio: 1 prefetch_mode: ~ # Uncomment these for validation val: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk # network structures network_g: type: BlindSR_ST n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # network structures network_TA: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # path path: pretrain_network_g: experiments/KDSRT-rec.pth pretrain_network_TA: experiments/KDSRT-rec.pth param_key_g: params_ema strict_load_g: False resume_state: ~ ignore_resume_networks: network_TA # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 2e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [1000000] gamma: 0.5 encoder_iter: 100000 total_iter: 1000000 lr_encoder: !!float 2e-4 lr_sr: !!float 2e-4 gamma_encoder: 0.1 gamma_sr: 0.5 lr_decay_encoder: 60000 lr_decay_sr: 600000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean kd_opt: type: KDLoss loss_weight: 1 temperature: 0.15 # Uncomment these for validation # validation settings val: val_freq: !!float 1e4 save_img: False metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true # logging settings logger: print_freq: 100 save_checkpoint_freq: !!float 1e4 use_tb_logger: true wandb: project: ~ resume_id: ~ # dist training settings dist_params: backend: nccl port: 29500 ================================================ FILE: KDSR-GAN/options/train_kdsrnet_x4TA.yml ================================================ # general settings name: train_KDSRNetTAx4plus_1000k_B12G4 model_type: KDSRNetTAModel scale: 4 num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs manual_seed: 0 # ----------------- options for synthesizing training data in RealESRNetModel ----------------- # gt_usm: False # USM the ground-truth # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 0.5 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 0.4 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 0.8 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 0.5 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 0.4 jpeg_range2: [30, 95] gt_size: 256 queue_size: 180 # dataset and data loader settings datasets: train: name: DF2K+OST type: RealESRGANDataset dataroot_gt: /root/dataset meta_info: datasets/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt io_backend: type: disk blur_kernel_size: 21 kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob: 0.1 blur_sigma: [0.2, 3] betag_range: [0.5, 4] betap_range: [1, 2] blur_kernel_size2: 21 kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob2: 0.1 blur_sigma2: [0.2, 1.5] betag_range2: [0.5, 4] betap_range2: [1, 2] final_sinc_prob: 0.8 gt_size: 256 use_hflip: True use_rot: False # data loader use_shuffle: true num_worker_per_gpu: 6 batch_size_per_gpu: 9 dataset_enlarge_ratio: 1 prefetch_mode: ~ # Uncomment these for validation val: name: NTIRE2020-Track1 type: PairedImageDataset dataroot_gt: /root/dataset/NTIRE2020-Track1/track1-valid-gt dataroot_lq: /root/dataset/NTIRE2020-Track1/track1-valid-input io_backend: type: disk # network structures network_g: type: BlindSR_TA n_feats: 128 n_encoder_res: 6 scale: 4 n_sr_blocks: 42 # path path: pretrain_network_g: ~ param_key_g: params_ema strict_load_g: true resume_state: ~ # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [4000000] gamma: 0.5 total_iter: 1000000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean # Uncomment these for validation # validation settings val: val_freq: !!float 1e4 save_img: False metrics: psnr: # metric name type: calculate_psnr crop_border: 4 test_y_channel: true # logging settings logger: print_freq: 100 save_checkpoint_freq: !!float 1e4 use_tb_logger: true wandb: project: ~ resume_id: ~ # dist training settings dist_params: backend: nccl port: 29500 ================================================ FILE: KDSR-GAN/pip.sh ================================================ pip install basicsr pip install -r requirements.txt pip install pandas sudo python3 setup.py develop ================================================ FILE: KDSR-GAN/requirements.txt ================================================ basicsr>=1.3.3.11 facexlib>=0.2.0.3 gfpgan>=0.2.1 numpy opencv-python Pillow torch>=1.7 torchvision tqdm ================================================ FILE: KDSR-GAN/scripts/extract_subimages.py ================================================ import argparse import cv2 import numpy as np import os import sys from basicsr.utils import scandir from multiprocessing import Pool from os import path as osp from tqdm import tqdm def main(args): """A multi-thread tool to crop large images to sub-images for faster IO. opt (dict): Configuration dict. It contains: n_thread (int): Thread number. compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size and longer compression time. Use 0 for faster CPU decompression. Default: 3, same in cv2. input_folder (str): Path to the input folder. save_folder (str): Path to save folder. crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. Usage: For each folder, run this script. Typically, there are GT folder and LQ folder to be processed for DIV2K dataset. After process, each sub_folder should have the same number of subimages. Remember to modify opt configurations according to your settings. """ opt = {} opt['n_thread'] = args.n_thread opt['compression_level'] = args.compression_level opt['input_folder'] = args.input opt['save_folder'] = args.output opt['crop_size'] = args.crop_size opt['step'] = args.step opt['thresh_size'] = args.thresh_size extract_subimages(opt) def extract_subimages(opt): """Crop images to subimages. Args: opt (dict): Configuration dict. It contains: input_folder (str): Path to the input folder. save_folder (str): Path to save folder. n_thread (int): Thread number. """ input_folder = opt['input_folder'] save_folder = opt['save_folder'] if not osp.exists(save_folder): os.makedirs(save_folder) print(f'mkdir {save_folder} ...') else: print(f'Folder {save_folder} already exists. Exit.') sys.exit(1) # scan all images img_list = list(scandir(input_folder, full_path=True)) pbar = tqdm(total=len(img_list), unit='image', desc='Extract') pool = Pool(opt['n_thread']) for path in img_list: pool.apply_async(worker, args=(path, opt), callback=lambda arg: pbar.update(1)) pool.close() pool.join() pbar.close() print('All processes done.') def worker(path, opt): """Worker for each process. Args: path (str): Image path. opt (dict): Configuration dict. It contains: crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. save_folder (str): Path to save folder. compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION. Returns: process_info (str): Process information displayed in progress bar. """ crop_size = opt['crop_size'] step = opt['step'] thresh_size = opt['thresh_size'] img_name, extension = osp.splitext(osp.basename(path)) # remove the x2, x3, x4 and x8 in the filename for DIV2K img_name = img_name.replace('x2', '').replace('x3', '').replace('x4', '').replace('x8', '') img = cv2.imread(path, cv2.IMREAD_UNCHANGED) h, w = img.shape[0:2] h_space = np.arange(0, h - crop_size + 1, step) if h - (h_space[-1] + crop_size) > thresh_size: h_space = np.append(h_space, h - crop_size) w_space = np.arange(0, w - crop_size + 1, step) if w - (w_space[-1] + crop_size) > thresh_size: w_space = np.append(w_space, w - crop_size) index = 0 for x in h_space: for y in w_space: index += 1 cropped_img = img[x:x + crop_size, y:y + crop_size, ...] cropped_img = np.ascontiguousarray(cropped_img) cv2.imwrite( osp.join(opt['save_folder'], f'{img_name}_s{index:03d}{extension}'), cropped_img, [cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']]) process_info = f'Processing {img_name} ...' return process_info if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', type=str, default='/mnt/bn/xiabinpaint/dataset/DF2K/DF2K_multiscale', help='Input folder') parser.add_argument('--output', type=str, default='/mnt/bn/xiabinpaint/dataset/DF2K/DF2K_multiscale_sub', help='Output folder') parser.add_argument('--crop_size', type=int, default=400, help='Crop size') parser.add_argument('--step', type=int, default=200, help='Step for overlapped sliding window') parser.add_argument( '--thresh_size', type=int, default=0, help='Threshold size. Patches whose size is lower than thresh_size will be dropped.') parser.add_argument('--n_thread', type=int, default=20, help='Thread number.') parser.add_argument('--compression_level', type=int, default=3, help='Compression level') args = parser.parse_args() main(args) ================================================ FILE: KDSR-GAN/scripts/extract_subimages_DF2K.py ================================================ import argparse import cv2 import numpy as np import os import sys from basicsr.utils import scandir from multiprocessing import Pool from os import path as osp from tqdm import tqdm def main(args): """A multi-thread tool to crop large images to sub-images for faster IO. opt (dict): Configuration dict. It contains: n_thread (int): Thread number. compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size and longer compression time. Use 0 for faster CPU decompression. Default: 3, same in cv2. input_folder (str): Path to the input folder. save_folder (str): Path to save folder. crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. Usage: For each folder, run this script. Typically, there are GT folder and LQ folder to be processed for DIV2K dataset. After process, each sub_folder should have the same number of subimages. Remember to modify opt configurations according to your settings. """ opt = {} opt['n_thread'] = args.n_thread opt['compression_level'] = args.compression_level opt['input_folder'] = args.input opt['save_folder'] = args.output opt['crop_size'] = args.crop_size opt['step'] = args.step opt['thresh_size'] = args.thresh_size extract_subimages(opt) def extract_subimages(opt): """Crop images to subimages. Args: opt (dict): Configuration dict. It contains: input_folder (str): Path to the input folder. save_folder (str): Path to save folder. n_thread (int): Thread number. """ input_folder = opt['input_folder'] save_folder = opt['save_folder'] if not osp.exists(save_folder): os.makedirs(save_folder) print(f'mkdir {save_folder} ...') else: print(f'Folder {save_folder} already exists. Exit.') sys.exit(1) # scan all images img_list = list(scandir(input_folder, full_path=True)) pbar = tqdm(total=len(img_list), unit='image', desc='Extract') pool = Pool(opt['n_thread']) for path in img_list: pool.apply_async(worker, args=(path, opt), callback=lambda arg: pbar.update(1)) pool.close() pool.join() pbar.close() print('All processes done.') def worker(path, opt): """Worker for each process. Args: path (str): Image path. opt (dict): Configuration dict. It contains: crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. save_folder (str): Path to save folder. compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION. Returns: process_info (str): Process information displayed in progress bar. """ crop_size = opt['crop_size'] step = opt['step'] thresh_size = opt['thresh_size'] img_name, extension = osp.splitext(osp.basename(path)) # remove the x2, x3, x4 and x8 in the filename for DIV2K img_name = img_name.replace('x2', '').replace('x3', '').replace('x4', '').replace('x8', '') img = cv2.imread(path, cv2.IMREAD_UNCHANGED) h, w = img.shape[0:2] h_space = np.arange(0, h - crop_size + 1, step) if h - (h_space[-1] + crop_size) > thresh_size: h_space = np.append(h_space, h - crop_size) w_space = np.arange(0, w - crop_size + 1, step) if w - (w_space[-1] + crop_size) > thresh_size: w_space = np.append(w_space, w - crop_size) index = 0 for x in h_space: for y in w_space: index += 1 cropped_img = img[x:x + crop_size, y:y + crop_size, ...] cropped_img = np.ascontiguousarray(cropped_img) cv2.imwrite( osp.join(opt['save_folder'], f'{img_name}_s{index:03d}{extension}'), cropped_img, [cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']]) process_info = f'Processing {img_name} ...' return process_info if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', type=str, default='/mnt/bn/xiabinpaint/dataset/DF2K/HR', help='Input folder') parser.add_argument('--output', type=str, default='/mnt/bn/xiabinpaint/dataset/DF2K/DF2K_sub', help='Output folder') parser.add_argument('--crop_size', type=int, default=480, help='Crop size') parser.add_argument('--step', type=int, default=240, help='Step for overlapped sliding window') parser.add_argument( '--thresh_size', type=int, default=0, help='Threshold size. Patches whose size is lower than thresh_size will be dropped.') parser.add_argument('--n_thread', type=int, default=20, help='Thread number.') parser.add_argument('--compression_level', type=int, default=3, help='Compression level') args = parser.parse_args() main(args) ================================================ FILE: KDSR-GAN/scripts/generate_meta_info.py ================================================ import argparse import cv2 import glob import os def main(args): txt_file = open(args.meta_info, 'w') for folder, root in zip(args.input, args.root): img_paths = sorted(glob.glob(os.path.join(folder, '*'))) for img_path in img_paths: status = True if args.check: # read the image once for check, as some images may have errors try: img = cv2.imread(img_path) except (IOError, OSError) as error: print(f'Read {img_path} error: {error}') status = False if img is None: status = False print(f'Img is None: {img_path}') if status: # get the relative path img_name = os.path.relpath(img_path, root) print(img_name) txt_file.write(f'{img_name}\n') if __name__ == '__main__': """Generate meta info (txt file) for only Ground-Truth images. It can also generate meta info from several folders into one txt file. """ parser = argparse.ArgumentParser() parser.add_argument( '--input', nargs='+', default=['datasets/DF2K/DF2K_HR', 'datasets/DF2K/DF2K_multiscale'], help='Input folder, can be a list') parser.add_argument( '--root', nargs='+', default=['datasets/DF2K', 'datasets/DF2K'], help='Folder root, should have the length as input folders') parser.add_argument( '--meta_info', type=str, default='datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt', help='txt path for meta info') parser.add_argument('--check', action='store_true', help='Read image to check whether it is ok') args = parser.parse_args() assert len(args.input) == len(args.root), ('Input folder and folder root should have the same length, but got ' f'{len(args.input)} and {len(args.root)}.') os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) main(args) ================================================ FILE: KDSR-GAN/scripts/generate_meta_info_DF2K.py ================================================ import argparse import cv2 import glob import os def main(args): txt_file = open(args.meta_info, 'w') for folder, root in zip(args.input, args.root): img_paths = sorted(glob.glob(os.path.join(folder, '*'))) for img_path in img_paths: status = True if args.check: # read the image once for check, as some images may have errors try: img = cv2.imread(img_path) except (IOError, OSError) as error: print(f'Read {img_path} error: {error}') status = False if img is None: status = False print(f'Img is None: {img_path}') if status: # get the relative path img_name = os.path.relpath(img_path, root) print(img_name) txt_file.write(f'{img_name}\n') if __name__ == '__main__': """Generate meta info (txt file) for only Ground-Truth images. It can also generate meta info from several folders into one txt file. """ parser = argparse.ArgumentParser() parser.add_argument( '--input', nargs='+', default=['/mnt/bn/xiabinpaint/dataset/DF2K/DF2K_sub', '/mnt/bn/xiabinpaint/dataset/DF2K/DF2K_multiscale_sub'], help='Input folder, can be a list') parser.add_argument( '--root', nargs='+', default=['/mnt/bn/xiabinpaint/dataset', '/mnt/bn/xiabinpaint/dataset'], help='Folder root, should have the length as input folders') parser.add_argument( '--meta_info', type=str, default='/mnt/bn/xiabinpaint/ICCV-SR/KDSR-GAN/datasets/meta_info/meta_info_DF2Kmultiscale_sub.txt', help='txt path for meta info') parser.add_argument('--check', action='store_true', help='Read image to check whether it is ok') args = parser.parse_args() assert len(args.input) == len(args.root), ('Input folder and folder root should have the same length, but got ' f'{len(args.input)} and {len(args.root)}.') os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) main(args) ================================================ FILE: KDSR-GAN/scripts/generate_meta_info_OST.py ================================================ import argparse import cv2 import glob import os def main(args): txt_file = open(args.meta_info, 'w') for folder, root in zip(args.input, args.root): img_paths = sorted(glob.glob(os.path.join(folder, '*'))) for img_path in img_paths: status = True if args.check: # read the image once for check, as some images may have errors try: img = cv2.imread(img_path) except (IOError, OSError) as error: print(f'Read {img_path} error: {error}') status = False if img is None: status = False print(f'Img is None: {img_path}') if status: # get the relative path img_name = os.path.relpath(img_path, root) print(img_name) txt_file.write(f'{img_name}\n') if __name__ == '__main__': """Generate meta info (txt file) for only Ground-Truth images. It can also generate meta info from several folders into one txt file. """ parser = argparse.ArgumentParser() parser.add_argument( '--input', nargs='+', default=['/mnt/bn/xiabinpaint/dataset/OST/train/HR'], help='Input folder, can be a list') parser.add_argument( '--root', nargs='+', default=['/mnt/bn/xiabinpaint/dataset'], help='Folder root, should have the length as input folders') parser.add_argument( '--meta_info', type=str, default='/mnt/bn/xiabinpaint/ICCV-SR/KDSR-GAN/datasets/meta_info/meta_info_OST.txt', help='txt path for meta info') parser.add_argument('--check', action='store_true', help='Read image to check whether it is ok') args = parser.parse_args() assert len(args.input) == len(args.root), ('Input folder and folder root should have the same length, but got ' f'{len(args.input)} and {len(args.root)}.') os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) main(args) ================================================ FILE: KDSR-GAN/scripts/generate_meta_info_pairdata.py ================================================ import argparse import glob import os def main(args): txt_file = open(args.meta_info, 'w') # sca images img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], '*'))) img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], '*'))) assert len(img_paths_gt) == len(img_paths_lq), ('GT folder and LQ folder should have the same length, but got ' f'{len(img_paths_gt)} and {len(img_paths_lq)}.') for img_path_gt, img_path_lq in zip(img_paths_gt, img_paths_lq): # get the relative paths img_name_gt = os.path.relpath(img_path_gt, args.root[0]) img_name_lq = os.path.relpath(img_path_lq, args.root[1]) print(f'{img_name_gt}, {img_name_lq}') txt_file.write(f'{img_name_gt}, {img_name_lq}\n') if __name__ == '__main__': """This script is used to generate meta info (txt file) for paired images. """ parser = argparse.ArgumentParser() parser.add_argument( '--input', nargs='+', default=['datasets/DF2K/DIV2K_train_HR_sub', 'datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub'], help='Input folder, should be [gt_folder, lq_folder]') parser.add_argument('--root', nargs='+', default=[None, None], help='Folder root, will use the ') parser.add_argument( '--meta_info', type=str, default='datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt', help='txt path for meta info') args = parser.parse_args() assert len(args.input) == 2, 'Input folder should have two elements: gt folder and lq folder' assert len(args.root) == 2, 'Root path should have two elements: root for gt folder and lq folder' os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) for i in range(2): if args.input[i].endswith('/'): args.input[i] = args.input[i][:-1] if args.root[i] is None: args.root[i] = os.path.dirname(args.input[i]) main(args) ================================================ FILE: KDSR-GAN/scripts/generate_multiscale_DF2K.py ================================================ import argparse import glob import os from PIL import Image def main(args): # For DF2K, we consider the following three scales, # and the smallest image whose shortest edge is 400 scale_list = [0.75, 0.5, 1 / 3] shortest_edge = 400 path_list = sorted(glob.glob(os.path.join(args.input, '*'))) for path in path_list: print(path) basename = os.path.splitext(os.path.basename(path))[0] img = Image.open(path) width, height = img.size for idx, scale in enumerate(scale_list): print(f'\t{scale:.2f}') rlt = img.resize((int(width * scale), int(height * scale)), resample=Image.LANCZOS) rlt.save(os.path.join(args.output, f'{basename}T{idx}.png')) # save the smallest image which the shortest edge is 400 if width < height: ratio = height / width width = shortest_edge height = int(width * ratio) else: ratio = width / height height = shortest_edge width = int(height * ratio) rlt = img.resize((int(width), int(height)), resample=Image.LANCZOS) rlt.save(os.path.join(args.output, f'{basename}T{idx+1}.png')) if __name__ == '__main__': """Generate multi-scale versions for GT images with LANCZOS resampling. It is now used for DF2K dataset (DIV2K + Flickr 2K) """ parser = argparse.ArgumentParser() parser.add_argument('--input', type=str, default='/mnt/bd/dlspace-hl-256g-0001/datasets/DF2K/HR', help='Input folder') parser.add_argument('--output', type=str, default='/mnt/bd/dlspace-hl-256g-0001/datasets/DF2K/DF2K_multiscale', help='Output folder') args = parser.parse_args() os.makedirs(args.output, exist_ok=True) main(args) ================================================ FILE: KDSR-GAN/scripts/pytorch2onnx.py ================================================ import argparse import torch import torch.onnx from basicsr.archs.rrdbnet_arch import RRDBNet def main(args): # An instance of the model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) if args.params: keyname = 'params' else: keyname = 'params_ema' model.load_state_dict(torch.load(args.input)[keyname]) # set the train mode to false since we will only run the forward pass. model.train(False) model.cpu().eval() # An example input x = torch.rand(1, 3, 64, 64) # Export the model with torch.no_grad(): torch_out = torch.onnx._export(model, x, args.output, opset_version=11, export_params=True) print(torch_out.shape) if __name__ == '__main__': """Convert pytorch model to onnx models""" parser = argparse.ArgumentParser() parser.add_argument( '--input', type=str, default='experiments/pretrained_models/RealESRGAN_x4plus.pth', help='Input model path') parser.add_argument('--output', type=str, default='realesrgan-x4.onnx', help='Output onnx path') parser.add_argument('--params', action='store_false', help='Use params instead of params_ema') args = parser.parse_args() main(args) ================================================ FILE: KDSR-GAN/setup.cfg ================================================ [flake8] ignore = # line break before binary operator (W503) W503, # line break after binary operator (W504) W504, max-line-length=120 [yapf] based_on_style = pep8 column_limit = 120 blank_line_before_nested_class_or_def = true split_before_expression_after_opening_paren = true [isort] line_length = 120 multi_line_output = 0 known_standard_library = pkg_resources,setuptools known_first_party = realesrgan known_third_party = PIL,basicsr,cv2,numpy,pytest,torch,torchvision,tqdm,yaml no_lines_before = STDLIB,LOCALFOLDER default_section = THIRDPARTY [codespell] skip = .git,./docs/build count = quiet-level = 3 [aliases] test=pytest [tool:pytest] addopts=tests/ ================================================ FILE: KDSR-GAN/setup.py ================================================ #!/usr/bin/env python from setuptools import find_packages, setup import os import subprocess import time version_file = 'kdsrgan/version.py' def readme(): with open('README.md', encoding='utf-8') as f: content = f.read() return content def get_git_hash(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH', 'HOME']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) sha = out.strip().decode('ascii') except OSError: sha = 'unknown' return sha def get_hash(): if os.path.exists('.git'): sha = get_git_hash()[:7] else: sha = 'unknown' return sha def write_version_py(): content = """# GENERATED VERSION FILE # TIME: {} __version__ = '{}' __gitsha__ = '{}' version_info = ({}) """ sha = get_hash() with open('VERSION', 'r') as f: SHORT_VERSION = f.read().strip() VERSION_INFO = ', '.join([x if x.isdigit() else f'"{x}"' for x in SHORT_VERSION.split('.')]) version_file_str = content.format(time.asctime(), SHORT_VERSION, sha, VERSION_INFO) with open(version_file, 'w') as f: f.write(version_file_str) def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__'] def get_requirements(filename='requirements.txt'): here = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(here, filename), 'r') as f: requires = [line.replace('\n', '') for line in f.readlines()] return requires if __name__ == '__main__': write_version_py() setup( name='realesrgan', version=get_version(), description='Real-ESRGAN aims at developing Practical Algorithms for General Image Restoration', long_description=readme(), long_description_content_type='text/markdown', author='Xintao Wang', author_email='xintao.wang@outlook.com', keywords='computer vision, pytorch, image restoration, super-resolution, esrgan, real-esrgan', url='https://github.com/xinntao/Real-ESRGAN', include_package_data=True, packages=find_packages(exclude=('options', 'datasets', 'experiments', 'results', 'tb_logger', 'wandb')), classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], license='BSD-3-Clause License', setup_requires=['cython', 'numpy'], install_requires=get_requirements(), zip_safe=False) ================================================ FILE: KDSR-GAN/test.sh ================================================ python3 kdsrgan/test.py -opt options/test_kdsrgan_x4ST.yml ================================================ FILE: KDSR-GAN/tests/data/gt.lmdb/meta_info.txt ================================================ baboon.png (480,500,3) 1 comic.png (360,240,3) 1 ================================================ FILE: KDSR-GAN/tests/data/lq.lmdb/meta_info.txt ================================================ baboon.png (120,125,3) 1 comic.png (80,60,3) 1 ================================================ FILE: KDSR-GAN/tests/data/meta_info_gt.txt ================================================ baboon.png comic.png ================================================ FILE: KDSR-GAN/tests/data/meta_info_pair.txt ================================================ gt/baboon.png, lq/baboon.png gt/comic.png, lq/comic.png ================================================ FILE: KDSR-GAN/tests/data/test_realesrgan_dataset.yml ================================================ name: Demo type: RealESRGANDataset dataroot_gt: tests/data/gt meta_info: tests/data/meta_info_gt.txt io_backend: type: disk blur_kernel_size: 21 kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob: 1 blur_sigma: [0.2, 3] betag_range: [0.5, 4] betap_range: [1, 2] blur_kernel_size2: 21 kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] sinc_prob2: 1 blur_sigma2: [0.2, 1.5] betag_range2: [0.5, 4] betap_range2: [1, 2] final_sinc_prob: 1 gt_size: 128 use_hflip: True use_rot: False ================================================ FILE: KDSR-GAN/tests/data/test_realesrgan_model.yml ================================================ scale: 4 num_gpu: 1 manual_seed: 0 is_train: True dist: False # ----------------- options for synthesizing training data ----------------- # # USM the ground-truth l1_gt_usm: True percep_gt_usm: True gan_gt_usm: False # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 1 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 1 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 1 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 1 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 1 jpeg_range2: [30, 95] gt_size: 32 queue_size: 1 # network structures network_g: type: RRDBNet num_in_ch: 3 num_out_ch: 3 num_feat: 4 num_block: 1 num_grow_ch: 2 network_d: type: UNetDiscriminatorSN num_in_ch: 3 num_feat: 2 skip_connection: True # path path: pretrain_network_g: ~ param_key_g: params_ema strict_load_g: true resume_state: ~ # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] optim_d: type: Adam lr: !!float 1e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [400000] gamma: 0.5 total_iter: 400000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean # perceptual loss (content and style losses) perceptual_opt: type: PerceptualLoss layer_weights: # before relu 'conv1_2': 0.1 'conv2_2': 0.1 'conv3_4': 1 'conv4_4': 1 'conv5_4': 1 vgg_type: vgg19 use_input_norm: true perceptual_weight: !!float 1.0 style_weight: 0 range_norm: false criterion: l1 # gan loss gan_opt: type: GANLoss gan_type: vanilla real_label_val: 1.0 fake_label_val: 0.0 loss_weight: !!float 1e-1 net_d_iters: 1 net_d_init_iters: 0 # validation settings val: val_freq: !!float 5e3 save_img: False ================================================ FILE: KDSR-GAN/tests/data/test_realesrgan_paired_dataset.yml ================================================ name: Demo type: RealESRGANPairedDataset scale: 4 dataroot_gt: tests/data dataroot_lq: tests/data meta_info: tests/data/meta_info_pair.txt io_backend: type: disk phase: train gt_size: 128 use_hflip: True use_rot: False ================================================ FILE: KDSR-GAN/tests/data/test_realesrnet_model.yml ================================================ scale: 4 num_gpu: 1 manual_seed: 0 is_train: True dist: False # ----------------- options for synthesizing training data ----------------- # gt_usm: True # USM the ground-truth # the first degradation process resize_prob: [0.2, 0.7, 0.1] # up, down, keep resize_range: [0.15, 1.5] gaussian_noise_prob: 1 noise_range: [1, 30] poisson_scale_range: [0.05, 3] gray_noise_prob: 1 jpeg_range: [30, 95] # the second degradation process second_blur_prob: 1 resize_prob2: [0.3, 0.4, 0.3] # up, down, keep resize_range2: [0.3, 1.2] gaussian_noise_prob2: 1 noise_range2: [1, 25] poisson_scale_range2: [0.05, 2.5] gray_noise_prob2: 1 jpeg_range2: [30, 95] gt_size: 32 queue_size: 1 # network structures network_g: type: RRDBNet num_in_ch: 3 num_out_ch: 3 num_feat: 4 num_block: 1 num_grow_ch: 2 # path path: pretrain_network_g: ~ param_key_g: params_ema strict_load_g: true resume_state: ~ # training settings train: ema_decay: 0.999 optim_g: type: Adam lr: !!float 2e-4 weight_decay: 0 betas: [0.9, 0.99] scheduler: type: MultiStepLR milestones: [1000000] gamma: 0.5 total_iter: 1000000 warmup_iter: -1 # no warm up # losses pixel_opt: type: L1Loss loss_weight: 1.0 reduction: mean # validation settings val: val_freq: !!float 5e3 save_img: False ================================================ FILE: KDSR-GAN/tests/test_dataset.py ================================================ import pytest import yaml from realesrgan.data.realesrgan_dataset import RealESRGANDataset from realesrgan.data.realesrgan_paired_dataset import RealESRGANPairedDataset def test_realesrgan_dataset(): with open('tests/data/test_realesrgan_dataset.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullLoader) dataset = RealESRGANDataset(opt) assert dataset.io_backend_opt['type'] == 'disk' # io backend assert len(dataset) == 2 # whether to read correct meta info assert dataset.kernel_list == [ 'iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso' ] # correct initialization the degradation configurations assert dataset.betag_range2 == [0.5, 4] # test __getitem__ result = dataset.__getitem__(0) # check returned keys expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 400, 400) assert result['kernel1'].shape == (21, 21) assert result['kernel2'].shape == (21, 21) assert result['sinc_kernel'].shape == (21, 21) assert result['gt_path'] == 'tests/data/gt/baboon.png' # ------------------ test lmdb backend -------------------- # opt['dataroot_gt'] = 'tests/data/gt.lmdb' opt['io_backend']['type'] = 'lmdb' dataset = RealESRGANDataset(opt) assert dataset.io_backend_opt['type'] == 'lmdb' # io backend assert len(dataset.paths) == 2 # whether to read correct meta info assert dataset.kernel_list == [ 'iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso' ] # correct initialization the degradation configurations assert dataset.betag_range2 == [0.5, 4] # test __getitem__ result = dataset.__getitem__(1) # check returned keys expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 400, 400) assert result['kernel1'].shape == (21, 21) assert result['kernel2'].shape == (21, 21) assert result['sinc_kernel'].shape == (21, 21) assert result['gt_path'] == 'comic' # ------------------ test with sinc_prob = 0 -------------------- # opt['dataroot_gt'] = 'tests/data/gt.lmdb' opt['io_backend']['type'] = 'lmdb' opt['sinc_prob'] = 0 opt['sinc_prob2'] = 0 opt['final_sinc_prob'] = 0 dataset = RealESRGANDataset(opt) result = dataset.__getitem__(0) # check returned keys expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 400, 400) assert result['kernel1'].shape == (21, 21) assert result['kernel2'].shape == (21, 21) assert result['sinc_kernel'].shape == (21, 21) assert result['gt_path'] == 'baboon' # ------------------ lmdb backend should have paths ends with lmdb -------------------- # with pytest.raises(ValueError): opt['dataroot_gt'] = 'tests/data/gt' opt['io_backend']['type'] = 'lmdb' dataset = RealESRGANDataset(opt) def test_realesrgan_paired_dataset(): with open('tests/data/test_realesrgan_paired_dataset.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullLoader) dataset = RealESRGANPairedDataset(opt) assert dataset.io_backend_opt['type'] == 'disk' # io backend assert len(dataset) == 2 # whether to read correct meta info # test __getitem__ result = dataset.__getitem__(0) # check returned keys expected_keys = ['gt', 'lq', 'gt_path', 'lq_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 128, 128) assert result['lq'].shape == (3, 32, 32) assert result['gt_path'] == 'tests/data/gt/baboon.png' assert result['lq_path'] == 'tests/data/lq/baboon.png' # ------------------ test lmdb backend -------------------- # opt['dataroot_gt'] = 'tests/data/gt.lmdb' opt['dataroot_lq'] = 'tests/data/lq.lmdb' opt['io_backend']['type'] = 'lmdb' dataset = RealESRGANPairedDataset(opt) assert dataset.io_backend_opt['type'] == 'lmdb' # io backend assert len(dataset) == 2 # whether to read correct meta info # test __getitem__ result = dataset.__getitem__(1) # check returned keys expected_keys = ['gt', 'lq', 'gt_path', 'lq_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 128, 128) assert result['lq'].shape == (3, 32, 32) assert result['gt_path'] == 'comic' assert result['lq_path'] == 'comic' # ------------------ test paired_paths_from_folder -------------------- # opt['dataroot_gt'] = 'tests/data/gt' opt['dataroot_lq'] = 'tests/data/lq' opt['io_backend'] = dict(type='disk') opt['meta_info'] = None dataset = RealESRGANPairedDataset(opt) assert dataset.io_backend_opt['type'] == 'disk' # io backend assert len(dataset) == 2 # whether to read correct meta info # test __getitem__ result = dataset.__getitem__(0) # check returned keys expected_keys = ['gt', 'lq', 'gt_path', 'lq_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 128, 128) assert result['lq'].shape == (3, 32, 32) # ------------------ test normalization -------------------- # dataset.mean = [0.5, 0.5, 0.5] dataset.std = [0.5, 0.5, 0.5] # test __getitem__ result = dataset.__getitem__(0) # check returned keys expected_keys = ['gt', 'lq', 'gt_path', 'lq_path'] assert set(expected_keys).issubset(set(result.keys())) # check shape and contents assert result['gt'].shape == (3, 128, 128) assert result['lq'].shape == (3, 32, 32) ================================================ FILE: KDSR-GAN/tests/test_discriminator_arch.py ================================================ import torch from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN def test_unetdiscriminatorsn(): """Test arch: UNetDiscriminatorSN.""" # model init and forward (cpu) net = UNetDiscriminatorSN(num_in_ch=3, num_feat=4, skip_connection=True) img = torch.rand((1, 3, 32, 32), dtype=torch.float32) output = net(img) assert output.shape == (1, 1, 32, 32) # model init and forward (gpu) if torch.cuda.is_available(): net.cuda() output = net(img.cuda()) assert output.shape == (1, 1, 32, 32) ================================================ FILE: KDSR-GAN/tests/test_model.py ================================================ import torch import yaml from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.data.paired_image_dataset import PairedImageDataset from basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN from realesrgan.models.realesrgan_model import RealESRGANModel from realesrgan.models.realesrnet_model import RealESRNetModel def test_realesrnet_model(): with open('tests/data/test_realesrnet_model.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullLoader) # build model model = RealESRNetModel(opt) # test attributes assert model.__class__.__name__ == 'RealESRNetModel' assert isinstance(model.net_g, RRDBNet) assert isinstance(model.cri_pix, L1Loss) assert isinstance(model.optimizers[0], torch.optim.Adam) # prepare data gt = torch.rand((1, 3, 32, 32), dtype=torch.float32) kernel1 = torch.rand((1, 5, 5), dtype=torch.float32) kernel2 = torch.rand((1, 5, 5), dtype=torch.float32) sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32) data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel) model.feed_data(data) # check dequeue model.feed_data(data) # check data shape assert model.lq.shape == (1, 3, 8, 8) assert model.gt.shape == (1, 3, 32, 32) # change probability to test if-else model.opt['gaussian_noise_prob'] = 0 model.opt['gray_noise_prob'] = 0 model.opt['second_blur_prob'] = 0 model.opt['gaussian_noise_prob2'] = 0 model.opt['gray_noise_prob2'] = 0 model.feed_data(data) # check data shape assert model.lq.shape == (1, 3, 8, 8) assert model.gt.shape == (1, 3, 32, 32) # ----------------- test nondist_validation -------------------- # # construct dataloader dataset_opt = dict( name='Demo', dataroot_gt='tests/data/gt', dataroot_lq='tests/data/lq', io_backend=dict(type='disk'), scale=4, phase='val') dataset = PairedImageDataset(dataset_opt) dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0) assert model.is_train is True model.nondist_validation(dataloader, 1, None, False) assert model.is_train is True def test_realesrgan_model(): with open('tests/data/test_realesrgan_model.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullLoader) # build model model = RealESRGANModel(opt) # test attributes assert model.__class__.__name__ == 'RealESRGANModel' assert isinstance(model.net_g, RRDBNet) # generator assert isinstance(model.net_d, UNetDiscriminatorSN) # discriminator assert isinstance(model.cri_pix, L1Loss) assert isinstance(model.cri_perceptual, PerceptualLoss) assert isinstance(model.cri_gan, GANLoss) assert isinstance(model.optimizers[0], torch.optim.Adam) assert isinstance(model.optimizers[1], torch.optim.Adam) # prepare data gt = torch.rand((1, 3, 32, 32), dtype=torch.float32) kernel1 = torch.rand((1, 5, 5), dtype=torch.float32) kernel2 = torch.rand((1, 5, 5), dtype=torch.float32) sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32) data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel) model.feed_data(data) # check dequeue model.feed_data(data) # check data shape assert model.lq.shape == (1, 3, 8, 8) assert model.gt.shape == (1, 3, 32, 32) # change probability to test if-else model.opt['gaussian_noise_prob'] = 0 model.opt['gray_noise_prob'] = 0 model.opt['second_blur_prob'] = 0 model.opt['gaussian_noise_prob2'] = 0 model.opt['gray_noise_prob2'] = 0 model.feed_data(data) # check data shape assert model.lq.shape == (1, 3, 8, 8) assert model.gt.shape == (1, 3, 32, 32) # ----------------- test nondist_validation -------------------- # # construct dataloader dataset_opt = dict( name='Demo', dataroot_gt='tests/data/gt', dataroot_lq='tests/data/lq', io_backend=dict(type='disk'), scale=4, phase='val') dataset = PairedImageDataset(dataset_opt) dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0) assert model.is_train is True model.nondist_validation(dataloader, 1, None, False) assert model.is_train is True # ----------------- test optimize_parameters -------------------- # model.feed_data(data) model.optimize_parameters(1) assert model.output.shape == (1, 3, 32, 32) assert isinstance(model.log_dict, dict) # check returned keys expected_keys = ['l_g_pix', 'l_g_percep', 'l_g_gan', 'l_d_real', 'out_d_real', 'l_d_fake', 'out_d_fake'] assert set(expected_keys).issubset(set(model.log_dict.keys())) ================================================ FILE: KDSR-GAN/tests/test_utils.py ================================================ import numpy as np from basicsr.archs.rrdbnet_arch import RRDBNet from realesrgan.utils import RealESRGANer def test_realesrganer(): # initialize with default model restorer = RealESRGANer( scale=4, model_path='experiments/pretrained_models/RealESRGAN_x4plus.pth', model=None, tile=10, tile_pad=10, pre_pad=2, half=False) assert isinstance(restorer.model, RRDBNet) assert restorer.half is False # initialize with user-defined model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) restorer = RealESRGANer( scale=4, model_path='experiments/pretrained_models/RealESRGAN_x4plus_anime_6B.pth', model=model, tile=10, tile_pad=10, pre_pad=2, half=True) # test attribute assert isinstance(restorer.model, RRDBNet) assert restorer.half is True # ------------------ test pre_process ---------------- # img = np.random.random((12, 12, 3)).astype(np.float32) restorer.pre_process(img) assert restorer.img.shape == (1, 3, 14, 14) # with modcrop restorer.scale = 1 restorer.pre_process(img) assert restorer.img.shape == (1, 3, 16, 16) # ------------------ test process ---------------- # restorer.process() assert restorer.output.shape == (1, 3, 64, 64) # ------------------ test post_process ---------------- # restorer.mod_scale = 4 output = restorer.post_process() assert output.shape == (1, 3, 60, 60) # ------------------ test tile_process ---------------- # restorer.scale = 4 img = np.random.random((12, 12, 3)).astype(np.float32) restorer.pre_process(img) restorer.tile_process() assert restorer.output.shape == (1, 3, 64, 64) # ------------------ test enhance ---------------- # img = np.random.random((12, 12, 3)).astype(np.float32) result = restorer.enhance(img, outscale=2) assert result[0].shape == (24, 24, 3) assert result[1] == 'RGB' # ------------------ test enhance with 16-bit image---------------- # img = np.random.random((4, 4, 3)).astype(np.uint16) + 512 result = restorer.enhance(img, outscale=2) assert result[0].shape == (8, 8, 3) assert result[1] == 'RGB' # ------------------ test enhance with gray image---------------- # img = np.random.random((4, 4)).astype(np.float32) result = restorer.enhance(img, outscale=2) assert result[0].shape == (8, 8) assert result[1] == 'L' # ------------------ test enhance with RGBA---------------- # img = np.random.random((4, 4, 4)).astype(np.float32) result = restorer.enhance(img, outscale=2) assert result[0].shape == (8, 8, 4) assert result[1] == 'RGBA' # ------------------ test enhance with RGBA, alpha_upsampler---------------- # restorer.tile_size = 0 img = np.random.random((4, 4, 4)).astype(np.float32) result = restorer.enhance(img, outscale=2, alpha_upsampler=None) assert result[0].shape == (8, 8, 4) assert result[1] == 'RGBA' ================================================ FILE: KDSR-GAN/train_KDSRGAN_S.sh ================================================ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=4397 kdsrgan/train.py -opt options/train_kdsrgan_x4ST.yml --launcher pytorch ================================================ FILE: KDSR-GAN/train_KDSRNet_S.sh ================================================ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=4349 kdsrgan/train.py -opt options/train_kdsrnet_x4ST.yml --launcher pytorch ================================================ FILE: KDSR-GAN/train_KDSRNet_T.sh ================================================ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=3309 kdsrgan/train.py -opt options/train_kdsrnet_x4TA.yml --launcher pytorch ================================================ FILE: KDSR-classic/README.md ================================================ # KDSR-classic This project is the official implementation of 'Knowledge Distillation based Degradation Estimation for Blind Super-Resolution', ICLR2023 > **Knowledge Distillation based Degradation Estimation for Blind Super-Resolution [[Paper](https://arxiv.org/pdf/2211.16928.pdf)] [[Project](https://github.com/Zj-BinXia/KDSR)]** This is code for KDSR-class (for classic degradation model, ie y=kx+n)

--- ## Dependencies and Installation - Python >= 3.8 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html)) - [PyTorch >= 1.10](https://pytorch.org/) ## Dataset Preparation We use DF2K, which combines [DIV2K](https://data.vision.ee.ethz.ch/cvl/DIV2K/) (800 images) and [Flickr2K](https://github.com/LimBee/NTIRE2017) (2650 images). --- ## Training (4 V100 GPUs) ### Isotropic Gaussian Kernels 1. We train KDSRT-M ( using L1 loss) ```bash sh main_iso_KDSRsMx4_stage3.sh ``` 2. we train KDSRS-M (using L1 loss and KD loss). **It is notable that modify the ''pre_train_TA'' and ''pre_train_ST'' of main_iso_KDSRsMx4_stage4.sh to the path of trained KDSRT-M checkpoint.** Then, we run ```bash sh main_iso_KDSRsMx4_stage4.sh ``` ### Anisotropic Gaussian Kernels plus noise 1. We train KDSRT ( using L1 loss) ```bash sh main_anisonoise_KDSRsMx4_stage3.sh ``` 2. we train KDSRS (using L1 loss and KD loss). **It is notable that modify the ''pre_train_TA'' and ''pre_train_ST'' of main_anisonoise_KDSRsMx4_stage4.sh to the path of trained KDSRT checkpoint.** Then, we run ```bash sh main_anisonoise_KDSRsMx4_stage4.sh ``` --- ## :european_castle: Model Zoo Please download checkpoints from [Google Drive](https://drive.google.com/drive/folders/113NBvfcrCedvend96KqDiRYVy3N8yprl). --- ## Testing ### Isotropic Gaussian Kernels Test KDSRsM ```bash sh test_iso_KDSRsMx4.sh ``` Test KDSRsL ```bash sh test_iso_KDSRsLx4.sh ``` ### Anisotropic Gaussian Kernels plus noise ```bash sh test_anisonoise_KDSRsMx4.sh ``` --- ## Results

--- ## BibTeX @InProceedings{xia2022knowledge, title={Knowledge Distillation based Degradation Estimation for Blind Super-Resolution}, author={Xia, Bin and Zhang, Yulun and Wang, Yitong and Tian, Yapeng and Yang, Wenming and Timofte, Radu and Van Gool, Luc}, journal={ICLR}, year={2023} } ## Acknowledgements This code is built on [EDSR (PyTorch)](https://github.com/thstkdgus35/EDSR-PyTorch), [IKC](https://github.com/yuanjunchai/IKC). We thank the authors for sharing the codes. ## 📧 Contact If you have any question, please email `zjbinxia@gmail.com`. ================================================ FILE: KDSR-classic/cal_parms.py ================================================ def count_param(model): param_count = 0 for param in model.parameters(): param_count += param.view(-1).size()[0] return param_count from option import args from model_ST.blindsr import make_model # args.n_feats=64 args.scale=[4] net = make_model(args) print("KDSRs-M parameters (M):",count_param(net)) args.scale=[4] args.n_feats=128 args.n_blocks=28 args.n_resblocks=5 net = make_model(args) print("KDSRs-L parameters (M):",count_param(net)) ================================================ FILE: KDSR-classic/data/__init__.py ================================================ from importlib import import_module #from dataloader import MSDataLoader from torch.utils.data import dataloader from torch.utils.data import ConcatDataset # This is a simple wrapper function for ConcatDataset class MyConcatDataset(ConcatDataset): def __init__(self, datasets): super(MyConcatDataset, self).__init__(datasets) self.train = datasets[0].train def set_scale(self, idx_scale): for d in self.datasets: if hasattr(d, 'set_scale'): d.set_scale(idx_scale) class Data: def __init__(self, args): self.loader_train = None if not args.test_only: datasets = [] for d in args.data_train: print(d) module_name = d if d.find('DIV2K-Q') < 0 else 'DIV2KJPEG' m = import_module('data.' + module_name.lower()) datasets.append(getattr(m, module_name)(args, name=d)) self.loader_train = dataloader.DataLoader( MyConcatDataset(datasets), batch_size=args.batch_size, shuffle=True, pin_memory=not args.cpu, num_workers=args.n_threads, ) self.loader_test = [] for d in args.data_test: if d in ['Set5', 'Set14', 'B100', 'Urban100',"MANGA109"]: m = import_module('data.benchmark') testset = getattr(m, 'Benchmark')(args, train=False, name=d) else: module_name = d if d.find('DIV2K-Q') < 0 else 'DIV2KJPEG' m = import_module('data.' + module_name.lower()) testset = getattr(m, module_name)(args, train=False, name=d) self.loader_test.append( dataloader.DataLoader( testset, batch_size=1, shuffle=False, pin_memory=not args.cpu, num_workers=args.n_threads, ) ) ================================================ FILE: KDSR-classic/data/benchmark.py ================================================ import os from data import common from data import multiscalesrdata as srdata class Benchmark(srdata.SRData): def __init__(self, args, name='', train=True): super(Benchmark, self).__init__( args, name=name, train=train, benchmark=True ) def _set_filesystem(self, dir_data): self.apath = os.path.join(dir_data,'benchmark', self.name) self.dir_hr = os.path.join(self.apath, 'HR') self.dir_lr = os.path.join(self.apath, 'LR_bicubic') self.ext = ('.png','.png') print(self.dir_hr) print(self.dir_lr) ================================================ FILE: KDSR-classic/data/common.py ================================================ import random import numpy as np import skimage.color as sc import torch def get_patch(hr, patch_size=48, scale=2, multi=False, input_large=False): ih, iw = hr.shape[:2] ip = scale * patch_size ix = random.randrange(0, iw - ip + 1) iy = random.randrange(0, ih - ip + 1) hr = hr[iy:iy + ip, ix:ix + ip, :] return hr def set_channel(hr, n_channels=3): def _set_channel(img): if img.ndim == 2: img = np.expand_dims(img, axis=2) c = img.shape[2] if n_channels == 1 and c == 3: img = np.expand_dims(sc.rgb2ycbcr(img)[:, :, 0], 2) elif n_channels == 3 and c == 1: img = np.concatenate([img] * n_channels, 2) return img return _set_channel(hr) def np2Tensor(hr, rgb_range=255): def _np2Tensor(img): np_transpose = np.ascontiguousarray(img.transpose((2, 0, 1))) tensor = torch.from_numpy(np_transpose).float() tensor.mul_(rgb_range / 255) return tensor return _np2Tensor(hr) def augment(hr, hflip=True, rot=True): hflip = hflip and random.random() < 0.5 vflip = rot and random.random() < 0.5 rot90 = rot and random.random() < 0.5 def _augment(img): if hflip: img = img[:, ::-1, :] if vflip: img = img[::-1, :, :] if rot90: img = img.transpose(1, 0, 2) return img return _augment(hr) ================================================ FILE: KDSR-classic/data/common2.py ================================================ import random import numpy as np import skimage.color as sc import torch def get_patch(*args, patch_size=96, scale=2, multi=False, input_large=False): ih, iw = args[0].shape[:2] if not input_large: p = scale if multi else 1 tp = p * patch_size ip = tp // scale else: tp = patch_size ip = patch_size ix = random.randrange(0, iw - ip + 1) iy = random.randrange(0, ih - ip + 1) if not input_large: tx, ty = scale * ix, scale * iy else: tx, ty = ix, iy ret = [ args[0][iy:iy + ip, ix:ix + ip, :], *[a[ty:ty + tp, tx:tx + tp, :] for a in args[1:]] ] return ret def set_channel(*args, n_channels=3): def _set_channel(img): if img.ndim == 2: img = np.expand_dims(img, axis=2) c = img.shape[2] if n_channels == 1 and c == 3: img = np.expand_dims(sc.rgb2ycbcr(img)[:, :, 0], 2) elif n_channels == 3 and c == 1: img = np.concatenate([img] * n_channels, 2) return img return [_set_channel(a) for a in args] def np2Tensor(*args, rgb_range=255): def _np2Tensor(img): np_transpose = np.ascontiguousarray(img.transpose((2, 0, 1))) tensor = torch.from_numpy(np_transpose).float() tensor.mul_(rgb_range / 255) return tensor return [_np2Tensor(a) for a in args] def augment(*args, hflip=True, rot=True): hflip = hflip and random.random() < 0.5 vflip = rot and random.random() < 0.5 rot90 = rot and random.random() < 0.5 def _augment(img): if hflip: img = img[:, ::-1, :] if vflip: img = img[::-1, :, :] if rot90: img = img.transpose(1, 0, 2) return img return [_augment(a) for a in args] ================================================ FILE: KDSR-classic/data/df2k.py ================================================ import os from data import multiscalesrdata class DF2K(multiscalesrdata.SRData): def __init__(self, args, name='DF2K', train=True, benchmark=False): data_range = [r.split('-') for r in args.data_range.split('/')] if train: data_range = data_range[0] else: if args.test_only and len(data_range) == 1: data_range = data_range[0] else: data_range = data_range[1] self.begin, self.end = list(map(lambda x: int(x), data_range)) super(DF2K, self).__init__(args, name=name, train=train, benchmark=benchmark) def _scan(self): names_hr = super(DF2K, self)._scan() names_hr = names_hr[self.begin - 1:self.end] return names_hr def _set_filesystem(self, dir_data): super(DF2K, self)._set_filesystem(dir_data) self.dir_hr = os.path.join(self.apath, 'HR') self.dir_lr = os.path.join(self.apath, 'LR_bicubic') ================================================ FILE: KDSR-classic/data/multiscalesrdata.py ================================================ import os import glob import random import pickle from data import common import numpy as np import imageio import torch import torch.utils.data as data class SRData(data.Dataset): def __init__(self, args, name='', train=True, benchmark=False): self.args = args self.name = name self.train = train self.split = 'train' if train else 'test' self.do_eval = True self.benchmark = benchmark self.input_large = (args.model == 'VDSR') self.scale = args.scale self.idx_scale = 0 self._set_filesystem(args.dir_data) if args.ext.find('img') < 0: path_bin = os.path.join(self.apath, 'bin') os.makedirs(path_bin, exist_ok=True) list_hr, list_lr = self._scan() if args.ext.find('img') >= 0 or benchmark: self.images_hr, self.images_lr = list_hr, list_lr elif args.ext.find('sep') >= 0: os.makedirs( self.dir_hr.replace(self.apath, path_bin), exist_ok=True ) for s in self.scale: os.makedirs( os.path.join( self.dir_lr.replace(self.apath, path_bin), 'X{}'.format(s) ), exist_ok=True ) self.images_hr, self.images_lr = [], [[] for _ in self.scale] for h in list_hr: b = h.replace(self.apath, path_bin) b = b.replace(self.ext[0], '.pt') self.images_hr.append(b) self._check_and_load(args.ext, h, b, verbose=True) for i, ll in enumerate(list_lr): for l in ll: b = l.replace(self.apath, path_bin) b = b.replace(self.ext[1], '.pt') self.images_lr[i].append(b) self._check_and_load(args.ext, l, b, verbose=True) if train: n_patches = args.batch_size * args.test_every n_images = len(args.data_train) * len(self.images_hr) if n_images == 0: self.repeat = 0 else: self.repeat = max(n_patches // n_images, 1) # Below functions as used to prepare images def _scan(self): names_hr = sorted( glob.glob(os.path.join(self.dir_hr, '*' + self.ext[0])) ) names_lr = [[] for _ in self.scale] for f in names_hr: filename, _ = os.path.splitext(os.path.basename(f)) for si, s in enumerate(self.scale): names_lr[si].append(os.path.join( self.dir_lr, 'X{}/{}x{}{}'.format( s, filename, s, self.ext[1] ) )) return names_hr, names_lr def _set_filesystem(self, dir_data): self.apath = os.path.join(dir_data, self.name) self.dir_hr = os.path.join(self.apath, 'HR') self.dir_lr = os.path.join(self.apath, 'LR_bicubic') if self.input_large: self.dir_lr += 'L' self.ext = ('.png', '.png') def _check_and_load(self, ext, img, f, verbose=True): if not os.path.isfile(f) or ext.find('reset') >= 0: if verbose: print('Making a binary: {}'.format(f)) with open(f, 'wb') as _f: pickle.dump(imageio.imread(img), _f) def __getitem__(self, idx): hr, filename = self._load_file(idx) hr = self.get_patch( hr) hr = common.set_channel(hr, n_channels=self.args.n_colors) hr = common.np2Tensor(hr, rgb_range=self.args.rgb_range) return hr, filename def __len__(self): if self.train: return len(self.images_hr) * self.repeat else: return len(self.images_hr) def _get_index(self, idx): if self.train: return idx % len(self.images_hr) else: return idx def _load_file(self, idx): idx = self._get_index(idx) f_hr = self.images_hr[idx] filename, _ = os.path.splitext(os.path.basename(f_hr)) if self.args.ext == 'img' or self.benchmark: hr = imageio.imread(f_hr) elif self.args.ext.find('sep') >= 0: with open(f_hr, 'rb') as _f: hr = pickle.load(_f) return hr, filename def get_patch(self, hr): scale = self.scale[self.idx_scale] if self.train: hr = common.get_patch( hr, patch_size=self.args.patch_size, scale=scale, multi=(len(self.scale) > 1), input_large=self.input_large ) if not self.args.no_augment: hr = common.augment( hr) else: ih, iw = hr.shape[:2] ih = ih//scale iw = iw // scale hr = hr[0:ih * scale, 0:iw * scale] return hr def set_scale(self, idx_scale): if not self.input_large: self.idx_scale = idx_scale else: self.idx_scale = random.randint(0, len(self.scale) - 1) ================================================ FILE: KDSR-classic/data/multiscalesrdata2.py ================================================ import os import glob import random import pickle from data import common2 as common import numpy as np import imageio import torch import torch.utils.data as data class SRData(data.Dataset): def __init__(self, args, name='', train=True, benchmark=False): self.args = args self.name = name self.train = train self.split = 'train' if train else 'test' self.do_eval = True self.benchmark = benchmark self.input_large = (args.model == 'VDSR') self.scale = args.scale self.idx_scale = 0 self._set_filesystem(args.dir_data) if args.ext.find('img') < 0: path_bin = os.path.join(self.apath, 'bin') os.makedirs(path_bin, exist_ok=True) list_hr, list_lr = self._scan() if args.ext.find('img') >= 0 or benchmark: self.images_hr, self.images_lr = list_hr, list_lr elif args.ext.find('sep') >= 0: os.makedirs( self.dir_hr.replace(self.apath, path_bin), exist_ok=True ) for s in self.scale: os.makedirs( os.path.join( self.dir_lr.replace(self.apath, path_bin), 'X{}'.format(s) ), exist_ok=True ) self.images_hr, self.images_lr = [], [[] for _ in self.scale] for h in list_hr: b = h.replace(self.apath, path_bin) b = b.replace(self.ext[0], '.pt') self.images_hr.append(b) self._check_and_load(args.ext, h, b, verbose=True) for i, ll in enumerate(list_lr): for l in ll: b = l.replace(self.apath, path_bin) b = b.replace(self.ext[1], '.pt') self.images_lr[i].append(b) self._check_and_load(args.ext, l, b, verbose=True) if train: n_patches = args.batch_size * args.test_every n_images = len(args.data_train) * len(self.images_hr) if n_images == 0: self.repeat = 0 else: self.repeat = max(n_patches // n_images, 1) # Below functions as used to prepare images def _scan(self): names_hr = sorted( glob.glob(os.path.join(self.dir_hr, '*' + self.ext[0])) ) names_lr = [[] for _ in self.scale] for f in names_hr: filename, _ = os.path.splitext(os.path.basename(f)) for si, s in enumerate(self.scale): names_lr[si].append(os.path.join( self.dir_lr, 'X{}/{}x{}{}'.format( s, filename, s, self.ext[1] ) )) return names_hr, names_lr def _set_filesystem(self, dir_data): self.apath = os.path.join(dir_data, self.name) self.dir_hr = os.path.join(self.apath, 'HR') self.dir_lr = os.path.join(self.apath, 'LR_bicubic') if self.input_large: self.dir_lr += 'L' self.ext = ('.png', '.png') def _check_and_load(self, ext, img, f, verbose=True): if not os.path.isfile(f) or ext.find('reset') >= 0: if verbose: print('Making a binary: {}'.format(f)) with open(f, 'wb') as _f: pickle.dump(imageio.imread(img,pilmode="RGB"), _f) def __getitem__(self, idx): lr, hr, filename = self._load_file(idx) pair = self.get_patch(lr, hr) pair = common.set_channel(*pair, n_channels=self.args.n_colors) pair_t = common.np2Tensor(*pair, rgb_range=self.args.rgb_range) return pair_t[0], pair_t[1], filename def __len__(self): if self.train: return len(self.images_hr) * self.repeat else: return len(self.images_hr) def _get_index(self, idx): if self.train: return idx % len(self.images_hr) else: return idx def _load_file(self, idx): idx = self._get_index(idx) f_hr = self.images_hr[idx] f_lr = self.images_lr[self.idx_scale][idx] filename, _ = os.path.splitext(os.path.basename(f_hr)) if self.args.ext == 'img' or self.benchmark: hr = imageio.imread(f_hr,pilmode="RGB") lr = imageio.imread(f_lr,pilmode="RGB") elif self.args.ext.find('sep') >= 0: with open(f_hr, 'rb') as _f: hr = pickle.load(_f) with open(f_lr, 'rb') as _f: lr = pickle.load(_f) return lr, hr, filename def get_patch(self, lr, hr): scale = self.scale[self.idx_scale] if self.train: lr, hr = common.get_patch( lr, hr, patch_size=self.args.patch_size, scale=scale, multi=(len(self.scale) > 1), input_large=self.input_large ) if not self.args.no_augment: lr, hr = common.augment(lr, hr) else: ih, iw = lr.shape[:2] hr = hr[0:ih * scale, 0:iw * scale] return lr, hr def set_scale(self, idx_scale): if not self.input_large: self.idx_scale = idx_scale else: self.idx_scale = random.randint(0, len(self.scale) - 1) ================================================ FILE: KDSR-classic/dataloader.py ================================================ import sys import threading import queue import random import collections import torch import torch.multiprocessing as multiprocessing from torch._C import _set_worker_signal_handlers from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataloader import _DataLoaderIter from torch.utils.data import _utils if sys.version_info[0] == 2: import Queue as queue else: import queue def _ms_loop(dataset, index_queue, data_queue, collate_fn, scale, seed, init_fn, worker_id): global _use_shared_memory _use_shared_memory = True _set_worker_signal_handlers() torch.set_num_threads(1) torch.manual_seed(seed) while True: r = index_queue.get() if r is None: break idx, batch_indices = r try: idx_scale = 0 if len(scale) > 1 and dataset.train: idx_scale = random.randrange(0, len(scale)) dataset.set_scale(idx_scale) samples = collate_fn([dataset[i] for i in batch_indices]) samples.append(idx_scale) except Exception: data_queue.put((idx, _utils.ExceptionWrapper(sys.exc_info()))) else: data_queue.put((idx, samples)) class _MSDataLoaderIter(_DataLoaderIter): def __init__(self, loader): self.dataset = loader.dataset self.scale = loader.scale self.collate_fn = loader.collate_fn self.batch_sampler = loader.batch_sampler self.num_workers = loader.num_workers self.pin_memory = loader.pin_memory and torch.cuda.is_available() self.timeout = loader.timeout self.done_event = threading.Event() self.sample_iter = iter(self.batch_sampler) if self.num_workers > 0: self.worker_init_fn = loader.worker_init_fn self.index_queues = [ multiprocessing.Queue() for _ in range(self.num_workers) ] self.worker_queue_idx = 0 self.worker_result_queue = multiprocessing.Queue() self.batches_outstanding = 0 self.worker_pids_set = False self.shutdown = False self.send_idx = 0 self.rcvd_idx = 0 self.reorder_dict = {} base_seed = torch.LongTensor(1).random_()[0] self.workers = [ multiprocessing.Process( target=_ms_loop, args=( self.dataset, self.index_queues[i], self.worker_result_queue, self.collate_fn, self.scale, base_seed + i, self.worker_init_fn, i ) ) for i in range(self.num_workers)] if self.pin_memory or self.timeout > 0: self.data_queue = queue.Queue() if self.pin_memory: maybe_device_id = torch.cuda.current_device() else: # do not initialize cuda context if not necessary maybe_device_id = None self.pin_memory_thread = threading.Thread( target=_utils.pin_memory._pin_memory_loop, args=(self.worker_result_queue, self.data_queue, maybe_device_id, self.done_event)) self.pin_memory_thread.daemon = True self.pin_memory_thread.start() else: self.data_queue = self.worker_result_queue for w in self.workers: w.daemon = True # ensure that the worker exits on process exit w.start() _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self.workers)) _utils.signal_handling._set_SIGCHLD_handler() self.worker_pids_set = True # prime the prefetch loop for _ in range(2 * self.num_workers): self._put_indices() class MSDataLoader(DataLoader): def __init__( self, args, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, collate_fn=_utils.collate.default_collate, pin_memory=False, drop_last=True, timeout=0, worker_init_fn=None): super(MSDataLoader, self).__init__( dataset, batch_size=batch_size, shuffle=shuffle, sampler=sampler, batch_sampler=batch_sampler, num_workers=args.n_threads, collate_fn=collate_fn, pin_memory=pin_memory, drop_last=drop_last, timeout=timeout, worker_init_fn=worker_init_fn) self.scale = args.scale def __iter__(self): return _MSDataLoaderIter(self) ================================================ FILE: KDSR-classic/loss/__init__.py ================================================ import os from importlib import import_module import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Loss(nn.modules.loss._Loss): def __init__(self, args, ckp): super(Loss, self).__init__() print('Preparing loss function:') self.n_GPUs = args.n_GPUs self.loss = [] self.loss_module = nn.ModuleList() for loss in args.loss.split('+'): weight, loss_type = loss.split('*') if loss_type == 'MSE': loss_function = nn.MSELoss() elif loss_type == 'L1': loss_function = nn.L1Loss() elif loss_type == 'CE': loss_function = nn.CrossEntropyLoss() elif loss_type.find('VGG') >= 0: module = import_module('loss.vgg') loss_function = getattr(module, 'VGG')( loss_type[3:], rgb_range=args.rgb_range ) elif loss_type.find('GAN') >= 0: module = import_module('loss.adversarial') loss_function = getattr(module, 'Adversarial')( args, loss_type ) self.loss.append({ 'type': loss_type, 'weight': float(weight), 'function': loss_function} ) if loss_type.find('GAN') >= 0: self.loss.append({'type': 'DIS', 'weight': 1, 'function': None}) if len(self.loss) > 1: self.loss.append({'type': 'Total', 'weight': 0, 'function': None}) for l in self.loss: if l['function'] is not None: print('{:.3f} * {}'.format(l['weight'], l['type'])) self.loss_module.append(l['function']) self.log = torch.Tensor() device = torch.device('cpu' if args.cpu else 'cuda') self.loss_module.to(device) if args.precision == 'half': self.loss_module.half() if not args.cpu and args.n_GPUs > 1: self.loss_module = nn.DataParallel( self.loss_module, range(args.n_GPUs) ) if args.load != '.': self.load(ckp.dir, cpu=args.cpu) def forward(self, sr, hr): losses = [] for i, l in enumerate(self.loss): if l['function'] is not None: loss = l['function'](sr, hr) effective_loss = l['weight'] * loss losses.append(effective_loss) self.log[-1, i] += effective_loss.item() elif l['type'] == 'DIS': self.log[-1, i] += self.loss[i - 1]['function'].loss loss_sum = sum(losses) if len(self.loss) > 1: self.log[-1, -1] += loss_sum.item() return loss_sum def step(self): for l in self.get_loss_module(): if hasattr(l, 'scheduler'): l.scheduler.step() def start_log(self): self.log = torch.cat((self.log, torch.zeros(1, len(self.loss)))) def end_log(self, n_batches): self.log[-1].div_(n_batches) def display_loss(self, batch): n_samples = batch + 1 log = [] for l, c in zip(self.loss, self.log[-1]): log.append('[{}: {:.4f}]'.format(l['type'], c / n_samples)) return ''.join(log) def plot_loss(self, apath, epoch): axis = np.linspace(1, epoch, epoch) for i, l in enumerate(self.loss): label = '{} Loss'.format(l['type']) fig = plt.figure() plt.title(label) plt.plot(axis, self.log[:, i].numpy(), label=label) plt.legend() plt.xlabel('Epochs') plt.ylabel('Loss') plt.grid(True) plt.savefig('{}/loss_{}.pdf'.format(apath, l['type'])) plt.close(fig) def get_loss_module(self): if self.n_GPUs == 1: return self.loss_module else: return self.loss_module.module def save(self, apath): torch.save(self.state_dict(), os.path.join(apath, 'loss.pt')) torch.save(self.log, os.path.join(apath, 'loss_log.pt')) def load(self, apath, cpu=False): if cpu: kwargs = {'map_location': lambda storage, loc: storage} else: kwargs = {} self.load_state_dict(torch.load( os.path.join(apath, 'loss.pt'), **kwargs )) self.log = torch.load(os.path.join(apath, 'loss_log.pt')) for l in self.loss_module: if hasattr(l, 'scheduler'): for _ in range(len(self.log)): l.scheduler.step() ================================================ FILE: KDSR-classic/loss/adversarial.py ================================================ import utility from model import common from loss import discriminator import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable class Adversarial(nn.Module): def __init__(self, args, gan_type): super(Adversarial, self).__init__() self.gan_type = gan_type self.gan_k = args.gan_k self.discriminator = discriminator.Discriminator(args, gan_type) if gan_type != 'WGAN_GP': self.optimizer = utility.make_optimizer(args, self.discriminator) else: self.optimizer = optim.Adam( self.discriminator.parameters(), betas=(0, 0.9), eps=1e-8, lr=1e-5 ) self.scheduler = utility.make_scheduler(args, self.optimizer) def forward(self, fake, real): fake_detach = fake.detach() self.loss = 0 for _ in range(self.gan_k): self.optimizer.zero_grad() d_fake = self.discriminator(fake_detach) d_real = self.discriminator(real) if self.gan_type == 'GAN': label_fake = torch.zeros_like(d_fake) label_real = torch.ones_like(d_real) loss_d \ = F.binary_cross_entropy_with_logits(d_fake, label_fake) \ + F.binary_cross_entropy_with_logits(d_real, label_real) elif self.gan_type.find('WGAN') >= 0: loss_d = (d_fake - d_real).mean() if self.gan_type.find('GP') >= 0: epsilon = torch.rand_like(fake).view(-1, 1, 1, 1) hat = fake_detach.mul(1 - epsilon) + real.mul(epsilon) hat.requires_grad = True d_hat = self.discriminator(hat) gradients = torch.autograd.grad( outputs=d_hat.sum(), inputs=hat, retain_graph=True, create_graph=True, only_inputs=True )[0] gradients = gradients.view(gradients.size(0), -1) gradient_norm = gradients.norm(2, dim=1) gradient_penalty = 10 * gradient_norm.sub(1).pow(2).mean() loss_d += gradient_penalty # Discriminator update self.loss += loss_d.item() loss_d.backward() self.optimizer.step() if self.gan_type == 'WGAN': for p in self.discriminator.parameters(): p.data.clamp_(-1, 1) self.loss /= self.gan_k d_fake_for_g = self.discriminator(fake) if self.gan_type == 'GAN': loss_g = F.binary_cross_entropy_with_logits( d_fake_for_g, label_real ) elif self.gan_type.find('WGAN') >= 0: loss_g = -d_fake_for_g.mean() # Generator loss return loss_g def state_dict(self, *args, **kwargs): state_discriminator = self.discriminator.state_dict(*args, **kwargs) state_optimizer = self.optimizer.state_dict() return dict(**state_discriminator, **state_optimizer) # Some references # https://github.com/kuc2477/pytorch-wgan-gp/blob/master/model.py # OR # https://github.com/caogang/wgan-gp/blob/master/gan_cifar10.py ================================================ FILE: KDSR-classic/loss/discriminator.py ================================================ from model import common import torch.nn as nn class Discriminator(nn.Module): def __init__(self, args, gan_type='GAN'): super(Discriminator, self).__init__() in_channels = 3 out_channels = 64 depth = 7 #bn = not gan_type == 'WGAN_GP' bn = True act = nn.LeakyReLU(negative_slope=0.2, inplace=True) m_features = [ common.BasicBlock(args.n_colors, out_channels, 3, bn=bn, act=act) ] for i in range(depth): in_channels = out_channels if i % 2 == 1: stride = 1 out_channels *= 2 else: stride = 2 m_features.append(common.BasicBlock( in_channels, out_channels, 3, stride=stride, bn=bn, act=act )) self.features = nn.Sequential(*m_features) patch_size = args.patch_size // (2**((depth + 1) // 2)) m_classifier = [ nn.Linear(out_channels * patch_size**2, 1024), act, nn.Linear(1024, 1) ] self.classifier = nn.Sequential(*m_classifier) def forward(self, x): features = self.features(x) output = self.classifier(features.view(features.size(0), -1)) return output ================================================ FILE: KDSR-classic/loss/vgg.py ================================================ from model import common import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from torch.autograd import Variable class VGG(nn.Module): def __init__(self, conv_index, rgb_range=1): super(VGG, self).__init__() vgg_features = models.vgg19(pretrained=True).features modules = [m for m in vgg_features] if conv_index == '22': self.vgg = nn.Sequential(*modules[:8]) elif conv_index == '54': self.vgg = nn.Sequential(*modules[:35]) vgg_mean = (0.485, 0.456, 0.406) vgg_std = (0.229 * rgb_range, 0.224 * rgb_range, 0.225 * rgb_range) self.sub_mean = common.MeanShift(rgb_range, vgg_mean, vgg_std) self.vgg.requires_grad = False def forward(self, sr, hr): def _forward(x): x = self.sub_mean(x) x = self.vgg(x) return x vgg_sr = _forward(sr) with torch.no_grad(): vgg_hr = _forward(hr.detach()) loss = F.mse_loss(vgg_sr, vgg_hr) return loss ================================================ FILE: KDSR-classic/main_anisonoise_KDSRsMx4_stage3.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=0,1,2,3 python3 main_anisonoise_stage3.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='aniso_gaussian' \ --noise=25.0 \ --lambda_min=0.2 \ --lambda_max=4.0 \ --lambda_1 4.0 \ --lambda_2 1.5 \ --theta 120 \ --n_GPUs=4 \ --epochs_encoder 0 \ --epochs_sr 500 \ --data_test Set14 \ --st_save_epoch 495 \ --data_train DF2K \ --save 'KDSRsMx4_anisonoise_stage3'\ --patch_size 64 \ --batch_size 64 \ ================================================ FILE: KDSR-classic/main_anisonoise_KDSRsMx4_stage4.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=0,1,2,3 python3 main_anisonoise_stage4.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='aniso_gaussian' \ --noise=25.0 \ --lambda_min=0.2 \ --lambda_max=4.0 \ --lambda_1 4.0 \ --lambda_2 1.5 \ --theta 120 \ --n_GPUs=4 \ --epochs_encoder 100 \ --epochs_sr 500 \ --data_test Set14 \ --st_save_epoch 495 \ --data_train DF2K \ --save 'KDSRsMx4_anisonoise_stage4'\ --pre_train_TA="./experiment/KDSRsMx4_anisonoise_stage3_x4_bicubic_aniso/model/model_TA_last.pt" \ --pre_train_ST="./experiment/KDSRsMx4_anisonoise_stage3_x4_bicubic_aniso/model/model_TA_last.pt" \ --resume 0 \ --lr_encoder 2e-4 \ --patch_size 64 \ --batch_size 64 \ ================================================ FILE: KDSR-classic/main_anisonoise_stage3.py ================================================ from option import args import torch import utility import data import model_TA import loss from trainer_anisonoise_stage3 import Trainer def count_param(model): param_count = 0 for param in model.parameters(): param_count += param.view(-1).size()[0] return param_count if __name__ == '__main__': torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if checkpoint.ok: loader = data.Data(args) model_TA = model_TA.Model(args, checkpoint) print(count_param(model_TA)) loss = loss.Loss(args, checkpoint) if not args.test_only else None t = Trainer(args, loader, model_TA, loss, checkpoint) while not t.terminate(): t.train() t.test() checkpoint.done() ================================================ FILE: KDSR-classic/main_anisonoise_stage4.py ================================================ from option import args import torch import utility import data import model_TA import model_ST import loss from trainer_anisonoise_stage4 import Trainer # def count_param(model): # param_count = 0 # for param in model.parameters(): # param_count += param.view(-1).size()[0] # return param_count if __name__ == '__main__': torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if checkpoint.ok: loader = data.Data(args) model_TA = model_TA.Model(args, checkpoint) model_ST = model_ST.Model(args, checkpoint) loss = loss.Loss(args, checkpoint) if not args.test_only else None t = Trainer(args, loader, model_ST, model_TA, loss, checkpoint) while not t.terminate(): t.train() t.test() checkpoint.done() ================================================ FILE: KDSR-classic/main_iso_KDSRsLx4_stage3.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=0,1,2,3 python3 main_iso_stage3.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='iso_gaussian' \ --noise=0 \ --sig_min=0.2 \ --sig_max=4.0 \ --sig=3.6 \ --n_GPUs=4 \ --epochs_encoder 0 \ --epochs_sr 500 \ --data_test Set14 \ --st_save_epoch 495 \ --data_train DF2K \ --save 'KDSRsLx4_iso_stage3'\ --patch_size 64 \ --batch_size 64 \ --n_feats 128 \ --n_blocks 28 \ --n_resblocks 5 ================================================ FILE: KDSR-classic/main_iso_KDSRsLx4_stage4.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=0,1,2,3 python3 main_iso_stage4.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='iso_gaussian' \ --noise=0 \ --sig_min=0.2 \ --sig_max=4.0 \ --sig=3.6 \ --n_GPUs=4 \ --epochs_encoder 0 \ --epochs_sr 600 \ --lr_decay_sr 150 \ --data_test Set14 \ --st_save_epoch 0 \ --data_train DF2K \ --save 'KDSRsLx4_iso_stage4'\ --pre_train_TA="experiment/KDSRsLx4_iso_stage3_x4_bicubic_iso/model/model_TA_last.pt" \ --pre_train_ST="experiment/KDSRsLx4_iso_stage3_x4_bicubic_iso/model/model_TA_last.pt" \ --lr_encoder 2e-4 \ --patch_size 64 \ --batch_size 64 \ --resume 0 \ --n_feats 128 \ --n_blocks 28 \ --n_resblocks 5 ================================================ FILE: KDSR-classic/main_iso_KDSRsMx4_stage3.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=4,5,6,7 python3 main_iso_stage3.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='iso_gaussian' \ --noise=0 \ --sig_min=0.2 \ --sig_max=4.0 \ --sig=3.6 \ --n_GPUs=4 \ --epochs_encoder 0 \ --epochs_sr 500 \ --data_test Set14 \ --st_save_epoch 495 \ --data_train DF2K \ --save 'KDSRsMx4_iso_stage3'\ --patch_size 64 \ --batch_size 64 \ ================================================ FILE: KDSR-classic/main_iso_KDSRsMx4_stage4.sh ================================================ ## noise-free degradations with isotropic Gaussian blurs # training knowledge distillation CUDA_VISIBLE_DEVICES=4,5,6,7 python3 main_iso_stage4.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='iso_gaussian' \ --noise=0 \ --sig_min=0.2 \ --sig_max=4.0 \ --sig=3.6 \ --n_GPUs=4 \ --epochs_encoder 0 \ --epochs_sr 600 \ --lr_decay_sr 150 \ --data_test Set14 \ --st_save_epoch 0 \ --data_train DF2K \ --save 'KDSRsMx4_iso_stage4'\ --pre_train_TA="experiment/KDSRsMx4_iso_stage3_x4_bicubic_iso/model/model_TA_last.pt" \ --pre_train_ST="experiment/KDSRsMx4_iso_stage3_x4_bicubic_iso/model/model_TA_last.pt" \ --lr_encoder 2e-4 \ --patch_size 64 \ --batch_size 64 \ --resume 0 ================================================ FILE: KDSR-classic/main_iso_stage3.py ================================================ from option import args import torch import utility import data import model_TA import loss from trainer_iso_stage3 import Trainer def count_param(model): param_count = 0 for param in model.parameters(): param_count += param.view(-1).size()[0] return param_count if __name__ == '__main__': torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if checkpoint.ok: loader = data.Data(args) model_TA = model_TA.Model(args, checkpoint) print(count_param(model_TA)) loss = loss.Loss(args, checkpoint) if not args.test_only else None t = Trainer(args, loader, model_TA, loss, checkpoint) while not t.terminate(): t.train() t.test() checkpoint.done() ================================================ FILE: KDSR-classic/main_iso_stage4.py ================================================ from option import args import torch import utility import data import model_TA import model_ST import loss from trainer_iso_stage4 import Trainer # def count_param(model): # param_count = 0 # for param in model.parameters(): # param_count += param.view(-1).size()[0] # return param_count if __name__ == '__main__': torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if checkpoint.ok: loader = data.Data(args) model_TA = model_TA.Model(args, checkpoint) model_ST = model_ST.Model(args, checkpoint) loss = loss.Loss(args, checkpoint) if not args.test_only else None t = Trainer(args, loader, model_ST, model_TA, loss, checkpoint) while not t.terminate(): t.train() t.test() checkpoint.done() ================================================ FILE: KDSR-classic/model/__init__.py ================================================ import os from importlib import import_module import torch import torch.nn as nn class Model(nn.Module): def __init__(self, args, ckp): super(Model, self).__init__() print('Making model...') self.args = args self.scale = args.scale self.idx_scale = 0 self.self_ensemble = args.self_ensemble self.chop = args.chop self.precision = args.precision self.cpu = args.cpu self.device = torch.device('cpu' if args.cpu else 'cuda') self.n_GPUs = args.n_GPUs self.save_models = args.save_models self.save = args.save module = import_module('model.'+args.model) self.model = module.make_model(args).to(self.device) if args.precision == 'half': self.model.half() if not args.cpu and args.n_GPUs > 1: self.model = nn.DataParallel(self.model, range(args.n_GPUs)) self.load( ckp.dir, pre_train=args.pre_train, resume=args.resume, cpu=args.cpu ) def forward(self, lr,lr_bic): if self.self_ensemble and not self.training: if self.chop: forward_function = self.forward_chop else: forward_function = self.model.forward return self.forward_x8(lr, forward_function) elif self.chop and not self.training: return self.forward_chop(lr) else: return self.model(lr,lr_bic) def get_model(self): if self.n_GPUs <= 1 or self.cpu: return self.model else: return self.model.module def state_dict(self, **kwargs): target = self.get_model() return target.state_dict(**kwargs) def save(self, apath, epoch, is_best=False): target = self.get_model() torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_latest.pt') ) if is_best: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_best.pt') ) if self.save_models: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_{}.pt'.format(epoch)) ) def load(self, apath, pre_train='.', resume=-1, cpu=False): if cpu: kwargs = {'map_location': lambda storage, loc: storage} else: kwargs = {} if resume == -1: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_latest.pt'), **kwargs), strict=True ) elif resume == 0: if pre_train != '.': self.get_model().load_state_dict( torch.load(pre_train, **kwargs), strict=True ) elif resume > 0: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_{}.pt'.format(resume)), **kwargs), strict=False ) def forward_chop(self, x, shave=10, min_size=160000): scale = self.scale[self.idx_scale] n_GPUs = min(self.n_GPUs, 4) b, c, h, w = x.size() h_half, w_half = h // 2, w // 2 h_size, w_size = h_half + shave, w_half + shave lr_list = [ x[:, :, 0:h_size, 0:w_size], x[:, :, 0:h_size, (w - w_size):w], x[:, :, (h - h_size):h, 0:w_size], x[:, :, (h - h_size):h, (w - w_size):w]] if w_size * h_size < min_size: sr_list = [] for i in range(0, 4, n_GPUs): lr_batch = torch.cat(lr_list[i:(i + n_GPUs)], dim=0) sr_batch = self.model(lr_batch) sr_list.extend(sr_batch.chunk(n_GPUs, dim=0)) else: sr_list = [ self.forward_chop(patch, shave=shave, min_size=min_size) \ for patch in lr_list ] h, w = scale * h, scale * w h_half, w_half = scale * h_half, scale * w_half h_size, w_size = scale * h_size, scale * w_size shave *= scale output = x.new(b, c, h, w) output[:, :, 0:h_half, 0:w_half] \ = sr_list[0][:, :, 0:h_half, 0:w_half] output[:, :, 0:h_half, w_half:w] \ = sr_list[1][:, :, 0:h_half, (w_size - w + w_half):w_size] output[:, :, h_half:h, 0:w_half] \ = sr_list[2][:, :, (h_size - h + h_half):h_size, 0:w_half] output[:, :, h_half:h, w_half:w] \ = sr_list[3][:, :, (h_size - h + h_half):h_size, (w_size - w + w_half):w_size] return output def forward_x8(self, x, forward_function): def _transform(v, op): if self.precision != 'single': v = v.float() v2np = v.data.cpu().numpy() if op == 'v': tfnp = v2np[:, :, :, ::-1].copy() elif op == 'h': tfnp = v2np[:, :, ::-1, :].copy() elif op == 't': tfnp = v2np.transpose((0, 1, 3, 2)).copy() ret = torch.Tensor(tfnp).to(self.device) if self.precision == 'half': ret = ret.half() return ret lr_list = [x] for tf in 'v', 'h', 't': lr_list.extend([_transform(t, tf) for t in lr_list]) sr_list = [forward_function(aug) for aug in lr_list] for i in range(len(sr_list)): if i > 3: sr_list[i] = _transform(sr_list[i], 't') if i % 4 > 1: sr_list[i] = _transform(sr_list[i], 'h') if (i % 4) % 2 == 1: sr_list[i] = _transform(sr_list[i], 'v') output_cat = torch.cat(sr_list, dim=0) output = output_cat.mean(dim=0, keepdim=True) return output ================================================ FILE: KDSR-classic/model/blindsr.py ================================================ import torch from torch import nn import model.common as common import torch.nn.functional as F from moco.builder import MoCo def make_model(args): return CZSR(args) class CZSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(CZSR, self).__init__() n_feats = args.n_feats kernel_size = 3 scale = args.scale[0] act = nn.LeakyReLU(0.1, True) self.head = nn.Sequential( nn.Conv2d(3, n_feats, kernel_size=3, padding=1), act ) # m_body =[ # common.ResBlock( # conv, n_feats, kernel_size, act=act, res_scale=args.res_scale), # common.ResBlock( # conv, n_feats, kernel_size, act=act, res_scale=args.res_scale), # common.ResBlock( # conv, n_feats, kernel_size, act=act, res_scale=args.res_scale), # common.ResBlock( # conv, n_feats, kernel_size, act=act, res_scale=args.res_scale), # ] m_body = [ nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act, nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act, nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act, nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act, nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act, nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1), act ] m_tail = [ common.Upsampler(conv, scale, n_feats, act=False), nn.Conv2d( n_feats, args.n_colors, kernel_size, padding=(kernel_size // 2) ) ] self.tail = nn.Sequential(*m_tail) self.body = nn.Sequential(*m_body) def forward(self, lr,lr_bic): res = self.head(lr) res = self.body(res) res = self.tail(res) res +=lr_bic return res ================================================ FILE: KDSR-classic/model/common.py ================================================ import math import torch import torch.nn as nn import torch.nn.functional as F def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class ResBlock(nn.Module): def __init__( self, conv, n_feats, kernel_size, bias=True, bn=False, act=nn.LeakyReLU(0.1, inplace=True), res_scale=1): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(conv(n_feats, n_feats, kernel_size, bias=bias)) if bn: m.append(nn.BatchNorm2d(n_feats)) if i == 0: m.append(act) self.body = nn.Sequential(*m) # self.res_scale = res_scale def forward(self, x): res = self.body(x) res += x return res class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, act=False, bias=True): m = [] if (int(scale) & (int(scale) - 1)) == 0: # Is scale = 2^n? for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, 4 * n_feat, 3, bias)) m.append(nn.PixelShuffle(2)) if act: m.append(act()) elif scale == 3: m.append(conv(n_feat, 9 * n_feat, 3, bias)) m.append(nn.PixelShuffle(3)) if act: m.append(act()) else: raise NotImplementedError super(Upsampler, self).__init__(*m) ================================================ FILE: KDSR-classic/model_ST/__init__.py ================================================ import os from importlib import import_module import torch import torch.nn as nn class Model(nn.Module): def __init__(self, args, ckp): super(Model, self).__init__() print('Making model...') self.args = args self.scale = args.scale self.idx_scale = 0 self.self_ensemble = args.self_ensemble self.chop = args.chop self.precision = args.precision self.cpu = args.cpu self.device = torch.device('cpu' if args.cpu else 'cuda') self.n_GPUs = args.n_GPUs self.save_models = args.save_models self.save = args.save module = import_module('model_ST.'+args.model) self.model = module.make_model(args).to(self.device) if args.precision == 'half': self.model.half() if not args.cpu and args.n_GPUs > 1: self.model = nn.DataParallel(self.model, range(args.n_GPUs)) self.load( ckp.dir, pre_train=args.pre_train_ST, resume=args.resume, cpu=args.cpu ) def forward(self, x): if self.self_ensemble and not self.training: if self.chop: forward_function = self.forward_chop else: forward_function = self.model.forward return self.forward_x8(x, forward_function) elif self.chop and not self.training: return self.forward_chop(x) else: return self.model(x) def get_model(self): if self.n_GPUs <= 1 or self.cpu: return self.model else: return self.model.module def state_dict(self, **kwargs): target = self.get_model() return target.state_dict(**kwargs) def save(self, apath, epoch, is_best=False): target = self.get_model() torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_ST_latest.pt') ) if is_best: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_ST_best.pt') ) if self.save_models: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_ST_{}.pt'.format(epoch)) ) def load(self, apath, pre_train='.', resume=-1, cpu=False): if cpu: kwargs = {'map_location': lambda storage, loc: storage} else: kwargs = {} if resume == -1: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_ST_latest.pt'), **kwargs), strict=True ) elif resume == 0: if pre_train != '.': self.get_model().load_state_dict( torch.load(pre_train, **kwargs), strict=False ) elif resume > 0: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_ST_{}.pt'.format(resume)), **kwargs), strict=True ) def forward_chop(self, x, shave=10, min_size=160000): scale = self.scale[self.idx_scale] n_GPUs = min(self.n_GPUs, 4) b, c, h, w = x.size() h_half, w_half = h // 2, w // 2 h_size, w_size = h_half + shave, w_half + shave lr_list = [ x[:, :, 0:h_size, 0:w_size], x[:, :, 0:h_size, (w - w_size):w], x[:, :, (h - h_size):h, 0:w_size], x[:, :, (h - h_size):h, (w - w_size):w]] if w_size * h_size < min_size: sr_list = [] for i in range(0, 4, n_GPUs): lr_batch = torch.cat(lr_list[i:(i + n_GPUs)], dim=0) sr_batch = self.model(lr_batch) sr_list.extend(sr_batch.chunk(n_GPUs, dim=0)) else: sr_list = [ self.forward_chop(patch, shave=shave, min_size=min_size) \ for patch in lr_list ] h, w = scale * h, scale * w h_half, w_half = scale * h_half, scale * w_half h_size, w_size = scale * h_size, scale * w_size shave *= scale output = x.new(b, c, h, w) output[:, :, 0:h_half, 0:w_half] \ = sr_list[0][:, :, 0:h_half, 0:w_half] output[:, :, 0:h_half, w_half:w] \ = sr_list[1][:, :, 0:h_half, (w_size - w + w_half):w_size] output[:, :, h_half:h, 0:w_half] \ = sr_list[2][:, :, (h_size - h + h_half):h_size, 0:w_half] output[:, :, h_half:h, w_half:w] \ = sr_list[3][:, :, (h_size - h + h_half):h_size, (w_size - w + w_half):w_size] return output def forward_x8(self, x, forward_function): def _transform(v, op): if self.precision != 'single': v = v.float() v2np = v.data.cpu().numpy() if op == 'v': tfnp = v2np[:, :, :, ::-1].copy() elif op == 'h': tfnp = v2np[:, :, ::-1, :].copy() elif op == 't': tfnp = v2np.transpose((0, 1, 3, 2)).copy() ret = torch.Tensor(tfnp).to(self.device) if self.precision == 'half': ret = ret.half() return ret lr_list = [x] for tf in 'v', 'h', 't': lr_list.extend([_transform(t, tf) for t in lr_list]) sr_list = [forward_function(aug) for aug in lr_list] for i in range(len(sr_list)): if i > 3: sr_list[i] = _transform(sr_list[i], 't') if i % 4 > 1: sr_list[i] = _transform(sr_list[i], 'h') if (i % 4) % 2 == 1: sr_list[i] = _transform(sr_list[i], 'v') output_cat = torch.cat(sr_list, dim=0) output = output_cat.mean(dim=0, keepdim=True) return output ================================================ FILE: KDSR-classic/model_ST/blindsr.py ================================================ import torch from torch import nn import model.common as common import torch.nn.functional as F def make_model(args): return BlindSR(args) class IDR_DDC(nn.Module): def __init__(self, channels_in, channels_out, kernel_size, reduction): super(IDR_DDC, self).__init__() self.channels_out = channels_out self.channels_in = channels_in self.kernel_size = kernel_size self.kernel = nn.Sequential( nn.Linear(channels_in, channels_in, bias=False), nn.LeakyReLU(0.1, True), nn.Linear(channels_in, channels_in * self.kernel_size * self.kernel_size, bias=False) ) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' b, c, h, w = x[0].size() # branch 1 kernel = self.kernel(x[1]).view(-1, 1, self.kernel_size, self.kernel_size) out = F.conv2d(x[0].view(1, -1, h, w), kernel, groups=b*c, padding=(self.kernel_size-1)//2) out = out.view(b, -1, h, w) return out class IDR_DCRB(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction): super(IDR_DCRB, self).__init__() self.da_conv1 = IDR_DDC(n_feat, n_feat, kernel_size, reduction) self.conv1 = conv(n_feat, n_feat, kernel_size) self.relu = nn.LeakyReLU(0.1, True) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' out = self.relu(self.da_conv1(x)) out = self.conv1(out) out = out + x[0] return out class DAG(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction, n_blocks): super(DAG, self).__init__() self.n_blocks = n_blocks modules_body = [ IDR_DCRB(conv, n_feat, kernel_size, reduction) \ for _ in range(n_blocks) ] # modules_body.append(conv(n_feat, n_feat, kernel_size)) self.body = nn.Sequential(*modules_body) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' res = x[0] for i in range(self.n_blocks): res = self.body[i]([res, x[1]]) return res class KDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(KDSR, self).__init__() n_blocks = args.n_blocks n_feats = args.n_feats kernel_size = 3 reduction = 8 scale = int(args.scale[0]) # RGB mean for DIV2K rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std) self.add_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std, 1) # head module modules_head = [conv(3, n_feats, kernel_size)] self.head = nn.Sequential(*modules_head) # body modules_body = [ DAG(common.default_conv, n_feats, kernel_size, reduction, n_blocks) ] modules_body.append(conv(n_feats, n_feats, kernel_size)) self.body = nn.Sequential(*modules_body) # tail modules_tail = [common.Upsampler(conv, scale, n_feats, act=False), conv(n_feats, 3, kernel_size)] self.tail = nn.Sequential(*modules_tail) def forward(self, x, k_v): # sub mean x = self.sub_mean(x) # head x = self.head(x) # body res = x res = self.body[0]([res, k_v]) res = self.body[-1](res) res = res + x # tail x = self.tail(res) # add mean x = self.add_mean(x) return x class KD_IDE(nn.Module): def __init__(self,args): super(KD_IDE, self).__init__() n_feats = args.n_feats n_resblocks = args.n_resblocks E1=[nn.Conv2d(3, n_feats, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True)] E2=[ common.ResBlock( common.default_conv, n_feats, kernel_size=3 ) for _ in range(n_resblocks) ] E3=[ nn.Conv2d(n_feats, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 4, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.AdaptiveAvgPool2d(1), ] E=E1+E2+E3 self.E = nn.Sequential( *E ) self.mlp = nn.Sequential( nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True), nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True) ) # compress self.compress = nn.Sequential( nn.Linear(n_feats * 4, n_feats), nn.LeakyReLU(0.1, True) ) def forward(self, x): fea = self.E(x).squeeze(-1).squeeze(-1) S_fea = [] # for i in range(len(self.mlp)): # fea = self.mlp[i](fea) # if i==2: # T_fea.append(fea) fea1 = self.mlp(fea) fea = self.compress(fea1) S_fea.append(fea1) return fea,S_fea class BlindSR(nn.Module): def __init__(self, args): super(BlindSR, self).__init__() # Generator self.G = KDSR(args) self.E_st = KD_IDE(args) def forward(self, x): if self.training: # degradation-aware represenetion learning deg_repre, S_fea = self.E_st(x) # degradation-aware SR sr = self.G(x, deg_repre) return sr, S_fea else: # degradation-aware represenetion learning deg_repre, _ = self.E_st(x) # degradation-aware SR sr = self.G(x, deg_repre) return sr ================================================ FILE: KDSR-classic/model_ST/common.py ================================================ import math import torch import torch.nn as nn import torch.nn.functional as F def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, act=False, bias=True): m = [] if (scale & (scale - 1)) == 0: # Is scale = 2^n? for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, 4 * n_feat, 3, bias)) m.append(nn.PixelShuffle(2)) if act: m.append(act()) elif scale == 3: m.append(conv(n_feat, 9 * n_feat, 3, bias)) m.append(nn.PixelShuffle(3)) if act: m.append(act()) else: raise NotImplementedError super(Upsampler, self).__init__(*m) ================================================ FILE: KDSR-classic/model_TA/__init__.py ================================================ import os from importlib import import_module import torch import torch.nn as nn class Model(nn.Module): def __init__(self, args, ckp): super(Model, self).__init__() print('Making model...') self.args = args self.scale = args.scale self.idx_scale = 0 self.self_ensemble = args.self_ensemble self.chop = args.chop self.precision = args.precision self.cpu = args.cpu self.device = torch.device('cpu' if args.cpu else 'cuda') self.n_GPUs = args.n_GPUs self.save_models = args.save_models self.save = args.save module = import_module('model_TA.'+args.model) self.model = module.make_model(args).to(self.device) if args.precision == 'half': self.model.half() if not args.cpu and args.n_GPUs > 1: self.model = nn.DataParallel(self.model, range(args.n_GPUs)) self.load( ckp.dir, pre_train=args.pre_train_TA, resume=args.resume, cpu=args.cpu ) def forward(self, x, deg_repre): if self.self_ensemble and not self.training: if self.chop: forward_function = self.forward_chop else: forward_function = self.model.forward return self.forward_x8(x, forward_function) elif self.chop and not self.training: return self.forward_chop(x, deg_repre) else: return self.model(x, deg_repre) def get_model(self): if self.n_GPUs <= 1 or self.cpu: return self.model else: return self.model.module def state_dict(self, **kwargs): target = self.get_model() return target.state_dict(**kwargs) def save(self, apath, epoch, is_best=False): target = self.get_model() torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_latest.pt') ) if is_best: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_best.pt') ) if self.save_models: torch.save( target.state_dict(), os.path.join(apath, 'model', 'model_{}.pt'.format(epoch)) ) def load(self, apath, pre_train='.', resume=-1, cpu=False): if cpu: kwargs = {'map_location': lambda storage, loc: storage} else: kwargs = {} if resume == -1: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_latest.pt'), **kwargs), strict=True ) elif resume == 0: if pre_train != '.': self.get_model().load_state_dict( torch.load(pre_train, **kwargs), strict=True ) elif resume > 0: self.get_model().load_state_dict( torch.load(os.path.join(apath, 'model', 'model_{}.pt'.format(resume)), **kwargs), strict=False ) def forward_chop(self, x, deg_repre, shave=10, min_size=160000): scale = self.scale[self.idx_scale] n_GPUs = min(self.n_GPUs, 4) b, c, h, w = x.size() h_half, w_half = h // 2, w // 2 h_size, w_size = h_half + shave, w_half + shave lr_list = [ x[:, :, 0:h_size, 0:w_size], x[:, :, 0:h_size, (w - w_size):w], x[:, :, (h - h_size):h, 0:w_size], x[:, :, (h - h_size):h, (w - w_size):w]] shave4=int(shave*scale) b, c4, h4, w4 = deg_repre.size() h4_half, w4_half = h4 // 2, w4 // 2 h4_size, w4_size = h4_half + shave4, w4_half + shave4 repre_list = [ deg_repre[:, :, 0:h4_size, 0:w4_size], deg_repre[:, :, 0:h4_size, (w4 - w4_size):w4], deg_repre[:, :, (h4 - h4_size):h4, 0:w4_size], deg_repre[:, :, (h4 - h4_size):h4, (w4 - w4_size):w4]] if w_size * h_size < min_size: sr_list = [] for i in range(0, 4, n_GPUs): lr_batch = torch.cat(lr_list[i:(i + n_GPUs)], dim=0) repre_batch = torch.cat(repre_list[i:(i + n_GPUs)], dim=0) sr_batch = self.model(lr_batch,repre_batch) sr_list.extend(sr_batch.chunk(n_GPUs, dim=0)) else: sr_list = [ self.forward_chop(lr_patch, repre_patch, shave=shave, min_size=min_size) \ for lr_patch, repre_patch in zip(lr_list,repre_list) ] h, w = scale * h, scale * w h_half, w_half = scale * h_half, scale * w_half h_size, w_size = scale * h_size, scale * w_size shave *= scale output = x.new(b, c, h, w) output[:, :, 0:h_half, 0:w_half] \ = sr_list[0][:, :, 0:h_half, 0:w_half] output[:, :, 0:h_half, w_half:w] \ = sr_list[1][:, :, 0:h_half, (w_size - w + w_half):w_size] output[:, :, h_half:h, 0:w_half] \ = sr_list[2][:, :, (h_size - h + h_half):h_size, 0:w_half] output[:, :, h_half:h, w_half:w] \ = sr_list[3][:, :, (h_size - h + h_half):h_size, (w_size - w + w_half):w_size] return output def forward_x8(self, x, forward_function): def _transform(v, op): if self.precision != 'single': v = v.float() v2np = v.data.cpu().numpy() if op == 'v': tfnp = v2np[:, :, :, ::-1].copy() elif op == 'h': tfnp = v2np[:, :, ::-1, :].copy() elif op == 't': tfnp = v2np.transpose((0, 1, 3, 2)).copy() ret = torch.Tensor(tfnp).to(self.device) if self.precision == 'half': ret = ret.half() return ret lr_list = [x] for tf in 'v', 'h', 't': lr_list.extend([_transform(t, tf) for t in lr_list]) sr_list = [forward_function(aug) for aug in lr_list] for i in range(len(sr_list)): if i > 3: sr_list[i] = _transform(sr_list[i], 't') if i % 4 > 1: sr_list[i] = _transform(sr_list[i], 'h') if (i % 4) % 2 == 1: sr_list[i] = _transform(sr_list[i], 'v') output_cat = torch.cat(sr_list, dim=0) output = output_cat.mean(dim=0, keepdim=True) return output ================================================ FILE: KDSR-classic/model_TA/blindsr.py ================================================ import torch from torch import nn import model.common as common import torch.nn.functional as F def make_model(args): return BlindSR(args) class IDR_DDC(nn.Module): def __init__(self, channels_in, channels_out, kernel_size, reduction): super(IDR_DDC, self).__init__() self.channels_out = channels_out self.channels_in = channels_in self.kernel_size = kernel_size self.kernel = nn.Sequential( nn.Linear(channels_in, channels_in, bias=False), nn.LeakyReLU(0.1, True), nn.Linear(channels_in, channels_in * self.kernel_size * self.kernel_size, bias=False) ) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' b, c, h, w = x[0].size() # branch 1 kernel = self.kernel(x[1]).view(-1, 1, self.kernel_size, self.kernel_size) out = F.conv2d(x[0].view(1, -1, h, w), kernel, groups=b*c, padding=(self.kernel_size-1)//2) out = out.view(b, -1, h, w) return out class IDR_DCRB(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction): super(IDR_DCRB, self).__init__() self.da_conv1 = IDR_DDC(n_feat, n_feat, kernel_size, reduction) self.conv1 = conv(n_feat, n_feat, kernel_size) self.relu = nn.LeakyReLU(0.1, True) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' out = self.relu(self.da_conv1(x)) out = self.conv1(out) out = out + x[0] return out class DAG(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction, n_blocks): super(DAG, self).__init__() self.n_blocks = n_blocks modules_body = [ IDR_DCRB(conv, n_feat, kernel_size, reduction) \ for _ in range(n_blocks) ] # modules_body.append(conv(n_feat, n_feat, kernel_size)) self.body = nn.Sequential(*modules_body) def forward(self, x): ''' :param x[0]: feature map: B * C * H * W :param x[1]: degradation representation: B * C ''' res = x[0] for i in range(self.n_blocks): res = self.body[i]([res, x[1]]) return res class KDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(KDSR, self).__init__() n_blocks = args.n_blocks n_feats = args.n_feats kernel_size = 3 reduction = 8 scale = int(args.scale[0]) # RGB mean for DIV2K rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std) self.add_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std, 1) # head module modules_head = [conv(3, n_feats, kernel_size)] self.head = nn.Sequential(*modules_head) # body modules_body = [ DAG(common.default_conv, n_feats, kernel_size, reduction, n_blocks) ] modules_body.append(conv(n_feats, n_feats, kernel_size)) self.body = nn.Sequential(*modules_body) # tail modules_tail = [common.Upsampler(conv, scale, n_feats, act=False), conv(n_feats, 3, kernel_size)] self.tail = nn.Sequential(*modules_tail) def forward(self, x, k_v): # sub mean x = self.sub_mean(x) # head x = self.head(x) # body res = x res = self.body[0]([res, k_v]) res = self.body[-1](res) res = res + x # tail x = self.tail(res) # add mean x = self.add_mean(x) return x class KD_IDE(nn.Module): def __init__(self,args): super(KD_IDE, self).__init__() n_feats = args.n_feats n_resblocks = args.n_resblocks scale = int(args.scale[0]) E1=[nn.Conv2d(3+scale*scale*3, n_feats, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True)] E2=[ common.ResBlock( common.default_conv, n_feats, kernel_size=3 ) for _ in range(n_resblocks) ] E3=[ nn.Conv2d(n_feats, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 2, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.Conv2d(n_feats * 2, n_feats * 4, kernel_size=3, padding=1), nn.LeakyReLU(0.1, True), nn.AdaptiveAvgPool2d(1), ] E=E1+E2+E3 self.E = nn.Sequential( *E ) self.mlp = nn.Sequential( nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True), nn.Linear(n_feats * 4, n_feats * 4), nn.LeakyReLU(0.1, True) ) # compress self.compress = nn.Sequential( nn.Linear(n_feats * 4, n_feats), nn.LeakyReLU(0.1, True) ) def forward(self, x): fea = self.E(x).squeeze(-1).squeeze(-1) T_fea = [] fea1 = self.mlp(fea) fea = self.compress(fea1) T_fea.append(fea1) return fea,T_fea class BlindSR(nn.Module): def __init__(self, args): super(BlindSR, self).__init__() # Generator self.G = KDSR(args) self.E = KD_IDE(args) def forward(self, x, deg_repre): if self.training: # degradation-aware represenetion learning deg_repre, T_fea = self.E(deg_repre) # degradation-aware SR sr = self.G(x, deg_repre) return sr, T_fea else: # degradation-aware represenetion learning deg_repre, _ = self.E(deg_repre) # degradation-aware SR sr = self.G(x, deg_repre) return sr ================================================ FILE: KDSR-classic/model_TA/common.py ================================================ import math import torch import torch.nn as nn import torch.nn.functional as F def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) self.bias.data.div_(std) self.weight.requires_grad = False self.bias.requires_grad = False class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, act=False, bias=True): m = [] if (scale & (scale - 1)) == 0: # Is scale = 2^n? for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, 4 * n_feat, 3, bias)) m.append(nn.PixelShuffle(2)) if act: m.append(act()) elif scale == 3: m.append(conv(n_feat, 9 * n_feat, 3, bias)) m.append(nn.PixelShuffle(3)) if act: m.append(act()) else: raise NotImplementedError super(Upsampler, self).__init__(*m) ================================================ FILE: KDSR-classic/option.py ================================================ import argparse import template parser = argparse.ArgumentParser(description='EDSR and MDSR') parser.add_argument('--debug', action='store_true', help='Enables debug mode') parser.add_argument('--template', default='.', help='You can set various templates in option.py') # Hardware specifications parser.add_argument('--n_threads', type=int, default=4, help='number of threads for data loading') parser.add_argument('--cpu', type=bool, default=False, help='use cpu only') parser.add_argument('--n_GPUs', type=int, default=2, help='number of GPUs') parser.add_argument('--seed', type=int, default=1, help='random seed') parser.add_argument('--pre_train_meta', type=str, default= '.', help='pre-trained model directory') parser.add_argument('--pre_train_TA', type=str, default= '.', help='pre-trained model directory') parser.add_argument('--pre_train_ST', type=str, default= '.', help='pre-trained model directory') parser.add_argument('--is_stage3', action='store_true', help='set this option to test the model') parser.add_argument('--temperature', type=float, default=0.15, help='for konwledge distillation') # Meta-Learning parser.add_argument('--task_iter', type=int, default=20, help='each task iteration times') parser.add_argument('--test_iter', type=int, default=20, help='each task iteration times') parser.add_argument('--meta_batch_size', type=int, default=8, help='each task iteration times') parser.add_argument('--task_batch_size', type=int, default=16, help='each task iteration times') parser.add_argument('--lr_task', type=float, default=1e-3, help='learning rate to train the whole network') # Data specifications parser.add_argument('--dir_data', type=str, default='D:/LongguangWang/Data', help='dataset directory') parser.add_argument('--dir_demo', type=str, default='../test', help='demo image directory') parser.add_argument('--data_train', type=str, default='DF2K', help='train dataset name') parser.add_argument('--data_test', type=str, default='Set5', help='test dataset name') parser.add_argument('--data_range', type=str, default='1-3450/801-810', help='train/test data range') parser.add_argument('--ext', type=str, default='sep', help='dataset file extension') parser.add_argument('--scale', type=str, default='4', help='super resolution scale') parser.add_argument('--patch_size', type=int, default=36, help='output patch size') parser.add_argument('--rgb_range', type=int, default=1, help='maximum value of RGB') parser.add_argument('--n_colors', type=int, default=3, help='number of color channels to use') parser.add_argument('--chop', action='store_true', help='enable memory-efficient forward') parser.add_argument('--no_augment', action='store_true', help='do not use data augmentation') # Degradation specifications parser.add_argument('--blur_kernel', type=int, default=21, help='size of blur kernels') parser.add_argument('--blur_type', type=str, default='iso_gaussian', help='blur types (iso_gaussian | aniso_gaussian)') parser.add_argument('--mode', type=str, default='bicubic', help='downsampler (bicubic | s-fold)') parser.add_argument('--noise', type=float, default=0.0, help='noise level') ## isotropic Gaussian blur parser.add_argument('--sig_min', type=float, default=0.2, help='minimum sigma of isotropic Gaussian blurs') parser.add_argument('--sig_max', type=float, default=4.0, help='maximum sigma of isotropic Gaussian blurs') parser.add_argument('--sig', type=float, default=4.0, help='specific sigma of isotropic Gaussian blurs') ## anisotropic Gaussian blur parser.add_argument('--lambda_min', type=float, default=0.2, help='minimum value for the eigenvalue of anisotropic Gaussian blurs') parser.add_argument('--lambda_max', type=float, default=4.0, help='maximum value for the eigenvalue of anisotropic Gaussian blurs') parser.add_argument('--lambda_1', type=float, default=0.2, help='one eigenvalue of anisotropic Gaussian blurs') parser.add_argument('--lambda_2', type=float, default=4.0, help='another eigenvalue of anisotropic Gaussian blurs') parser.add_argument('--theta', type=float, default=0.0, help='rotation angle of anisotropic Gaussian blurs [0, 180]') # Model specifications parser.add_argument('--model', default='blindsr', help='model name') parser.add_argument('--pre_train', type=str, default= '.', help='pre-trained model directory') parser.add_argument('--extend', type=str, default='.', help='pre-trained model directory') parser.add_argument('--shift_mean', default=True, help='subtract pixel mean from the input') parser.add_argument('--dilation', action='store_true', help='use dilated convolution') parser.add_argument('--precision', type=str, default='single', choices=('single', 'half'), help='FP precision for test (single | half)') parser.add_argument('--n_resblocks', type=int, default=9, help='number of residual blocks') parser.add_argument('--n_feats', type=int, default=64, help='number of feature maps') parser.add_argument('--res_scale', type=float, default=1, help='residual scaling') parser.add_argument('--n_blocks', type=int, default=53, help='number of blocks in KDSR') # Training specifications parser.add_argument('--reset', action='store_true', help='reset the training') parser.add_argument('--test_every', type=int, default=1000, help='do test per every N batches') parser.add_argument('--epochs_encoder', type=int, default=100, help='number of epochs to train the degradation encoder') parser.add_argument('--epochs_sr', type=int, default=500, help='number of epochs to train the whole network') parser.add_argument('--st_save_epoch', type=int, default=550, help='number of epochs to save network') parser.add_argument('--batch_size', type=int, default=32, help='input batch size for training') parser.add_argument('--split_batch', type=int, default=1, help='split the batch into smaller chunks') parser.add_argument('--self_ensemble', action='store_true', help='use self-ensemble method for test') parser.add_argument('--test_only', action='store_true', help='set this option to test the model') # Optimization specifications parser.add_argument('--lr_encoder', type=float, default=1e-3, help='learning rate to train the degradation encoder') parser.add_argument('--lr_sr', type=float, default=1e-4, help='learning rate to train the whole network') parser.add_argument('--lr_decay_encoder', type=int, default=60, help='learning rate decay per N epochs') parser.add_argument('--lr_decay_sr', type=int, default=125, help='learning rate decay per N epochs') parser.add_argument('--decay_type', type=str, default='step', help='learning rate decay type') parser.add_argument('--gamma_encoder', type=float, default=0.1, help='learning rate decay factor for step decay') parser.add_argument('--gamma_sr', type=float, default=0.5, help='learning rate decay factor for step decay') parser.add_argument('--optimizer', default='ADAM', choices=('SGD', 'ADAM', 'RMSprop'), help='optimizer to use (SGD | ADAM | RMSprop)') parser.add_argument('--momentum', type=float, default=0.9, help='SGD momentum') parser.add_argument('--beta1', type=float, default=0.9, help='ADAM beta1') parser.add_argument('--beta2', type=float, default=0.999, help='ADAM beta2') parser.add_argument('--epsilon', type=float, default=1e-8, help='ADAM epsilon for numerical stability') parser.add_argument('--weight_decay', type=float, default=0, help='weight decay') parser.add_argument('--start_epoch', type=int, default=0, help='resume from the snapshot, and the start_epoch') # Loss specifications parser.add_argument('--loss', type=str, default='1*L1', help='loss function configuration') parser.add_argument('--skip_threshold', type=float, default='1e6', help='skipping batch that has large error') # Log specifications parser.add_argument('--save', type=str, default='blindsr', help='file name to save') parser.add_argument('--load', type=str, default='.', help='file name to load') parser.add_argument('--resume', type=int, default=0, help='resume from specific checkpoint') parser.add_argument('--save_models', action='store_true', help='save all intermediate models') parser.add_argument('--print_every', type=int, default=200, help='how many batches to wait before logging training status') parser.add_argument('--save_results', default=False, help='save output results') args = parser.parse_args() template.set_template(args) args.scale = list(map(lambda x: int(x), args.scale.split('+'))) args.data_train = args.data_train.split('+') args.data_test = args.data_test.split('+') for arg in vars(args): if vars(args)[arg] == 'True': vars(args)[arg] = True elif vars(args)[arg] == 'False': vars(args)[arg] = False ================================================ FILE: KDSR-classic/template.py ================================================ def set_template(args): # Set the templates here if args.template.find('jpeg') >= 0: args.data_train = 'DIV2K_jpeg' args.data_test = 'DIV2K_jpeg' args.epochs = 200 args.lr_decay = 100 if args.template.find('EDSR_paper') >= 0: args.model = 'EDSR' args.n_resblocks = 32 args.n_feats = 256 args.res_scale = 0.1 if args.template.find('MDSR') >= 0: args.model = 'MDSR' args.patch_size = 48 args.epochs = 650 if args.template.find('DDBPN') >= 0: args.model = 'DDBPN' args.patch_size = 128 args.scale = '4' args.data_test = 'Set5' args.batch_size = 20 args.epochs = 1000 args.lr_decay = 500 args.gamma = 0.1 args.weight_decay = 1e-4 args.loss = '1*MSE' if args.template.find('GAN') >= 0: args.epochs = 200 args.lr = 5e-5 args.lr_decay = 150 if args.template.find('RCAN') >= 0: args.model = 'RCAN' args.n_resgroups = 10 args.n_resblocks = 20 args.n_feats = 64 args.chop = True ================================================ FILE: KDSR-classic/test.py ================================================ from option import args import torch import utility import data import model import loss from trainer import Trainer if __name__ == '__main__': torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if checkpoint.ok: loader = data.Data(args) model = model.Model(args, checkpoint) loss = loss.Loss(args, checkpoint) if not args.test_only else None t = Trainer(args, loader, model, loss, checkpoint) while not t.terminate(): t.test() checkpoint.done() ================================================ FILE: KDSR-classic/test_anisonoise_KDSRsMx4.sh ================================================ CUDA_VISIBLE_DEVICES=4 python3 main_anisonoise_stage4.py --dir_data='/root/datasets' \ --model='blindsr' \ --scale='4' \ --blur_type='aniso_gaussian' \ --lambda_1 3.5 \ --lambda_2 1.5 \ --theta 30 \ --n_GPUs=1 \ --data_test Set14 \ --save 'KDSRsM_anisonoise_test'\ --pre_train_ST="./experiment/KDSRsM_anisonoise_x4.pt" \ --resume 0 \ --test_only \ --save_results False ================================================ FILE: KDSR-classic/test_iso_KDSRsLx4.sh ================================================ CUDA_VISIBLE_DEVICES=4 python3 main_iso_stage4.py --test_only \ --dir_data='/root/datasets' \ --data_test='Set5+Set14+B100+Urban100+MANGA109' \ --model='blindsr' \ --scale='4' \ --resume=0 \ --pre_train_ST 'experiment/KDSRsL_iso_x4.pt' \ --n_GPUs=1 \ --save 'KDSRsL_iso_test'\ --blur_type='iso_gaussian' \ --noise 0 \ --save_results False \ --n_feats 128 \ --n_blocks 28 \ --n_resblocks 5 ================================================ FILE: KDSR-classic/test_iso_KDSRsMx4.sh ================================================ CUDA_VISIBLE_DEVICES=4 python3 main_iso_stage4.py --test_only \ --dir_data='/root/datasets' \ --data_test='Set5+Set14+B100+Urban100+MANGA109' \ --model='blindsr' \ --scale='4' \ --resume=0 \ --pre_train_ST 'experiment/KDSRsM_iso_x4.pt' \ --n_GPUs=1 \ --save 'KDSRsM_iso_test'\ --blur_type='iso_gaussian' \ --noise 0 \ --save_results False \ ================================================ FILE: KDSR-classic/trainer_anisonoise_stage3.py ================================================ import os import utility2 import torch from decimal import Decimal import torch.nn.functional as F from utils import util from utils import util2 from collections import OrderedDict import random import numpy as np import torch.nn as nn import utility3 class Trainer(): def __init__(self, args, loader, model_TA, my_loss, ckp): self.test_res_psnr = [] self.test_res_ssim = [] self.args = args self.scale = args.scale self.loss1= nn.L1Loss() self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model_TA = model_TA self.loss = my_loss self.optimizer = utility2.make_optimizer(args, self.model_TA) self.scheduler = utility2.make_scheduler(args, self.optimizer) self.pixel_unshuffle = nn.PixelUnshuffle(self.scale[0]) if self.args.load != '.': self.optimizer.load_state_dict( torch.load(os.path.join(ckp.dir, 'optimizer.pt')) ) for _ in range(len(ckp.log)): self.scheduler.step() def train(self): self.scheduler.step() self.loss.step() epoch = self.scheduler.last_epoch + 1 lr = self.args.lr_sr * (self.args.gamma_sr ** ((epoch - self.args.epochs_encoder) // self.args.lr_decay_sr)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr self.ckp.write_log('[Epoch {}]\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))) self.loss.start_log() self.model_TA.train() degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig_min=self.args.sig_min, sig_max=self.args.sig_max, lambda_min=self.args.lambda_min, lambda_max=self.args.lambda_max, noise=self.args.noise ) timer = utility2.timer() for batch, ( hr, _,) in enumerate(self.loader_train): hr = hr.cuda() # b, c, h, w timer.tic() loss_all = 0 lr_blur, hr_blur = degrade(hr) # b, c, h, w hr2 = self.pixel_unshuffle(hr) sr, _ = self.model_TA(lr_blur, torch.cat([lr_blur,hr2], dim=1)) # sr,_ = self.model_TA(lr_blur, torch.cat([hr_blur,hr],dim=1)) loss_all += self.loss1(sr,hr) self.optimizer.zero_grad() loss_all.backward() self.optimizer.step() # Remove the hooks before next training phase timer.hold() if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [SR loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), loss_all.item(), timer.release(), )) self.loss.end_log(len(self.loader_train)) # save model if epoch > self.args.st_save_epoch or (epoch %20 ==0): target = self.model_TA.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_TA_{}.pt'.format(epoch)) ) optimzer_dict = self.optimizer.state_dict() torch.save( optimzer_dict, os.path.join(self.ckp.dir, 'optimzer', 'optimzer_TA_{}.pt'.format(epoch)) ) target = self.model_TA.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_TA_last.pt') ) optimzer_dict = self.optimizer.state_dict() torch.save( optimzer_dict, os.path.join(self.ckp.dir, 'optimzer', 'optimzer_TA_last.pt') ) def test(self): self.ckp.write_log('\nEvaluation:') self.ckp.add_log(torch.zeros(1, len(self.scale))) timer_test = utility2.timer() self.model_TA.eval() degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig=self.args.sig, lambda_1=self.args.lambda_1, lambda_2=self.args.lambda_2, theta=self.args.theta, noise=10 ) for idx_data, d in enumerate(self.loader_test): for idx_scale, scale in enumerate(self.scale): d.dataset.set_scale(idx_scale) eval_psnr = 0 eval_ssim = 0 for idx, (hr, filename) in enumerate(d): hr = hr.cuda() # b, c, h, w hr = self.crop_border(hr, scale) # inference timer_test.tic() lr_blur, hr_blur = degrade(hr, random=False) hr2 = self.pixel_unshuffle(hr) sr = self.model_TA(lr_blur, torch.cat([lr_blur, hr2], dim=1)) # sr = self.model_TA(lr_blur, torch.cat([hr_blur,hr],dim=1)) timer_test.hold() sr = utility2.quantize(sr, self.args.rgb_range) hr = utility2.quantize(hr, self.args.rgb_range) # metrics eval_psnr += utility2.calc_psnr( sr, hr, scale, self.args.rgb_range, benchmark=d.dataset.benchmark ) # eval_psnr += utility3.calc_psnr( # sr, hr, scale # ) eval_ssim += utility2.calc_ssim( (sr*255).round().clamp(0,255), (hr*255).round().clamp(0,255),scale, benchmark=d.dataset.benchmark ) # save results if self.args.save_results: save_list = [sr] filename = filename[0] self.ckp.save_results(filename, save_list, scale) if len(self.test_res_psnr)>10: self.test_res_psnr.pop(0) self.test_res_ssim.pop(0) self.test_res_psnr.append(eval_psnr / len(d)) self.test_res_ssim.append(eval_ssim / len(d)) self.ckp.log[-1, idx_scale] = eval_psnr / len(d) self.ckp.write_log( '[Epoch {}---{} x{}]\tPSNR: {:.3f} SSIM: {:.4f} mean_PSNR: {:.3f} mean_SSIM: {:.4f}'.format( self.args.resume, self.args.data_test, scale, eval_psnr / len(d), eval_ssim / len(d), np.mean(self.test_res_psnr), np.mean(self.test_res_ssim) )) def crop_border(self, img_hr, scale): b, c, h, w = img_hr.size() img_hr = img_hr[:, :, :int(h//scale*scale), :int(w//scale*scale)] return img_hr def get_patch(self, img, patch_size=48, scale=4): tb, tc, th, tw = img.shape ## HR image tp = round(scale * patch_size) tx = random.randrange(0, (tw - tp)) ty = random.randrange(0, (th - tp)) return img[:,:,ty:ty + tp, tx:tx + tp] def crop(self, img_hr): # b, c, h, w = img_hr.size() tp_hr = [] for i in range(self.task_batch_size): tp_hr.append(self.get_patch(img_hr,self.args.patch_size,self.scale[0])) tp_hr = torch.cat(tp_hr,dim=0) return tp_hr def terminate(self): if self.args.test_only: self.test() return True else: epoch = self.scheduler.last_epoch + 1 return epoch >= self.args.epochs_sr ================================================ FILE: KDSR-classic/trainer_anisonoise_stage4.py ================================================ import os import utility import torch from decimal import Decimal import torch.nn.functional as F from utils import util2 import numpy as np import torch.nn as nn class Trainer(): def __init__(self, args, loader, model_ST, model_TA, my_loss, ckp): self.is_first =True self.args = args self.scale = args.scale self.test_res_psnr = [] self.test_res_ssim = [] self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model_ST = model_ST self.model_TA = model_TA self.model_Est = torch.nn.DataParallel(self.model_ST.get_model().E_st, range(self.args.n_GPUs)) self.model_Eta = torch.nn.DataParallel(self.model_TA.get_model().E, range(self.args.n_GPUs)) self.loss1 = nn.L1Loss() self.loss = my_loss self.optimizer = utility.make_optimizer(args, self.model_ST) self.scheduler = utility.make_scheduler(args, self.optimizer) self.temperature = args.temperature self.pixel_unshuffle = nn.PixelUnshuffle(self.scale[0]) if self.args.load != '.': self.optimizer.load_state_dict( torch.load(os.path.join(ckp.dir, 'optimizer.pt')) ) for _ in range(len(ckp.log)): self.scheduler.step() def train(self): self.scheduler.step() self.loss.step() epoch = self.scheduler.last_epoch + 1 if epoch <= self.args.epochs_encoder: lr = self.args.lr_encoder * (self.args.gamma_encoder ** (epoch // self.args.lr_decay_encoder)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr else: lr = self.args.lr_sr * (self.args.gamma_sr ** ((epoch - self.args.epochs_encoder) // self.args.lr_decay_sr)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr self.ckp.write_log('[Epoch {}]\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))) self.loss.start_log() self.model_ST.train() degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig_min=self.args.sig_min, sig_max=self.args.sig_max, lambda_min=self.args.lambda_min, lambda_max=self.args.lambda_max, noise=self.args.noise ) timer = utility.timer() losses_sr, losses_distill_distribution, losses_distill_abs = utility.AverageMeter(),utility.AverageMeter(),utility.AverageMeter() for batch, (hr, _,) in enumerate(self.loader_train): hr = hr.cuda() # b, c, h, w timer.tic() lr_blur, hr_blur = degrade(hr) # b, c, h, w hr2 = self.pixel_unshuffle(hr) _, T_fea = self.model_Eta(torch.cat([lr_blur,hr2],dim=1)) loss_distill_dis = 0 loss_distill_abs = 0 if epoch <= self.args.epochs_encoder: _, S_fea = self.model_Est(lr_blur) for i in range(len(T_fea)): student_distance = F.log_softmax(S_fea[i] / self.temperature, dim=1) teacher_distance = F.softmax(T_fea[i].detach()/ self.temperature, dim=1) loss_distill_dis += F.kl_div( student_distance, teacher_distance, reduction='batchmean') loss_distill_abs += nn.L1Loss()(S_fea[i], T_fea[i].detach()) losses_distill_distribution.update(loss_distill_dis.item()) #losses_distill_distribution.update(loss_distill_dis) losses_distill_abs.update(loss_distill_abs.item()) loss = loss_distill_dis #+ 0.1* loss_distill_abs else: sr, S_fea = self.model_ST(lr_blur) loss_SR = self.loss(sr, hr) for i in range(len(T_fea)): student_distance = F.log_softmax(S_fea[i] / self.temperature, dim=1) teacher_distance = F.softmax(T_fea[i].detach() / self.temperature, dim=1) loss_distill_dis += F.kl_div( student_distance, teacher_distance, reduction='batchmean') loss_distill_abs += nn.L1Loss()(S_fea[i], T_fea[i].detach()) losses_distill_distribution.update(loss_distill_dis.item()) #losses_distill_distribution.update(loss_distill_dis) losses_distill_abs.update(loss_distill_abs.item()) loss = loss_SR + loss_distill_dis #+ 0.1* loss_distill_abs losses_sr.update(loss_SR.item()) # backward self.optimizer.zero_grad() loss.backward() self.optimizer.step() timer.hold() if epoch <= self.args.epochs_encoder: if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [ distill_dis loss:{:.3f}, distill_abs loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), losses_distill_distribution.avg, losses_distill_abs.avg, timer.release(), )) else: if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [SR loss:{:.3f}, distill_dis loss:{:.3f}, distill_abs loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), losses_sr.avg, losses_distill_distribution.avg, losses_distill_abs.avg, timer.release(), )) self.loss.end_log(len(self.loader_train)) # save model if epoch > self.args.st_save_epoch or epoch%30==0: target = self.model_ST.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_ST_{}.pt'.format(epoch)) ) target = self.model_ST.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_ST_last.pt') ) def test(self): self.ckp.write_log('\nEvaluation:') self.ckp.add_log(torch.zeros(1, len(self.scale))) self.model_ST.eval() timer_test = utility.timer() with torch.no_grad(): degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig=self.args.sig, lambda_1=self.args.lambda_1, lambda_2=self.args.lambda_2, theta=self.args.theta, noise=10 ) for idx_data, d in enumerate(self.loader_test): for idx_scale, scale in enumerate(self.scale): d.dataset.set_scale(idx_scale) eval_psnr = 0 eval_ssim = 0 for idx, (hr, filename) in enumerate(d): hr = hr.cuda() # b, c, h, w hr = self.crop_border(hr, scale) lr_blur, hr_blur = degrade(hr, random=False) # b, c, h, w # inference timer_test.tic() sr = self.model_ST(lr_blur) timer_test.hold() sr = utility.quantize(sr, self.args.rgb_range) hr = utility.quantize(hr, self.args.rgb_range) # metrics eval_psnr += utility.calc_psnr( sr, hr, scale, self.args.rgb_range, benchmark=d.dataset.benchmark ) eval_ssim += utility.calc_ssim( (sr * 255).round().clamp(0, 255), (hr * 255).round().clamp(0, 255), scale, benchmark=d.dataset.benchmark ) # save results if self.args.save_results: save_list = [sr] filename = filename[0] self.ckp.save_results(filename, save_list, scale) if len(self.test_res_psnr) > 10: self.test_res_psnr.pop(0) self.test_res_ssim.pop(0) self.test_res_psnr.append(eval_psnr / len(d)) self.test_res_ssim.append(eval_ssim / len(d)) self.ckp.log[-1, idx_scale] = eval_psnr / len(d) self.ckp.write_log( '[Epoch {}---{} x{}]\tPSNR: {:.3f} SSIM: {:.4f} mean_PSNR: {:.3f} mean_SSIM: {:.4f}'.format( self.args.resume, self.args.data_test, scale, eval_psnr / len(d), eval_ssim / len(d), np.mean(self.test_res_psnr), np.mean(self.test_res_ssim) )) def crop_border(self, img_hr, scale): b, c, h, w = img_hr.size() img_hr = img_hr[:, :, :int(h//scale*scale), :int(w//scale*scale)] return img_hr def terminate(self): if self.args.test_only: self.test() return True else: epoch = self.scheduler.last_epoch + 1 return epoch >= self.args.epochs_sr ================================================ FILE: KDSR-classic/trainer_iso_stage3.py ================================================ import os import utility2 import utility import torch from decimal import Decimal import torch.nn.functional as F from utils import util from utils import util2 from collections import OrderedDict import random import numpy as np import torch.nn as nn import utility3 class Trainer(): def __init__(self, args, loader, model_TA, my_loss, ckp): self.test_res_psnr = [] self.test_res_ssim = [] self.args = args self.scale = args.scale self.loss1= nn.L1Loss() self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model_TA = model_TA self.loss = my_loss self.optimizer = utility2.make_optimizer(args, self.model_TA) self.scheduler = utility2.make_scheduler(args, self.optimizer) self.pixel_unshuffle = nn.PixelUnshuffle(self.scale[0]) if self.args.load != '.': self.optimizer.load_state_dict( torch.load(os.path.join(ckp.dir, 'optimizer.pt')) ) for _ in range(len(ckp.log)): self.scheduler.step() def train(self): self.scheduler.step() self.loss.step() epoch = self.scheduler.last_epoch + 1 lr = self.args.lr_sr * (self.args.gamma_sr ** ((epoch - self.args.epochs_encoder) // self.args.lr_decay_sr)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr self.ckp.write_log('[Epoch {}]\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))) self.loss.start_log() self.model_TA.train() degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig_min=self.args.sig_min, sig_max=self.args.sig_max, lambda_min=self.args.lambda_min, lambda_max=self.args.lambda_max, noise=self.args.noise ) timer = utility2.timer() for batch, ( hr, _,) in enumerate(self.loader_train): hr = hr.cuda() # b, c, h, w timer.tic() loss_all = 0 lr_blur, hr_blur = degrade(hr) # b, c, h, w hr2 = self.pixel_unshuffle(hr) sr, _ = self.model_TA(lr_blur, torch.cat([lr_blur,hr2], dim=1)) # sr,_ = self.model_TA(lr_blur, torch.cat([hr_blur,hr],dim=1)) loss_all += self.loss1(sr,hr) self.optimizer.zero_grad() loss_all.backward() self.optimizer.step() # Remove the hooks before next training phase timer.hold() if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [SR loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), loss_all.item(), timer.release(), )) self.loss.end_log(len(self.loader_train)) # save model if epoch > self.args.st_save_epoch or (epoch %20 ==0): target = self.model_TA.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_TA_{}.pt'.format(epoch)) ) optimzer_dict = self.optimizer.state_dict() torch.save( optimzer_dict, os.path.join(self.ckp.dir, 'optimzer', 'optimzer_TA_{}.pt'.format(epoch)) ) target = self.model_TA.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_TA_last.pt') ) optimzer_dict = self.optimizer.state_dict() torch.save( optimzer_dict, os.path.join(self.ckp.dir, 'optimzer', 'optimzer_TA_last.pt') ) def test(self): self.ckp.write_log('\nEvaluation:') self.ckp.add_log(torch.zeros(1, len(self.scale))) self.model_TA.eval() if self.scale[0]==4: sig_list=[1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2] elif self.scale[0]==2: sig_list=[0.9,1,1.1,1.2,1.3,1.4,1.5,1.6] timer_test = utility.timer() with torch.no_grad(): for idx_data, d in enumerate(self.loader_test): for idx_scale, scale in enumerate(self.scale): d.dataset.set_scale(idx_scale) eval_psnr = 0 eval_ssim = 0 for idx, (hr0, filename) in enumerate(d): for sig in sig_list: degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig=sig, lambda_1=self.args.lambda_1, lambda_2=self.args.lambda_2, theta=self.args.theta, noise=self.args.noise ) hr = hr0.cuda() # b, c, h, w hr = self.crop_border(hr, scale) # inference timer_test.tic() lr_blur, hr_blur = degrade(hr, random=False) hr2 = self.pixel_unshuffle(hr) sr = self.model_TA(lr_blur, torch.cat([lr_blur, hr2], dim=1)) timer_test.hold() sr = utility.quantize(sr, self.args.rgb_range) hr = utility.quantize(hr, self.args.rgb_range) # metrics # eval_psnr += utility.calc_psnr( # sr, hr, scale, self.args.rgb_range, # benchmark=d.dataset.benchmark # ) eval_psnr += utility3.calc_psnr( sr, hr, scale ) eval_ssim += utility.calc_ssim( (sr * 255).round().clamp(0, 255), (hr * 255).round().clamp(0, 255), scale, benchmark=d.dataset.benchmark ) # save results if self.args.save_results: save_list = [sr] filename = filename[0] self.ckp.save_results(filename, save_list, scale) # if len(self.test_res_psnr) > 10: # self.test_res_psnr.pop(0) # self.test_res_ssim.pop(0) # self.test_res_psnr.append(eval_psnr / len(d) /len(sig_list)) # self.test_res_ssim.append(eval_ssim / len(d)/len(sig_list)) self.ckp.log[-1, idx_scale] = eval_psnr / len(d)/len(sig_list) self.ckp.write_log( '[Epoch {}---{} x{}]\tPSNR: {:.3f} SSIM: {:.4f}'.format( self.args.resume, self.args.data_test, scale, eval_psnr / len(d) /len(sig_list), eval_ssim / len(d) /len(sig_list) )) def crop_border(self, img_hr, scale): b, c, h, w = img_hr.size() img_hr = img_hr[:, :, :int(h//scale*scale), :int(w//scale*scale)] return img_hr def terminate(self): if self.args.test_only: self.test() return True else: epoch = self.scheduler.last_epoch + 1 return epoch >= self.args.epochs_sr ================================================ FILE: KDSR-classic/trainer_iso_stage4.py ================================================ import os import utility import torch from decimal import Decimal import torch.nn.functional as F from utils import util2 import numpy as np import torch.nn as nn class Trainer(): def __init__(self, args, loader, model_ST, model_TA, my_loss, ckp): self.is_first =True self.args = args self.scale = args.scale self.test_res_psnr = [] self.test_res_ssim = [] self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model_ST = model_ST self.model_TA = model_TA self.model_Est = torch.nn.DataParallel(self.model_ST.get_model().E_st, range(self.args.n_GPUs)) self.model_Eta = torch.nn.DataParallel(self.model_TA.get_model().E, range(self.args.n_GPUs)) self.loss1 = nn.L1Loss() self.loss = my_loss self.optimizer = utility.make_optimizer(args, self.model_ST) self.scheduler = utility.make_scheduler(args, self.optimizer) self.temperature = args.temperature self.pixel_unshuffle = nn.PixelUnshuffle(self.scale[0]) if self.args.load != '.': self.optimizer.load_state_dict( torch.load(os.path.join(ckp.dir, 'optimizer.pt')) ) for _ in range(len(ckp.log)): self.scheduler.step() def train(self): self.scheduler.step() self.loss.step() epoch = self.scheduler.last_epoch + 1 if epoch <= self.args.epochs_encoder: lr = self.args.lr_encoder * (self.args.gamma_encoder ** (epoch // self.args.lr_decay_encoder)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr else: lr = self.args.lr_sr * (self.args.gamma_sr ** ((epoch - self.args.epochs_encoder) // self.args.lr_decay_sr)) for param_group in self.optimizer.param_groups: param_group['lr'] = lr self.ckp.write_log('[Epoch {}]\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))) self.loss.start_log() self.model_ST.train() degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig_min=self.args.sig_min, sig_max=self.args.sig_max, lambda_min=self.args.lambda_min, lambda_max=self.args.lambda_max, noise=self.args.noise ) timer = utility.timer() losses_sr, losses_distill_distribution, losses_distill_abs = utility.AverageMeter(),utility.AverageMeter(),utility.AverageMeter() for batch, (hr, _,) in enumerate(self.loader_train): hr = hr.cuda() # b, c, h, w timer.tic() lr_blur, hr_blur = degrade(hr) # b, c, h, w hr2 = self.pixel_unshuffle(hr) _, T_fea = self.model_Eta(torch.cat([lr_blur,hr2],dim=1)) loss_distill_dis = 0 loss_distill_abs = 0 if epoch <= self.args.epochs_encoder: _, S_fea = self.model_Est(lr_blur) for i in range(len(T_fea)): student_distance = F.log_softmax(S_fea[i] / self.temperature, dim=1) teacher_distance = F.softmax(T_fea[i].detach()/ self.temperature, dim=1) loss_distill_dis += F.kl_div( student_distance, teacher_distance, reduction='batchmean') loss_distill_abs += nn.L1Loss()(S_fea[i], T_fea[i].detach()) losses_distill_distribution.update(loss_distill_dis.item()) #losses_distill_distribution.update(loss_distill_dis) losses_distill_abs.update(loss_distill_abs.item()) loss = loss_distill_dis #+ 0.1* loss_distill_abs else: sr, S_fea = self.model_ST(lr_blur) loss_SR = self.loss(sr, hr) for i in range(len(T_fea)): student_distance = F.log_softmax(S_fea[i] / self.temperature, dim=1) teacher_distance = F.softmax(T_fea[i].detach() / self.temperature, dim=1) loss_distill_dis += F.kl_div( student_distance, teacher_distance, reduction='batchmean') loss_distill_abs += nn.L1Loss()(S_fea[i], T_fea[i].detach()) losses_distill_distribution.update(loss_distill_dis.item()) #losses_distill_distribution.update(loss_distill_dis) losses_distill_abs.update(loss_distill_abs.item()) loss = loss_SR + loss_distill_dis #+ 0.1* loss_distill_abs losses_sr.update(loss_SR.item()) # backward self.optimizer.zero_grad() loss.backward() self.optimizer.step() timer.hold() if epoch <= self.args.epochs_encoder: if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [ distill_dis loss:{:.3f}, distill_abs loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), losses_distill_distribution.avg, losses_distill_abs.avg, timer.release(), )) else: if (batch + 1) % self.args.print_every == 0: self.ckp.write_log( 'Epoch: [{:04d}][{:04d}/{:04d}]\t' 'Loss [SR loss:{:.3f}, distill_dis loss:{:.3f}, distill_abs loss:{:.3f}]\t' 'Time [{:.1f}s]'.format( epoch, (batch + 1) * self.args.batch_size, len(self.loader_train.dataset), losses_sr.avg, losses_distill_distribution.avg, losses_distill_abs.avg, timer.release(), )) self.loss.end_log(len(self.loader_train)) # save model if epoch > self.args.st_save_epoch or epoch%30==0: target = self.model_ST.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_ST_{}.pt'.format(epoch)) ) target = self.model_ST.get_model() model_dict = target.state_dict() torch.save( model_dict, os.path.join(self.ckp.dir, 'model', 'model_ST_last.pt') ) def test(self): self.ckp.write_log('\nEvaluation:') self.ckp.add_log(torch.zeros(1, len(self.scale))) self.model_ST.eval() if self.scale[0]==4: sig_list=[1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2] elif self.scale[0]==2: sig_list=[0.9,1,1.1,1.2,1.3,1.4,1.5,1.6] timer_test = utility.timer() # print(sig_list) with torch.no_grad(): for idx_data, d in enumerate(self.loader_test): for idx_scale, scale in enumerate(self.scale): d.dataset.set_scale(idx_scale) eval_psnr = 0 eval_ssim = 0 for idx, (hr0, filename) in enumerate(d): for sig in sig_list: degrade = util2.SRMDPreprocessing( self.scale[0], kernel_size=self.args.blur_kernel, blur_type=self.args.blur_type, sig=sig, lambda_1=self.args.lambda_1, lambda_2=self.args.lambda_2, theta=self.args.theta, noise=self.args.noise ) hr = hr0.cuda() # b, c, h, w hr = self.crop_border(hr, scale) lr_blur, hr_blur = degrade(hr, random=False) # b, c, h, w # inference timer_test.tic() sr = self.model_ST(lr_blur) timer_test.hold() sr = utility.quantize(sr, self.args.rgb_range) hr = utility.quantize(hr, self.args.rgb_range) # metrics eval_psnr += utility.calc_psnr( sr, hr, scale, self.args.rgb_range, benchmark=d.dataset.benchmark ) # eval_psnr += utility3.calc_psnr( # sr, hr, scale # ) eval_ssim += utility.calc_ssim( (sr * 255).round().clamp(0, 255), (hr * 255).round().clamp(0, 255), scale, benchmark=d.dataset.benchmark ) # save results if self.args.save_results: save_list = [sr] filename = filename[0] self.ckp.save_results(filename, save_list, scale) # if len(self.test_res_psnr) > 10: # self.test_res_psnr.pop(0) # self.test_res_ssim.pop(0) # self.test_res_psnr.append(eval_psnr / len(d) /len(sig_list)) # self.test_res_ssim.append(eval_ssim / len(d)/len(sig_list)) self.ckp.log[-1, idx_scale] = eval_psnr / len(d)/len(sig_list) self.ckp.write_log( '[Epoch {}---{} x{}]\tPSNR: {:.3f} SSIM: {:.4f} '.format( self.args.resume, self.args.data_test, scale, eval_psnr / len(d) /len(sig_list), eval_ssim / len(d) /len(sig_list) )) def crop_border(self, img_hr, scale): b, c, h, w = img_hr.size() img_hr = img_hr[:, :, :int(h//scale*scale), :int(w//scale*scale)] return img_hr def terminate(self): if self.args.test_only: self.test() return True else: epoch = self.scheduler.last_epoch + 1 return epoch >= self.args.epochs_sr ================================================ FILE: KDSR-classic/utility.py ================================================ import os import math import time import datetime import matplotlib.pyplot as plt import numpy as np import scipy.misc as misc import cv2 import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs import imageio class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class timer(): def __init__(self): self.acc = 0 self.tic() def tic(self): self.t0 = time.time() def toc(self): return time.time() - self.t0 def hold(self): self.acc += self.toc() def release(self): ret = self.acc self.acc = 0 return ret def reset(self): self.acc = 0 class checkpoint(): def __init__(self, args): self.args = args self.ok = True self.log = torch.Tensor() now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S') if args.blur_type == 'iso_gaussian': self.dir = './experiment/' + args.save + '_x' + str(int(args.scale[0])) + '_' + args.mode + '_iso' elif args.blur_type == 'aniso_gaussian': self.dir = './experiment/' + args.save + '_x' + str(int(args.scale[0])) + '_' + args.mode + '_aniso' def _make_dir(path): if not os.path.exists(path): os.makedirs(path) _make_dir(self.dir) _make_dir(self.dir + '/model') _make_dir(self.dir + '/optimzer') _make_dir(self.dir + '/results') open_type = 'a' if os.path.exists(self.dir + '/log.txt') else 'w' self.log_file = open(self.dir + '/log.txt', open_type) with open(self.dir + '/config.txt', open_type) as f: f.write(now + '\n\n') for arg in vars(args): f.write('{}: {}\n'.format(arg, getattr(args, arg))) f.write('\n') def save(self, trainer, epoch, is_best=False): trainer.model.save(self.dir, epoch, is_best=is_best) trainer.loss.save(self.dir) trainer.loss.plot_loss(self.dir, epoch) self.plot_psnr(epoch) torch.save(self.log, os.path.join(self.dir, 'psnr_log.pt')) torch.save( trainer.optimizer.state_dict(), os.path.join(self.dir, 'optimizer.pt') ) def add_log(self, log): self.log = torch.cat([self.log, log]) def write_log(self, log, refresh=False): print(log) self.log_file.write(log + '\n') if refresh: self.log_file.close() self.log_file = open(self.dir + '/log.txt', 'a') def done(self): self.log_file.close() def plot_psnr(self, epoch): axis = np.linspace(1, epoch, epoch) label = 'SR on {}'.format(self.args.data_test) fig = plt.figure() plt.title(label) for idx_scale, scale in enumerate(self.args.scale): plt.plot( axis, self.log[:, idx_scale].numpy(), label='Scale {}'.format(scale) ) plt.legend() plt.xlabel('Epochs') plt.ylabel('PSNR') plt.grid(True) plt.savefig('{}/test_{}.pdf'.format(self.dir, self.args.data_test)) plt.close(fig) def save_results(self, filename, save_list, scale): filename = '{}/results/{}_x{}_'.format(self.dir, filename, scale) normalized = save_list[0][0].data.mul(255 / self.args.rgb_range) ndarr = normalized.byte().permute(1, 2, 0).cpu().numpy() imageio.imsave('{}{}.png'.format(filename, 'SR'), ndarr) def quantize(img, rgb_range): pixel_range = 255 / rgb_range return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) def calc_psnr(sr, hr, scale, rgb_range, benchmark=False): diff = (sr - hr).data.div(rgb_range) if benchmark: shave = scale if diff.size(1) > 1: convert = diff.new(1, 3, 1, 1) convert[0, 0, 0, 0] = 65.738 convert[0, 1, 0, 0] = 129.057 convert[0, 2, 0, 0] = 25.064 diff.mul_(convert).div_(256) diff = diff.sum(dim=1, keepdim=True) else: shave = scale + 6 import math shave = math.ceil(shave) valid = diff[:, :, shave:-shave, shave:-shave] mse = valid.pow(2).mean() return -10 * math.log10(mse) def calc_ssim(img1, img2, scale=2, benchmark=False): '''calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] ''' if benchmark: border = math.ceil(scale) else: border = math.ceil(scale) + 6 img1 = img1.data.squeeze().float().clamp(0, 255).round().cpu().numpy() img1 = np.transpose(img1, (1, 2, 0)) img2 = img2.data.squeeze().cpu().numpy() img2 = np.transpose(img2, (1, 2, 0)) img1_y = np.dot(img1, [65.738, 129.057, 25.064]) / 255.0 + 16.0 img2_y = np.dot(img2, [65.738, 129.057, 25.064]) / 255.0 + 16.0 if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') h, w = img1.shape[:2] img1_y = img1_y[border:h - border, border:w - border] img2_y = img2_y[border:h - border, border:w - border] if img1_y.ndim == 2: return ssim(img1_y, img2_y) elif img1.ndim == 3: if img1.shape[2] == 3: ssims = [] for i in range(3): ssims.append(ssim(img1, img2)) return np.array(ssims).mean() elif img1.shape[2] == 1: return ssim(np.squeeze(img1), np.squeeze(img2)) else: raise ValueError('Wrong input image dimensions.') def ssim(img1, img2): C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) kernel = cv2.getGaussianKernel(11, 1.5) window = np.outer(kernel, kernel.transpose()) mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] mu1_sq = mu1 ** 2 mu2_sq = mu2 ** 2 mu1_mu2 = mu1 * mu2 sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) return ssim_map.mean() def make_optimizer(args, my_model): trainable = filter(lambda x: x.requires_grad, my_model.parameters()) if args.optimizer == 'SGD': optimizer_function = optim.SGD kwargs = {'momentum': args.momentum} elif args.optimizer == 'ADAM': optimizer_function = optim.Adam kwargs = { 'betas': (args.beta1, args.beta2), 'eps': args.epsilon } elif args.optimizer == 'RMSprop': optimizer_function = optim.RMSprop kwargs = {'eps': args.epsilon} kwargs['weight_decay'] = args.weight_decay return optimizer_function(trainable, **kwargs) def make_scheduler(args, my_optimizer): if args.decay_type == 'step': scheduler = lrs.StepLR( my_optimizer, step_size=args.lr_decay_sr, gamma=args.gamma_sr, ) elif args.decay_type.find('step') >= 0: milestones = args.decay_type.split('_') milestones.pop(0) milestones = list(map(lambda x: int(x), milestones)) scheduler = lrs.MultiStepLR( my_optimizer, milestones=milestones, gamma=args.gamma ) scheduler.step(args.start_epoch - 1) return scheduler ================================================ FILE: KDSR-classic/utility2.py ================================================ import os import math import time import datetime import matplotlib.pyplot as plt import numpy as np import scipy.misc as misc import cv2 import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class timer(): def __init__(self): self.acc = 0 self.tic() def tic(self): self.t0 = time.time() def toc(self): return time.time() - self.t0 def hold(self): self.acc += self.toc() def release(self): ret = self.acc self.acc = 0 return ret def reset(self): self.acc = 0 class checkpoint(): def __init__(self, args): self.args = args self.ok = True self.log = torch.Tensor() now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S') if args.blur_type == 'iso_gaussian': self.dir = './experiment/' + args.save + '_x' + str(int(args.scale[0])) + '_' + args.mode + '_iso' elif args.blur_type == 'aniso_gaussian': self.dir = './experiment/' + args.save + '_x' + str(int(args.scale[0])) + '_' + args.mode + '_aniso' def _make_dir(path): if not os.path.exists(path): os.makedirs(path) _make_dir(self.dir) _make_dir(self.dir + '/model') _make_dir(self.dir + '/results') open_type = 'a' if os.path.exists(self.dir + '/log.txt') else 'w' self.log_file = open(self.dir + '/log.txt', open_type) with open(self.dir + '/config.txt', open_type) as f: f.write(now + '\n\n') for arg in vars(args): f.write('{}: {}\n'.format(arg, getattr(args, arg))) f.write('\n') def save(self, trainer, epoch, is_best=False): trainer.model.save(self.dir, epoch, is_best=is_best) trainer.loss.save(self.dir) trainer.loss.plot_loss(self.dir, epoch) self.plot_psnr(epoch) torch.save(self.log, os.path.join(self.dir, 'psnr_log.pt')) torch.save( trainer.optimizer.state_dict(), os.path.join(self.dir, 'optimizer.pt') ) def add_log(self, log): self.log = torch.cat([self.log, log]) def write_log(self, log, refresh=False): print(log) self.log_file.write(log + '\n') if refresh: self.log_file.close() self.log_file = open(self.dir + '/log.txt', 'a') def done(self): self.log_file.close() def plot_psnr(self, epoch): axis = np.linspace(1, epoch, epoch) label = 'SR on {}'.format(self.args.data_test) fig = plt.figure() plt.title(label) for idx_scale, scale in enumerate(self.args.scale): plt.plot( axis, self.log[:, idx_scale].numpy(), label='Scale {}'.format(scale) ) plt.legend() plt.xlabel('Epochs') plt.ylabel('PSNR') plt.grid(True) plt.savefig('{}/test_{}.pdf'.format(self.dir, self.args.data_test)) plt.close(fig) def save_results(self, filename, save_list, scale): filename = '{}/results/{}_x{}_'.format(self.dir, filename, scale) normalized = save_list[0][0].data.mul(255 / self.args.rgb_range) ndarr = normalized.byte().permute(1, 2, 0).cpu().numpy() misc.imsave('{}{}.png'.format(filename, 'SR'), ndarr) def quantize(img, rgb_range): pixel_range = 255 / rgb_range return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) def calc_psnr(sr, hr, scale, rgb_range, benchmark=False): diff = (sr - hr).data.div(rgb_range) if benchmark: shave = scale if diff.size(1) > 1: convert = diff.new(1, 3, 1, 1) convert[0, 0, 0, 0] = 65.738 convert[0, 1, 0, 0] = 129.057 convert[0, 2, 0, 0] = 25.064 diff.mul_(convert).div_(256) diff = diff.sum(dim=1, keepdim=True) else: shave = scale + 6 import math shave = math.ceil(shave) valid = diff[:, :, shave:-shave, shave:-shave] mse = valid.pow(2).mean() return -10 * math.log10(mse) def calc_ssim(img1, img2, scale=2, benchmark=False): '''calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] ''' if benchmark: border = math.ceil(scale) else: border = math.ceil(scale) + 6 img1 = img1.data.squeeze().float().clamp(0, 255).round().cpu().numpy() img1 = np.transpose(img1, (1, 2, 0)) img2 = img2.data.squeeze().cpu().numpy() img2 = np.transpose(img2, (1, 2, 0)) img1_y = np.dot(img1, [65.738, 129.057, 25.064]) / 255.0 + 16.0 img2_y = np.dot(img2, [65.738, 129.057, 25.064]) / 255.0 + 16.0 if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') h, w = img1.shape[:2] img1_y = img1_y[border:h - border, border:w - border] img2_y = img2_y[border:h - border, border:w - border] if img1_y.ndim == 2: return ssim(img1_y, img2_y) elif img1.ndim == 3: if img1.shape[2] == 3: ssims = [] for i in range(3): ssims.append(ssim(img1, img2)) return np.array(ssims).mean() elif img1.shape[2] == 1: return ssim(np.squeeze(img1), np.squeeze(img2)) else: raise ValueError('Wrong input image dimensions.') def ssim(img1, img2): C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) kernel = cv2.getGaussianKernel(11, 1.5) window = np.outer(kernel, kernel.transpose()) mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] mu1_sq = mu1 ** 2 mu2_sq = mu2 ** 2 mu1_mu2 = mu1 * mu2 sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) return ssim_map.mean() def make_optimizer(args, my_model): trainable = filter(lambda x: x.requires_grad, my_model.parameters()) if args.optimizer == 'SGD': optimizer_function = optim.SGD kwargs = {'momentum': args.momentum} elif args.optimizer == 'ADAM': optimizer_function = optim.Adam kwargs = { 'betas': (args.beta1, args.beta2), 'eps': args.epsilon } elif args.optimizer == 'RMSprop': optimizer_function = optim.RMSprop kwargs = {'eps': args.epsilon} kwargs['weight_decay'] = args.weight_decay return optimizer_function(trainable, **kwargs) def make_scheduler(args, my_optimizer): if args.decay_type == 'step': scheduler = lrs.StepLR( my_optimizer, step_size=args.lr_decay_sr, gamma=args.gamma_sr, ) elif args.decay_type.find('step') >= 0: milestones = args.decay_type.split('_') milestones.pop(0) milestones = list(map(lambda x: int(x), milestones)) scheduler = lrs.MultiStepLR( my_optimizer, milestones=milestones, gamma=args.gamma ) scheduler.step(args.start_epoch - 1) return scheduler ================================================ FILE: KDSR-classic/utility3.py ================================================ import os import math import time import datetime import matplotlib.pyplot as plt import numpy as np import scipy.misc as misc import cv2 import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs def tensor2img(tensor, out_type=np.float32, min_max=(0, 1)): """ Converts a torch Tensor into an image Numpy array Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default) """ tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # clamp tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1] n_dim = tensor.dim() if n_dim == 4: n_img = len(tensor) img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy() img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR elif n_dim == 3: img_np = tensor.numpy() img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR elif n_dim == 2: img_np = tensor.numpy() else: raise TypeError( "Only support 4D, 3D and 2D tensor. But received with dimension: {:d}".format( n_dim ) ) if out_type == np.uint8: img_np = (img_np * 255.0).round() # Important. Unlike matlab, numpy.unit8() WILL NOT round by default. return img_np.astype(out_type) def bgr2ycbcr(img, only_y=True): '''bgr version of rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1] ''' img = tensor2img(img.squeeze()) in_img_type = img.dtype img.astype(np.float32) if in_img_type != np.uint8: img *= 255. # convert if only_y: rlt = np.dot(img, [24.966, 128.553, 65.481]) / 255.0 + 16.0 else: rlt = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) / 255.0 + [16, 128, 128] if in_img_type == np.uint8: rlt = rlt.round() else: rlt /= 255. return rlt.astype(in_img_type) def calc_psnr(img1, img2,scale): # img1 and img2 have range [0, 255] img1 = img1.data img2 = img2.data img1 = img1[:, :, scale:-scale, scale:-scale] img2 = img2[:, :, scale:-scale, scale:-scale] img1 = bgr2ycbcr(img1, only_y=True) * 255 img2 = bgr2ycbcr(img2, only_y=True) * 255 img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) mse = np.mean((img1 - img2) ** 2) if mse == 0: return float("inf") return 20 * math.log10(255.0 / math.sqrt(mse)) def ssim(img1, img2): C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) kernel = cv2.getGaussianKernel(11, 1.5) window = np.outer(kernel, kernel.transpose()) mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] mu1_sq = mu1 ** 2 mu2_sq = mu2 ** 2 mu1_mu2 = mu1 * mu2 sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ( (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) ) return ssim_map.mean() def calculate_ssim(img1, img2): """calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] """ if not img1.shape == img2.shape: raise ValueError("Input images must have the same dimensions.") if img1.ndim == 2: return ssim(img1, img2) elif img1.ndim == 3: if img1.shape[2] == 3: ssims = [] for i in range(3): ssims.append(ssim(img1, img2)) return np.array(ssims).mean() elif img1.shape[2] == 1: return ssim(np.squeeze(img1), np.squeeze(img2)) else: raise ValueError("Wrong input image dimensions.") ================================================ FILE: KDSR-classic/utils/__init__.py ================================================ ================================================ FILE: KDSR-classic/utils/util.py ================================================ import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import utility def cal_sigma(sig_x, sig_y, radians): sig_x = sig_x.view(-1, 1, 1) sig_y = sig_y.view(-1, 1, 1) radians = radians.view(-1, 1, 1) D = torch.cat([F.pad(sig_x ** 2, [0, 1, 0, 0]), F.pad(sig_y ** 2, [1, 0, 0, 0])], 1) U = torch.cat([torch.cat([radians.cos(), -radians.sin()], 2), torch.cat([radians.sin(), radians.cos()], 2)], 1) sigma = torch.bmm(U, torch.bmm(D, U.transpose(1, 2))) return sigma def anisotropic_gaussian_kernel(batch, kernel_size, covar): ax = torch.arange(kernel_size).float().cuda() - kernel_size // 2 xx = ax.repeat(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) yy = ax.repeat_interleave(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) xy = torch.stack([xx, yy], -1).view(batch, -1, 2) inverse_sigma = torch.inverse(covar) kernel = torch.exp(- 0.5 * (torch.bmm(xy, inverse_sigma) * xy).sum(2)).view(batch, kernel_size, kernel_size) return kernel / kernel.sum([1, 2], keepdim=True) def isotropic_gaussian_kernel(batch, kernel_size, sigma): ax = torch.arange(kernel_size).float().cuda() - kernel_size//2 xx = ax.repeat(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) yy = ax.repeat_interleave(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) kernel = torch.exp(-(xx ** 2 + yy ** 2) / (2. * sigma.view(-1, 1, 1) ** 2)) return kernel / kernel.sum([1,2], keepdim=True) def random_anisotropic_gaussian_kernel(batch=1, kernel_size=21, lambda_min=0.2, lambda_max=4.0): theta = torch.rand(batch).cuda() * math.pi lambda_1 = torch.rand(batch).cuda() * (lambda_max - lambda_min) + lambda_min lambda_2 = torch.rand(batch).cuda() * (lambda_max - lambda_min) + lambda_min covar = cal_sigma(lambda_1, lambda_2, theta) kernel = anisotropic_gaussian_kernel(batch, kernel_size, covar) return kernel def stable_anisotropic_gaussian_kernel(kernel_size=21, theta=0, lambda_1=0.2, lambda_2=4.0): theta = torch.ones(1).cuda() * theta / 180 * math.pi lambda_1 = torch.ones(1).cuda() * lambda_1 lambda_2 = torch.ones(1).cuda() * lambda_2 covar = cal_sigma(lambda_1, lambda_2, theta) kernel = anisotropic_gaussian_kernel(1, kernel_size, covar) return kernel def random_isotropic_gaussian_kernel(batch=1, kernel_size=21, sig_min=0.2, sig_max=4.0): x = torch.rand(batch).cuda() * (sig_max - sig_min) + sig_min k = isotropic_gaussian_kernel(batch, kernel_size, x) return k def stable_isotropic_gaussian_kernel(kernel_size=21, sig=4.0): x = torch.ones(1).cuda() * sig k = isotropic_gaussian_kernel(1, kernel_size, x) return k def random_gaussian_kernel(batch, kernel_size=21, blur_type='iso_gaussian', sig_min=0.2, sig_max=4.0, lambda_min=0.2, lambda_max=4.0): if blur_type == 'iso_gaussian': return random_isotropic_gaussian_kernel(batch=batch, kernel_size=kernel_size, sig_min=sig_min, sig_max=sig_max) elif blur_type == 'aniso_gaussian': return random_anisotropic_gaussian_kernel(batch=batch, kernel_size=kernel_size, lambda_min=lambda_min, lambda_max=lambda_max) def stable_gaussian_kernel(kernel_size=21, blur_type='iso_gaussian', sig=2.6, lambda_1=0.2, lambda_2=4.0, theta=0): if blur_type == 'iso_gaussian': return stable_isotropic_gaussian_kernel(kernel_size=kernel_size, sig=sig) elif blur_type == 'aniso_gaussian': return stable_anisotropic_gaussian_kernel(kernel_size=kernel_size, lambda_1=lambda_1, lambda_2=lambda_2, theta=theta) # implementation of matlab bicubic interpolation in pytorch class bicubic(nn.Module): def __init__(self): super(bicubic, self).__init__() def cubic(self, x): absx = torch.abs(x) absx2 = torch.abs(x) * torch.abs(x) absx3 = torch.abs(x) * torch.abs(x) * torch.abs(x) condition1 = (absx <= 1).to(torch.float32) condition2 = ((1 < absx) & (absx <= 2)).to(torch.float32) f = (1.5 * absx3 - 2.5 * absx2 + 1) * condition1 + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2) * condition2 return f def contribute(self, in_size, out_size, scale): kernel_width = 4 if scale < 1: kernel_width = 4 / scale x0 = torch.arange(start=1, end=out_size[0] + 1).to(torch.float32).cuda() x1 = torch.arange(start=1, end=out_size[1] + 1).to(torch.float32).cuda() u0 = x0 / scale + 0.5 * (1 - 1 / scale) u1 = x1 / scale + 0.5 * (1 - 1 / scale) left0 = torch.floor(u0 - kernel_width / 2) left1 = torch.floor(u1 - kernel_width / 2) P = np.ceil(kernel_width) + 2 indice0 = left0.unsqueeze(1) + torch.arange(start=0, end=P).to(torch.float32).unsqueeze(0).cuda() indice1 = left1.unsqueeze(1) + torch.arange(start=0, end=P).to(torch.float32).unsqueeze(0).cuda() mid0 = u0.unsqueeze(1) - indice0.unsqueeze(0) mid1 = u1.unsqueeze(1) - indice1.unsqueeze(0) if scale < 1: weight0 = scale * self.cubic(mid0 * scale) weight1 = scale * self.cubic(mid1 * scale) else: weight0 = self.cubic(mid0) weight1 = self.cubic(mid1) weight0 = weight0 / (torch.sum(weight0, 2).unsqueeze(2)) weight1 = weight1 / (torch.sum(weight1, 2).unsqueeze(2)) indice0 = torch.min(torch.max(torch.FloatTensor([1]).cuda(), indice0), torch.FloatTensor([in_size[0]]).cuda()).unsqueeze(0) indice1 = torch.min(torch.max(torch.FloatTensor([1]).cuda(), indice1), torch.FloatTensor([in_size[1]]).cuda()).unsqueeze(0) kill0 = torch.eq(weight0, 0)[0][0] kill1 = torch.eq(weight1, 0)[0][0] weight0 = weight0[:, :, kill0 == 0] weight1 = weight1[:, :, kill1 == 0] indice0 = indice0[:, :, kill0 == 0] indice1 = indice1[:, :, kill1 == 0] return weight0, weight1, indice0, indice1 def forward(self, input, scale=1/4): b, c, h, w = input.shape weight0, weight1, indice0, indice1 = self.contribute([h, w], [int(h * scale), int(w * scale)], scale) weight0 = weight0[0] weight1 = weight1[0] indice0 = indice0[0].long() indice1 = indice1[0].long() out = input[:, :, (indice0 - 1), :] * (weight0.unsqueeze(0).unsqueeze(1).unsqueeze(4)) out = (torch.sum(out, dim=3)) A = out.permute(0, 1, 3, 2) out = A[:, :, (indice1 - 1), :] * (weight1.unsqueeze(0).unsqueeze(1).unsqueeze(4)) out = out.sum(3).permute(0, 1, 3, 2) return out class Gaussin_Kernel(object): def __init__(self, kernel_size=21, blur_type='iso_gaussian', sig=2.6, sig_min=0.2, sig_max=4.0, lambda_1=0.2, lambda_2=4.0, theta=0, lambda_min=0.2, lambda_max=4.0): self.kernel_size = kernel_size self.blur_type = blur_type self.sig = sig self.sig_min = sig_min self.sig_max = sig_max self.lambda_1 = lambda_1 self.lambda_2 = lambda_2 self.theta = theta self.lambda_min = lambda_min self.lambda_max = lambda_max def __call__(self, batch, random): # random kernel if random == True: return random_gaussian_kernel(batch, kernel_size=self.kernel_size, blur_type=self.blur_type, sig_min=self.sig_min, sig_max=self.sig_max, lambda_min=self.lambda_min, lambda_max=self.lambda_max) # stable kernel else: return stable_gaussian_kernel(kernel_size=self.kernel_size, blur_type=self.blur_type, sig=self.sig, lambda_1=self.lambda_1, lambda_2=self.lambda_2, theta=self.theta) class BatchBlur(nn.Module): def __init__(self, kernel_size=21): super(BatchBlur, self).__init__() self.kernel_size = kernel_size if kernel_size % 2 == 1: self.pad = nn.ReflectionPad2d(kernel_size//2) else: self.pad = nn.ReflectionPad2d((kernel_size//2, kernel_size//2-1, kernel_size//2, kernel_size//2-1)) def forward(self, input, kernel): B, C, H, W = input.size() input_pad = self.pad(input) H_p, W_p = input_pad.size()[-2:] if len(kernel.size()) == 2: input_CBHW = input_pad.view((C * B, 1, H_p, W_p)) kernel = kernel.contiguous().view((1, 1, self.kernel_size, self.kernel_size)) return F.conv2d(input_CBHW, kernel, padding=0).view((B, C, H, W)) else: input_CBHW = input_pad.view((1, C * B, H_p, W_p)) kernel = kernel.contiguous().view((B, 1, self.kernel_size, self.kernel_size)) kernel = kernel.repeat(1, C, 1, 1).view((B * C, 1, self.kernel_size, self.kernel_size)) return F.conv2d(input_CBHW, kernel, groups=B*C).view((B, C, H, W)) class SRMDPreprocessing(object): def __init__(self, scale, mode='bicubic', kernel_size=21, blur_type='iso_gaussian', sig=2.6, sig_min=0.2, sig_max=4.0, lambda_1=0.2, lambda_2=4.0, theta=0, lambda_min=0.2, lambda_max=4.0, noise=0.0, rgb_range=1 ): ''' # sig, sig_min and sig_max are used for isotropic Gaussian blurs During training phase (random=True): the width of the blur kernel is randomly selected from [sig_min, sig_max] During test phase (random=False): the width of the blur kernel is set to sig # lambda_1, lambda_2, theta, lambda_min and lambda_max are used for anisotropic Gaussian blurs During training phase (random=True): the eigenvalues of the covariance is randomly selected from [lambda_min, lambda_max] the angle value is randomly selected from [0, pi] During test phase (random=False): the eigenvalues of the covariance are set to lambda_1 and lambda_2 the angle value is set to theta ''' self.kernel_size = kernel_size self.scale = scale self.mode = mode self.noise = noise / (255/rgb_range) self.rgb_range=rgb_range self.gen_kernel = Gaussin_Kernel( kernel_size=kernel_size, blur_type=blur_type, sig=sig, sig_min=sig_min, sig_max=sig_max, lambda_1=lambda_1, lambda_2=lambda_2, theta=theta, lambda_min=lambda_min, lambda_max=lambda_max ) self.blur = BatchBlur(kernel_size=kernel_size) self.bicubic = bicubic() def __call__(self, hr_tensor, random=True): with torch.no_grad(): # only downsampling if self.gen_kernel.blur_type == 'iso_gaussian' and self.gen_kernel.sig == 0: B, C, H, W = hr_tensor.size() hr_blured = hr_tensor.view(-1, C, H, W) b_kernels = None # gaussian blur + downsampling else: B, C, H, W = hr_tensor.size() b_kernels = self.gen_kernel(B, random) # B degradations # blur hr_blured = self.blur(hr_tensor.view(B, -1, H, W), b_kernels) hr_blured = hr_blured.view(-1, C, H, W) # B, C, H, W # downsampling if self.mode == 'bicubic': lr_blured = self.bicubic(hr_blured, scale=1/self.scale) elif self.mode == 's-fold': lr_blured = hr_blured.view(-1, C, H//self.scale, self.scale, W//self.scale, self.scale)[:, :, :, 0, :, 0] # add noise noise_level = None if self.noise > 0: _, C, H_lr, W_lr = lr_blured.size() noise_level = torch.rand(B, 1, 1, 1).to(lr_blured.device) * self.noise if random else self.noise noise = torch.randn_like(lr_blured).view(-1, C, H_lr, W_lr).mul_(noise_level).view(-1, C, H_lr, W_lr) lr_blured.add_(noise) lr_blured = utility.quantize(lr_blured, self.rgb_range) if isinstance(noise_level, float): noise_level = torch.Tensor([noise_level]).view(1,1,1,1).to(lr_blured.device) return lr_blured.view(B, C, H//int(self.scale), W//int(self.scale)), [b_kernels,noise_level] class BicubicPreprocessing(object): def __init__(self, scale, rgb_range=1 ): ''' # sig, sig_min and sig_max are used for isotropic Gaussian blurs During training phase (random=True): the width of the blur kernel is randomly selected from [sig_min, sig_max] During test phase (random=False): the width of the blur kernel is set to sig # lambda_1, lambda_2, theta, lambda_min and lambda_max are used for anisotropic Gaussian blurs During training phase (random=True): the eigenvalues of the covariance is randomly selected from [lambda_min, lambda_max] the angle value is randomly selected from [0, pi] During test phase (random=False): the eigenvalues of the covariance are set to lambda_1 and lambda_2 the angle value is set to theta ''' self.scale = scale self.rgb_range=rgb_range self.bicubic = bicubic() def __call__(self, hr_tensor, random=True): with torch.no_grad(): B, C, H, W = hr_tensor.size() lr = self.bicubic(hr_tensor, scale=1/self.scale) lr_bic = self.bicubic(lr, scale=self.scale) lr = utility.quantize(lr, self.rgb_range) lr_bic = utility.quantize(lr_bic, self.rgb_range) return lr.view(B, C, H//int(self.scale), W//int(self.scale)),lr_bic.view(B, C, H, W) ================================================ FILE: KDSR-classic/utils/util2.py ================================================ import math import numpy as np import utility import torch import torch.nn as nn import torch.nn.functional as F def cal_sigma(sig_x, sig_y, radians): sig_x = sig_x.view(-1, 1, 1) sig_y = sig_y.view(-1, 1, 1) radians = radians.view(-1, 1, 1) D = torch.cat([F.pad(sig_x ** 2, [0, 1, 0, 0]), F.pad(sig_y ** 2, [1, 0, 0, 0])], 1) U = torch.cat([torch.cat([radians.cos(), -radians.sin()], 2), torch.cat([radians.sin(), radians.cos()], 2)], 1) sigma = torch.bmm(U, torch.bmm(D, U.transpose(1, 2))) return sigma def anisotropic_gaussian_kernel(batch, kernel_size, covar): ax = torch.arange(kernel_size).float().cuda() - kernel_size // 2 xx = ax.repeat(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) yy = ax.repeat_interleave(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) xy = torch.stack([xx, yy], -1).view(batch, -1, 2) inverse_sigma = torch.inverse(covar) kernel = torch.exp(- 0.5 * (torch.bmm(xy, inverse_sigma) * xy).sum(2)).view(batch, kernel_size, kernel_size) return kernel / kernel.sum([1, 2], keepdim=True) def isotropic_gaussian_kernel(batch, kernel_size, sigma): ax = torch.arange(kernel_size).float().cuda() - kernel_size//2 xx = ax.repeat(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) yy = ax.repeat_interleave(kernel_size).view(1, kernel_size, kernel_size).expand(batch, -1, -1) kernel = torch.exp(-(xx ** 2 + yy ** 2) / (2. * sigma.view(-1, 1, 1) ** 2)) return kernel / kernel.sum([1,2], keepdim=True) def random_anisotropic_gaussian_kernel(batch=1, kernel_size=21, lambda_min=0.2, lambda_max=4.0): theta = torch.rand(batch).cuda() * math.pi lambda_1 = torch.rand(batch).cuda() * (lambda_max - lambda_min) + lambda_min lambda_2 = torch.rand(batch).cuda() * (lambda_max - lambda_min) + lambda_min covar = cal_sigma(lambda_1, lambda_2, theta) kernel = anisotropic_gaussian_kernel(batch, kernel_size, covar) return kernel def stable_anisotropic_gaussian_kernel(kernel_size=21, theta=0, lambda_1=0.2, lambda_2=4.0): theta = torch.ones(1).cuda() * theta / 180 * math.pi lambda_1 = torch.ones(1).cuda() * lambda_1 lambda_2 = torch.ones(1).cuda() * lambda_2 covar = cal_sigma(lambda_1, lambda_2, theta) kernel = anisotropic_gaussian_kernel(1, kernel_size, covar) return kernel def random_isotropic_gaussian_kernel(batch=1, kernel_size=21, sig_min=0.2, sig_max=4.0): x = torch.rand(batch).cuda() * (sig_max - sig_min) + sig_min k = isotropic_gaussian_kernel(batch, kernel_size, x) return k def stable_isotropic_gaussian_kernel(kernel_size=21, sig=4.0): x = torch.ones(1).cuda() * sig k = isotropic_gaussian_kernel(1, kernel_size, x) return k def random_gaussian_kernel(batch, kernel_size=21, blur_type='iso_gaussian', sig_min=0.2, sig_max=4.0, lambda_min=0.2, lambda_max=4.0): if blur_type == 'iso_gaussian': return random_isotropic_gaussian_kernel(batch=batch, kernel_size=kernel_size, sig_min=sig_min, sig_max=sig_max) elif blur_type == 'aniso_gaussian': return random_anisotropic_gaussian_kernel(batch=batch, kernel_size=kernel_size, lambda_min=lambda_min, lambda_max=lambda_max) def stable_gaussian_kernel(kernel_size=21, blur_type='iso_gaussian', sig=2.6, lambda_1=0.2, lambda_2=4.0, theta=0): if blur_type == 'iso_gaussian': return stable_isotropic_gaussian_kernel(kernel_size=kernel_size, sig=sig) elif blur_type == 'aniso_gaussian': return stable_anisotropic_gaussian_kernel(kernel_size=kernel_size, lambda_1=lambda_1, lambda_2=lambda_2, theta=theta) # implementation of matlab bicubic interpolation in pytorch class bicubic(nn.Module): def __init__(self): super(bicubic, self).__init__() def cubic(self, x): absx = torch.abs(x) absx2 = torch.abs(x) * torch.abs(x) absx3 = torch.abs(x) * torch.abs(x) * torch.abs(x) condition1 = (absx <= 1).to(torch.float32) condition2 = ((1 < absx) & (absx <= 2)).to(torch.float32) f = (1.5 * absx3 - 2.5 * absx2 + 1) * condition1 + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2) * condition2 return f def contribute(self, in_size, out_size, scale): kernel_width = 4 if scale < 1: kernel_width = 4 / scale x0 = torch.arange(start=1, end=out_size[0] + 1).to(torch.float32).cuda() x1 = torch.arange(start=1, end=out_size[1] + 1).to(torch.float32).cuda() u0 = x0 / scale + 0.5 * (1 - 1 / scale) u1 = x1 / scale + 0.5 * (1 - 1 / scale) left0 = torch.floor(u0 - kernel_width / 2) left1 = torch.floor(u1 - kernel_width / 2) P = np.ceil(kernel_width) + 2 indice0 = left0.unsqueeze(1) + torch.arange(start=0, end=P).to(torch.float32).unsqueeze(0).cuda() indice1 = left1.unsqueeze(1) + torch.arange(start=0, end=P).to(torch.float32).unsqueeze(0).cuda() mid0 = u0.unsqueeze(1) - indice0.unsqueeze(0) mid1 = u1.unsqueeze(1) - indice1.unsqueeze(0) if scale < 1: weight0 = scale * self.cubic(mid0 * scale) weight1 = scale * self.cubic(mid1 * scale) else: weight0 = self.cubic(mid0) weight1 = self.cubic(mid1) weight0 = weight0 / (torch.sum(weight0, 2).unsqueeze(2)) weight1 = weight1 / (torch.sum(weight1, 2).unsqueeze(2)) indice0 = torch.min(torch.max(torch.FloatTensor([1]).cuda(), indice0), torch.FloatTensor([in_size[0]]).cuda()).unsqueeze(0) indice1 = torch.min(torch.max(torch.FloatTensor([1]).cuda(), indice1), torch.FloatTensor([in_size[1]]).cuda()).unsqueeze(0) kill0 = torch.eq(weight0, 0)[0][0] kill1 = torch.eq(weight1, 0)[0][0] weight0 = weight0[:, :, kill0 == 0] weight1 = weight1[:, :, kill1 == 0] indice0 = indice0[:, :, kill0 == 0] indice1 = indice1[:, :, kill1 == 0] return weight0, weight1, indice0, indice1 def forward(self, input, scale=1/4): b, c, h, w = input.shape weight0, weight1, indice0, indice1 = self.contribute([h, w], [int(h * scale), int(w * scale)], scale) weight0 = weight0[0] weight1 = weight1[0] indice0 = indice0[0].long() indice1 = indice1[0].long() out = input[:, :, (indice0 - 1), :] * (weight0.unsqueeze(0).unsqueeze(1).unsqueeze(4)) out = (torch.sum(out, dim=3)) A = out.permute(0, 1, 3, 2) out = A[:, :, (indice1 - 1), :] * (weight1.unsqueeze(0).unsqueeze(1).unsqueeze(4)) out = out.sum(3).permute(0, 1, 3, 2) return out class Gaussin_Kernel(object): def __init__(self, kernel_size=21, blur_type='iso_gaussian', sig=2.6, sig_min=0.2, sig_max=4.0, lambda_1=0.2, lambda_2=4.0, theta=0, lambda_min=0.2, lambda_max=4.0): self.kernel_size = kernel_size self.blur_type = blur_type self.sig = sig self.sig_min = sig_min self.sig_max = sig_max self.lambda_1 = lambda_1 self.lambda_2 = lambda_2 self.theta = theta self.lambda_min = lambda_min self.lambda_max = lambda_max def __call__(self, batch, random): # random kernel if random == True: return random_gaussian_kernel(batch, kernel_size=self.kernel_size, blur_type=self.blur_type, sig_min=self.sig_min, sig_max=self.sig_max, lambda_min=self.lambda_min, lambda_max=self.lambda_max) # stable kernel else: return stable_gaussian_kernel(kernel_size=self.kernel_size, blur_type=self.blur_type, sig=self.sig, lambda_1=self.lambda_1, lambda_2=self.lambda_2, theta=self.theta) class BatchBlur(nn.Module): def __init__(self, kernel_size=21): super(BatchBlur, self).__init__() self.kernel_size = kernel_size if kernel_size % 2 == 1: self.pad = nn.ReflectionPad2d(kernel_size//2) else: self.pad = nn.ReflectionPad2d((kernel_size//2, kernel_size//2-1, kernel_size//2, kernel_size//2-1)) def forward(self, input, kernel): B, C, H, W = input.size() input_pad = self.pad(input) H_p, W_p = input_pad.size()[-2:] if len(kernel.size()) == 2: input_CBHW = input_pad.view((C * B, 1, H_p, W_p)) kernel = kernel.contiguous().view((1, 1, self.kernel_size, self.kernel_size)) return F.conv2d(input_CBHW, kernel, padding=0).view((B, C, H, W)) else: input_CBHW = input_pad.view((1, C * B, H_p, W_p)) kernel = kernel.contiguous().view((B, 1, self.kernel_size, self.kernel_size)) kernel = kernel.repeat(1, C, 1, 1).view((B * C, 1, self.kernel_size, self.kernel_size)) return F.conv2d(input_CBHW, kernel, groups=B*C).view((B, C, H, W)) class SRMDPreprocessing(object): def __init__(self, scale, mode='bicubic', kernel_size=21, blur_type='iso_gaussian', sig=2.6, sig_min=0.2, sig_max=4.0, lambda_1=0.2, lambda_2=4.0, theta=0, lambda_min=0.2, lambda_max=4.0, noise=0.0, rgb_range=1 ): ''' # sig, sig_min and sig_max are used for isotropic Gaussian blurs During training phase (random=True): the width of the blur kernel is randomly selected from [sig_min, sig_max] During test phase (random=False): the width of the blur kernel is set to sig # lambda_1, lambda_2, theta, lambda_min and lambda_max are used for anisotropic Gaussian blurs During training phase (random=True): the eigenvalues of the covariance is randomly selected from [lambda_min, lambda_max] the angle value is randomly selected from [0, pi] During test phase (random=False): the eigenvalues of the covariance are set to lambda_1 and lambda_2 the angle value is set to theta ''' self.kernel_size = kernel_size self.scale = scale self.mode = mode self.noise = noise / (255 / rgb_range) self.rgb_range = rgb_range self.gen_kernel = Gaussin_Kernel( kernel_size=kernel_size, blur_type=blur_type, sig=sig, sig_min=sig_min, sig_max=sig_max, lambda_1=lambda_1, lambda_2=lambda_2, theta=theta, lambda_min=lambda_min, lambda_max=lambda_max ) self.blur = BatchBlur(kernel_size=kernel_size) self.bicubic = bicubic() def __call__(self, hr_tensor, random=True): with torch.no_grad(): # only downsampling if self.gen_kernel.blur_type == 'iso_gaussian' and self.gen_kernel.sig == 0: B, C, H, W = hr_tensor.size() hr_blured = hr_tensor.view(-1, C, H, W) b_kernels = None # gaussian blur + downsampling else: B, C, H, W = hr_tensor.size() b_kernels = self.gen_kernel(1, random) # B degradations b_kernels = b_kernels.expand(B,-1,-1) # blur hr_blured = self.blur(hr_tensor.view(B, -1, H, W), b_kernels) hr_blured = hr_blured.view(-1, C, H, W) # B, C, H, W # downsampling if self.mode == 'bicubic': lr_blured = self.bicubic(hr_blured, scale=1/self.scale) elif self.mode == 's-fold': lr_blured = hr_blured.view(-1, C, H//self.scale, self.scale, W//self.scale, self.scale)[:, :, :, 0, :, 0] # add noise if self.noise > 0: _, C, H_lr, W_lr = lr_blured.size() noise_level = torch.rand(1, 1, 1, 1).to(lr_blured.device) * self.noise if random else self.noise noise = torch.randn_like(lr_blured).view(-1, C, H_lr, W_lr).mul_(noise_level).view(-1, C, H_lr, W_lr) lr_blured.add_(noise) hr_blured = self.bicubic(lr_blured, scale= self.scale) lr_blured = utility.quantize(lr_blured, self.rgb_range) hr_blured = utility.quantize(hr_blured, self.rgb_range) return lr_blured.view(B, C, H//int(self.scale), W//int(self.scale)), hr_blured.view(B, C, H, W) ================================================ FILE: README.md ================================================ # Knowledge Distillation based Degradation Estimation for Blind Super-Resolution (ICLR2023) [Paper](https://arxiv.org/pdf/2211.16928.pdf) | [Project Page](https://github.com/Zj-BinXia/KDSR) | [pretrained models](https://drive.google.com/drive/folders/1_LyZDLu5dNIBaCSu7oB9w9d1SPf1pm8c?usp=sharing) #### News - **August 28, 2023:** For real-world SR tasks, we released a pretrained model [KDSR-GANV2](https://drive.google.com/file/d/1plvMt7VrOY9YLbWrpchOzi6t1wcqkzBl/view?usp=sharing) and [training files](KDSR-GAN/options/train_kdsrgan_x4STV2.yml) that is more focused on perception rather than distortion. - **Jan 28, 2023:** Training&Testing codes and pre-trained models are released!
> **Abstract:** *Blind image super-resolution (Blind-SR) aims to recover a high-resolution (HR) image from its corresponding low-resolution (LR) input image with unknown degradations. Most of the existing works design an explicit degradation estimator for each degradation to guide SR. However, it is infeasible to provide concrete labels of multiple degradation combinations (\eg, blur, noise, jpeg compression) to supervise the degradation estimator training. In addition, these special designs for certain degradation, such as blur, impedes the models from being generalized to handle different degradations. To this end, it is necessary to design an implicit degradation estimator that can extract discriminative degradation representation for all degradations without relying on the supervision of degradation ground-truth. In this paper, we propose a Knowledge Distillation based Blind-SR network (KDSR). It consists of a knowledge distillation based implicit degradation estimator network (KD-IDE) and an efficient SR network. To learn the KDSR model, we first train a teacher network: KD-IDE$_{T}$. It takes paired HR and LR patches as inputs and is optimized with the SR network jointly. Then, we further train a student network KD-IDE$_{S}$, which only takes LR images as input and learns to extract the same implicit degradation representation (IDR) as KD-IDE$_{T}$. In addition, to fully use extracted IDR, we design a simple, strong, and efficient IDR based dynamic convolution residual block (IDR-DCRB) to build an SR network. We conduct extensive experiments under classic and real-world degradation settings. The results show that KDSR achieves SOTA performance and can generalize to various degradation processes.*

--- ## Dependencies and Installation - Python >= 3.8 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html)) - [PyTorch >= 1.10](https://pytorch.org/) ### Installation 1. Clone repo ```bash git clone git@github.com:Zj-BinXia/KDSR.git ``` 2. If you want to train or test KDSR-GAN (ie, Real-world SR, trained with the same degradation model as Real-ESRGAN) ```bash cd KDSR-GAN ``` 3. If you want to train or test KDSR-classic (ie, classic degradation models, trained with the isotropic Gaussian Blur or anisotropic Gaussian blur and noises) ```bash cd KDSR-classic ``` **More details please see the README in folder of KDSR-GAN and KDSR-classic** --- ## BibTeX @InProceedings{xia2022knowledge, title={Knowledge Distillation based Degradation Estimation for Blind Super-Resolution}, author={Xia, Bin and Zhang, Yulun and Wang, Yitong and Tian, Yapeng and Yang, Wenming and Timofte, Radu and Van Gool, Luc}, journal={ICLR}, year={2023} } ## 📧 Contact If you have any question, please email `zjbinxia@gmail.com`.