import data.sirs_dataset as datasets
from data.image_folder import read_fns
from engine import Engine
from options.net_options.train_options import TrainOptions
from tools import mutils
res = engine.eval(eval_dataloader_real, dataset_name='testdata_real',
savedir=join(result_dir, 'real20'), suffix='real20')
print(res)
res = engine.eval(eval_dataloader_solidobject, dataset_name='testdata_solidobject',
savedir=join(result_dir, 'solidobject'), suffix='solidobject')
print(res)
res = engine.eval(eval_dataloader_postcard, dataset_name='testdata_postcard',
savedir=join(result_dir, 'postcard'), suffix='postcard')
print(res)
res = engine.eval(eval_dataloader_wild, dataset_name='testdata_wild',
savedir=join(result_dir, 'wild'), suffix='wild')
print(res)
explain line by line to a beginner
Assistant
User
Assistant
Certainly! Let's go through the code step by step:
Import Statements
Importing Libraries and Modules:
python
import os
from os.path import join
import torch.backends.cudnn as cudnn
import data.sirs_dataset as datasets
from data.image_folder import read_fns
from engine import Engine
from options.net_options.train_options import TrainOptions
from tools import mutils
These lines import the necessary libraries and modules.
os and join are used for handling file paths.
cudnn is a library for optimizing performance on NVIDIA GPUs.
datasets likely contains dataset classes and functions for data handling.
read_fns is a function to read filenames.
Engine might be the main class for running and evaluating the model.
TrainOptions is a class for handling command-line options for training.
mutils is a module containing miscellaneous utility functions.
Setting up options and configurations
Parsing Options:
python
opt = TrainOptions().parse()
This line parses training options from command-line arguments using the TrainOptions class and stores them in opt.
This line creates a path for saving evaluation results.
'./checkpoints' is the base directory.
opt.name is the experiment name or identifier.
mutils.get_formatted_time() provides a timestamp for organizing results.
Evaluation Loop
Evaluating the Datasets:
python
res = engine.eval(eval_dataloader_real, dataset_name='testdata_real',
savedir=join(result_dir, 'real20'), suffix='real20')
print(res)
res = engine.eval(eval_dataloader_solidobject, dataset_name='testdata_solidobject',
savedir=join(result_dir, 'solidobject'), suffix='solidobject')
print(res)
res = engine.eval(eval_dataloader_postcard, dataset_name='testdata_postcard',
savedir=join(result_dir, 'postcard'), suffix='postcard')
print(res)
res = engine.eval(eval_dataloader_wild, dataset_name='testdata_wild',
savedir=join(result_dir, 'wild'), suffix='wild')
print(res)
Each dataset (real, solidobject, postcard, wild) is evaluated using the engine.eval() method.
dataset_name provides a name for logging.
savedir specifies where to save the evaluation results.
suffix adds a suffix to the saved files.
print(res) prints the evaluation results to the console.
By breaking the code down this way, we can see that it's set up for evaluating different datasets using a pre-defined framework, while saving and possibly summarizing the results in specified directories.
class ReflectionSynthesis(object):
def init(self):
#(mingcv) Kernel Size of the Gaussian Blurry
self.kernel_sizes = [5, 7, 9, 11]
self.kernel_probs = [0.1, 0.2, 0.3, 0.4]
code
#(mingcv) Sigma of the Gaussian Blurry
self.sigma_range = [2, 5]
self.alpha_range = [0.8, 1.0]
self.beta_range = [0.4, 1.0]
def __call__(self, T_, R_):
T_ = np.asarray(T_, np.float32) / 255.
R_ = np.asarray(R_, np.float32) / 255.
kernel_size = np.random.choice(self.kernel_sizes, p=self.kernel_probs)
sigma = np.random.uniform(self.sigma_range[0], self.sigma_range[1])
kernel = cv2.getGaussianKernel(kernel_size, sigma)
kernel2d = np.dot(kernel, kernel.T)
for i in range(3):
R_[..., i] = convolve2d(R_[..., i], kernel2d, mode='same')
a = np.random.uniform(self.alpha_range[0], self.alpha_range[1])
b = np.random.uniform(self.beta_range[0], self.beta_range[1])
T, R = a * T_, b * R_
if random.random() < 0.7:
I = T + R - T * R
else:
I = T + R
if np.max(I) > 1:
m = I[I > 1]
m = (np.mean(m) - 1) * 1.3
I = np.clip(T + np.clip(R - m, 0, 1), 0, 1)
return T_, R_, I
if size is not None:
self.fns = self.fns[:size]
def align(self, x1, x2, x3):
h, w = x1.height, x1.width
h, w = h // 32 * 32, w // 32 * 32
x1 = x1.resize((w, h))
x2 = x2.resize((w, h))
x3 = x3.resize((w, h))
return x1, x2, x3
def __getitem__(self, index):
fn = self.fns[index]
t_img = Image.open(join(self.datadir, 'transmission_layer', fn)).convert('RGB')
r_img = Image.open(join(self.datadir, 'reflection_layer', fn)).convert('RGB')
m_img = Image.open(join(self.datadir, 'blended', fn)).convert('RGB')
if self.if_align:
t_img, r_img, m_img = self.align(t_img, r_img, m_img)
B = TF.to_tensor(t_img)
R = TF.to_tensor(r_img)
M = TF.to_tensor(m_img)
dic = {'input': M, 'target_t': B, 'fn': fn, 'real': True, 'target_r': R, 'target_r_hat': M - B}
return dic
def __len__(self):
if self.size is not None:
return min(len(self.fns), self.size)
else:
return len(self.fns)
class RealDataset(BaseDataset):
def init(self, datadir, fns=None, size=None):
super(RealDataset, self).init()
self.size = size
self.datadir = datadir
self.fns = fns or os.listdir(join(datadir))
code
if size is not None:
self.fns = self.fns[:size]
def align(self, x):
h, w = x.height, x.width
h, w = h // 32 * 32, w // 32 * 32
x = x.resize((w, h))
return x
def __getitem__(self, index):
fn = self.fns[index]
B = -1
m_img = Image.open(join(self.datadir, fn)).convert('RGB')
M = to_tensor(self.align(m_img))
data = {'input': M, 'target_t': B, 'fn': fn}
return data
def __len__(self):
if self.size is not None:
return min(len(self.fns), self.size)
else:
return len(self.fns)
class FusionDataset(BaseDataset):
def init(self, datasets, fusion_ratios=None, size=None):
self.datasets = datasets
self.size = size or sum([len(dataset) for dataset in datasets])
self.fusion_ratios = fusion_ratios or [1. / len(datasets)] * len(datasets)
print('[i] using a fusion dataset: %d %s imgs fused with ratio %s' % (
self.size, [len(dataset) for dataset in datasets], self.fusion_ratios))
code
def reset(self):
for dataset in self.datasets:
dataset.reset()
def __getitem__(self, index):
residual = 1
for i, ratio in enumerate(self.fusion_ratios):
if random.random() < ratio / residual or i == len(self.fusion_ratios) - 1:
dataset = self.datasets[i]
return dataset[index % len(dataset)]
residual -= ratio
def __len__(self):
return self.size
Certainly! This script defines several custom datasets and utility classes for handling synthetic reflection datasets in deep learning experiments. Let's break down each class and its methods:
Class: ReflectionSynthesis
This class synthesizes reflection images by blending transmission and reflection layers.
Constructor:
python
def __init__(self):
self.kernel_sizes = [5, 7, 9, 11] # Kernel sizes for Gaussian blur
self.kernel_probs = [0.1, 0.2, 0.3, 0.4] # Probabilities for each kernel size
self.sigma_range = [2, 5] # Range for Gaussian blur sigma
self.alpha_range = [0.8, 1.0] # Range for alpha blending
self.beta_range = [0.4, 1.0] # Range for beta blending
Call Method:
python
def __call__(self, T_, R_):
T_ = np.asarray(T_, np.float32) / 255. # Normalize transmission layer
R_ = np.asarray(R_, np.float32) / 255. # Normalize reflection layer
kernel_size = np.random.choice(self.kernel_sizes, p=self.kernel_probs)
sigma = np.random.uniform(self.sigma_range[0], self.sigma_range[1])
kernel = cv2.getGaussianKernel(kernel_size, sigma)
kernel2d = np.dot(kernel, kernel.T)
for i in range(3):
R_[..., i] = convolve2d(R_[..., i], kernel2d, mode='same') # Apply Gaussian blur on reflection
a = np.random.uniform(self.alpha_range[0], self.alpha_range[1])
b = np.random.uniform(self.beta_range[0], self.beta_range[1])
T, R = a * T_, b * R_ # Alpha and beta blending
# Randomly decide between different blending formulas
if random.random() < 0.7:
I = T + R - T * R
else:
I = T + R
if np.max(I) > 1:
m = I[I > 1]
m = (np.mean(m) - 1) * 1.3
I = np.clip(T + np.clip(R - m, 0, 1), 0, 1)
return T_, R_, I
Class: DataLoader
A custom data loader that extends PyTorch's DataLoader.
A dataset for testing DSR with additional functionalities.
Constructor:
python
def __init__(self, datadir, fns=None, size=None, enable_transforms=False, unaligned_transforms=False, round_factor=1, flag=None, if_align=False):
super(DSRTestDataset, self).__init__()
self.size = size
self.datadir = datadir
self.fns = fns or os.listdir(join(datadir, 'blended'))
self.enable_transforms = enable_transforms
self.unaligned_transforms = unaligned_transforms
self.round_factor = round_factor
self.flag = flag
self.if_align = if_align
if size is not None:
self.fns = self.fns[:size]
Align Method:
python
def align(self, x1, x2):
h, w = x1.height, x1.width
h, w = h // 32 * 32, w // 32 * 32
x1 = x1.resize((w, h))
x2 = x2.resize((w, h))
return x1, x2
Get Item Method:
python
def __getitem__(self, index):
fn = self.fns[index]
t_img = Image.open(join(self.datadir, 'transmission_layer', fn)).convert('RGB')
m_img = Image.open(join(self.datadir, 'blended', fn)).convert('RGB')
if self.if_align:
t_img, m_img = self.align(t_img, m_img)
if self.enable_transforms:
t_img, m_img = paired_data_transforms(t_img, m_img, self.unaligned_transforms)
B = TF.to_tensor(t_img)
M = TF.to_tensor(m_img)
dic = {'input': M, 'target_t': B, 'fn': fn, 'real': True, 'target_r': M - B}
if self.flag is not None:
dic.update(self.flag)
return dic
Class: SIRTestDataset
A dataset for evaluating the SIR (Single Image Reflection) method.
Constructor:
python
def __init__(self, datadir, fns=None, size=None, if_align=False):
super(SIRTestDataset, self).__init__()
self.size = size
self.datadir = datadir
self.fns = fns or os.listdir(join(datadir, 'blended'))
self.if_align = if_align
if size is not None:
self.fns = self.fns[:size]
Align Method:
python
def align(self, x1, x2, x3):
h, w = x1.height, x1.width
h, w = h // 32 * 32, w // 32 * 32
x1 = x1.resize((w, h))
x2 = x2.resize((w, h))
x3 = x3.resize((w, h))
return x1, x2, x3
Get Item Method:
python
def __getitem__(self, index):
fn = self.fns[index]
t_img = Image.open(join(self.datadir, 'transmission_layer', fn)).convert('RGB')
r_img = Image.open(join(self.datadir, 'reflection_layer', fn)).convert('RGB')
m_img = Image.open(join(self.datadir, 'blended', fn)).convert('RGB')
if self.if_align:
t_img, r_img, m_img = self.align(t_img, r_img, m_img)
B = TF.to_tensor(t_img)
R = TF.to_tensor(r_img)
M = TF.to_tensor(m_img)
dic = {'input': M, 'target_t': B, 'fn': fn, 'real': True, 'target_r': R, 'target_r_hat': M - B}
return dic
Length Method:
python
def __len__(self):
if self.size is not None:
return min(len(self.fns), self.size)
else:
return len(self.fns)
Class: RealDataset
A dataset for real-world images without ground truth reflection/transmission layers.
Constructor:
python
def __init__(self, datadir, fns=None, size=None):
super(RealDataset, self).__init__()
self.size = size
self.datadir = datadir
self.fns = fns or os.listdir(join(datadir))
if size is not None:
self.fns = self.fns[:size]
Align Method:
python
def align(self, x):
h, w = x.height, x.width
h, w = h // 32 * 32, w // 32 * 32
x = x.resize((w, h))
return x
Get Item Method:
python
def __getitem__(self, index):
fn = self.fns[index]
B = -1
m_img = Image.open(join(self.datadir, fn)).convert('RGB')
M = to_tensor(self.align(m_img))
data = {'input': M, 'target_t': B, 'fn': fn}
return data
Length Method:
python
def __len__(self):
if self.size is not None:
return min(len(self.fns), self.size)
else:
return len(self.fns)
Class: FusionDataset
This class combines multiple datasets based on given ratios.
Constructor:
python
def __init__(self, datasets, fusion_ratios=None, size=None):
self.datasets = datasets
self.size = size or sum([len(dataset) for dataset in datasets])
self.fusion_ratios = fusion_ratios or [1. / len(datasets)] * len(datasets)
print('[i] using a fusion dataset: %d %s imgs fused with ratio %s' % (
self.size, [len(dataset) for dataset in datasets], self.fusion_ratios))
Reset Method:
python
def reset(self):
for dataset in self.datasets:
dataset.reset()
Get Item Method:
python
def __getitem__(self, index):
residual = 1
for i, ratio in enumerate(self.fusion_ratios):
if random.random() < ratio / residual or i == len(self.fusion_ratios) - 1:
dataset = self.datasets[i]
return dataset[index % len(dataset)]
residual -= ratio
Length Method:
python
def __len__(self):
return self.size
Overall, these classes are designed for handling and synthesizing reflection datasets, supporting both training and testing phases. They are tailored for deep learning tasks like image reflection removal.
def __len__(self):
if self.size is not None:
return min(max(len(self.B_paths), len(self.R_paths)), self.size)
else:
return max(len(self.B_paths), len(self.R_paths))
Length Method:
python
def __len__(self):
if self.size is not None:
return min(len(self.fns), self.size)
else:
return len(self.fns)