id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
167,868 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
to_2tuple = _ntuple(2)
The provided code snippet includes necessary dependencies for implementing the `fspecial` function. Write a Python function `def fspecial(size=None, sigma=None, channels=1, filter_type='gaussian')` to solve the following problem:
r""" Function same as 'fspecial' in MATLAB, only support gaussian now. Args: size (int or tuple): size of window sigma (float): sigma of gaussian channels (int): channels of output
Here is the function:
def fspecial(size=None, sigma=None, channels=1, filter_type='gaussian'):
r""" Function same as 'fspecial' in MATLAB, only support gaussian now.
Args:
size (int or tuple): size of window
sigma (float): sigma of gaussian
channels (int): channels of output
"""
if filter_type == 'gaussian':
shape = to_2tuple(size)
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2. * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
h = torch.from_numpy(h).float().repeat(channels, 1, 1, 1)
return h
else:
raise NotImplementedError(f'Only support gaussian filter now, got {filter_type}') | r""" Function same as 'fspecial' in MATLAB, only support gaussian now. Args: size (int or tuple): size of window sigma (float): sigma of gaussian channels (int): channels of output |
167,869 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
def conv2d(input, weight, bias=None, stride=1, padding='same', dilation=1, groups=1):
"""Matlab like conv2, weights needs to be flipped.
Args:
input (tensor): (b, c, h, w)
weight (tensor): (out_ch, in_ch, kh, kw), conv weight
bias (bool or None): bias
stride (int or tuple): conv stride
padding (str): padding mode
dilation (int): conv dilation
"""
kernel_size = weight.shape[2:]
pad_func = ExactPadding2d(kernel_size, stride, dilation, mode=padding)
weight = torch.flip(weight, dims=(-1, -2))
return F.conv2d(pad_func(input), weight, bias, stride, dilation=dilation, groups=groups)
def imfilter(input, weight, bias=None, stride=1, padding='same', dilation=1, groups=1):
"""imfilter same as matlab.
Args:
input (tensor): (b, c, h, w) tensor to be filtered
weight (tensor): (out_ch, in_ch, kh, kw) filter kernel
padding (str): padding mode
dilation (int): dilation of conv
groups (int): groups of conv
"""
kernel_size = weight.shape[2:]
pad_func = ExactPadding2d(kernel_size, stride, dilation, mode=padding)
return F.conv2d(pad_func(input), weight, bias, stride, dilation=dilation, groups=groups)
def filter2(input, weight, shape='same'):
if shape == 'same':
return imfilter(input, weight, groups=input.shape[1])
elif shape == 'valid':
return F.conv2d(input, weight, stride=1, padding=0, groups=input.shape[1])
else:
raise NotImplementedError(f'Shape type {shape} is not implemented.') | null |
167,870 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
def dct(x, norm=None):
"""
Discrete Cosine Transform, Type II (a.k.a. the DCT)
For the meaning of the parameter `norm`, see:
https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
Args:
x: the input signal
norm: the normalization, None or 'ortho'
Return:
the DCT-II of the signal over the last dimension
"""
x_shape = x.shape
N = x_shape[-1]
x = x.contiguous().view(-1, N)
v = torch.cat([x[:, ::2], x[:, 1::2].flip([1])], dim=-1)
Vc = torch.view_as_real(torch.fft.fft(v, dim=-1))
k = -torch.arange(N, dtype=x.dtype, device=x.device)[None, :] * np.pi / (2 * N)
W_r = torch.cos(k)
W_i = torch.sin(k)
V = Vc[:, :, 0] * W_r - Vc[:, :, 1] * W_i
if norm == 'ortho':
V[:, 0] /= np.sqrt(N) * 2
V[:, 1:] /= np.sqrt(N / 2) * 2
V = 2 * V.view(*x_shape)
return V
The provided code snippet includes necessary dependencies for implementing the `dct2d` function. Write a Python function `def dct2d(x, norm='ortho')` to solve the following problem:
2-dimentional Discrete Cosine Transform, Type II (a.k.a. the DCT) For the meaning of the parameter `norm`, see: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html :param x: the input signal :param norm: the normalization, None or 'ortho' :return: the DCT-II of the signal over the last 2 dimensions
Here is the function:
def dct2d(x, norm='ortho'):
"""
2-dimentional Discrete Cosine Transform, Type II (a.k.a. the DCT)
For the meaning of the parameter `norm`, see:
https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
:param x: the input signal
:param norm: the normalization, None or 'ortho'
:return: the DCT-II of the signal over the last 2 dimensions
"""
X1 = dct(x, norm=norm)
X2 = dct(X1.transpose(-1, -2), norm=norm)
return X2.transpose(-1, -2) | 2-dimentional Discrete Cosine Transform, Type II (a.k.a. the DCT) For the meaning of the parameter `norm`, see: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html :param x: the input signal :param norm: the normalization, None or 'ortho' :return: the DCT-II of the signal over the last 2 dimensions |
167,871 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
The provided code snippet includes necessary dependencies for implementing the `fitweibull` function. Write a Python function `def fitweibull(x, iters=50, eps=1e-2)` to solve the following problem:
Simulate wblfit function in matlab. ref: https://github.com/mlosch/python-weibullfit/blob/master/weibull/backend_pytorch.py Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation. :param x (tensor): (B, N), batch of samples from an (unknown) distribution. Each value must satisfy x > 0. :param iters: Maximum number of iterations :param eps: Stopping criterion. Fit is stopped ff the change within two iterations is smaller than eps. :param use_cuda: Use gpu :return: Tuple (Shape, Scale) which can be (NaN, NaN) if a fit is impossible. Impossible fits may be due to 0-values in x.
Here is the function:
def fitweibull(x, iters=50, eps=1e-2):
"""Simulate wblfit function in matlab.
ref: https://github.com/mlosch/python-weibullfit/blob/master/weibull/backend_pytorch.py
Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation.
:param x (tensor): (B, N), batch of samples from an (unknown) distribution. Each value must satisfy x > 0.
:param iters: Maximum number of iterations
:param eps: Stopping criterion. Fit is stopped ff the change within two iterations is smaller than eps.
:param use_cuda: Use gpu
:return: Tuple (Shape, Scale) which can be (NaN, NaN) if a fit is impossible.
Impossible fits may be due to 0-values in x.
"""
ln_x = torch.log(x)
k = 1.2 / torch.std(ln_x, dim=1, keepdim=True)
k_t_1 = k
for t in range(iters):
# Partial derivative df/dk
x_k = x**k.repeat(1, x.shape[1])
x_k_ln_x = x_k * ln_x
ff = torch.sum(x_k_ln_x, dim=-1, keepdim=True)
fg = torch.sum(x_k, dim=-1, keepdim=True)
f1 = torch.mean(ln_x, dim=-1, keepdim=True)
f = ff / fg - f1 - (1.0 / k)
ff_prime = torch.sum(x_k_ln_x * ln_x, dim=-1, keepdim=True)
fg_prime = ff
f_prime = (ff_prime / fg - (ff / fg * fg_prime / fg)) + (1. / (k * k))
# Newton-Raphson method k = k - f(k;x)/f'(k;x)
k = k - f / f_prime
error = torch.abs(k - k_t_1).max().item()
if error < eps:
break
k_t_1 = k
# Lambda (scale) can be calculated directly
lam = torch.mean(x**k.repeat(1, x.shape[1]), dim=-1, keepdim=True)**(1.0 / k)
return torch.cat((k, lam), dim=1) # Shape (SC), Scale (FE) | Simulate wblfit function in matlab. ref: https://github.com/mlosch/python-weibullfit/blob/master/weibull/backend_pytorch.py Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation. :param x (tensor): (B, N), batch of samples from an (unknown) distribution. Each value must satisfy x > 0. :param iters: Maximum number of iterations :param eps: Stopping criterion. Fit is stopped ff the change within two iterations is smaller than eps. :param use_cuda: Use gpu :return: Tuple (Shape, Scale) which can be (NaN, NaN) if a fit is impossible. Impossible fits may be due to 0-values in x. |
167,872 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
def cov(tensor, rowvar=True, bias=False):
r"""Estimate a covariance matrix (np.cov)
Ref: https://gist.github.com/ModarTensai/5ab449acba9df1a26c12060240773110
"""
tensor = tensor if rowvar else tensor.transpose(-1, -2)
correction = int(not bias) if tensor.shape[-1] > 1 else 0
return torch.cov(tensor, correction=correction)
The provided code snippet includes necessary dependencies for implementing the `nancov` function. Write a Python function `def nancov(x)` to solve the following problem:
r"""Calculate nancov for batched tensor, rows that contains nan value will be removed. Args: x (tensor): (B, row_num, feat_dim) Return: cov (tensor): (B, feat_dim, feat_dim)
Here is the function:
def nancov(x):
r"""Calculate nancov for batched tensor, rows that contains nan value
will be removed.
Args:
x (tensor): (B, row_num, feat_dim)
Return:
cov (tensor): (B, feat_dim, feat_dim)
"""
assert len(x.shape) == 3, f'Shape of input should be (batch_size, row_num, feat_dim), but got {x.shape}'
b, rownum, feat_dim = x.shape
nan_mask = torch.isnan(x).any(dim=2, keepdim=True)
cov_x = []
for i in range(b):
x_no_nan = x[i].masked_select(~nan_mask[i]).reshape(-1, feat_dim)
cov_x.append(cov(x_no_nan, rowvar=False))
return torch.stack(cov_x) | r"""Calculate nancov for batched tensor, rows that contains nan value will be removed. Args: x (tensor): (B, row_num, feat_dim) Return: cov (tensor): (B, feat_dim, feat_dim) |
167,873 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
The provided code snippet includes necessary dependencies for implementing the `nanmean` function. Write a Python function `def nanmean(v, *args, inplace=False, **kwargs)` to solve the following problem:
r"""nanmean same as matlab function: calculate mean values by removing all nan.
Here is the function:
def nanmean(v, *args, inplace=False, **kwargs):
r"""nanmean same as matlab function: calculate mean values by removing all nan.
"""
if not inplace:
v = v.clone()
is_nan = torch.isnan(v)
v[is_nan] = 0
return v.sum(*args, **kwargs) / (~is_nan).float().sum(*args, **kwargs) | r"""nanmean same as matlab function: calculate mean values by removing all nan. |
167,874 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
to_2tuple = _ntuple(2)
The provided code snippet includes necessary dependencies for implementing the `im2col` function. Write a Python function `def im2col(x, kernel, mode='sliding')` to solve the following problem:
r"""simple im2col as matlab Args: x (Tensor): shape (b, c, h, w) kernel (int): kernel size mode (string): - sliding (default): rearranges sliding image neighborhoods of kernel size into columns with no zero-padding - distinct: rearranges discrete image blocks of kernel size into columns, zero pad right and bottom if necessary Return: flatten patch (Tensor): (b, h * w / kernel **2, kernel * kernel)
Here is the function:
def im2col(x, kernel, mode='sliding'):
r"""simple im2col as matlab
Args:
x (Tensor): shape (b, c, h, w)
kernel (int): kernel size
mode (string):
- sliding (default): rearranges sliding image neighborhoods of kernel size into columns with no zero-padding
- distinct: rearranges discrete image blocks of kernel size into columns, zero pad right and bottom if necessary
Return:
flatten patch (Tensor): (b, h * w / kernel **2, kernel * kernel)
"""
b, c, h, w = x.shape
kernel = to_2tuple(kernel)
if mode == 'sliding':
stride = 1
elif mode == 'distinct':
stride = kernel
h2 = math.ceil(h / stride[0])
w2 = math.ceil(w / stride[1])
pad_row = (h2 - 1) * stride[0] + kernel[0] - h
pad_col = (w2 - 1) * stride[1] + kernel[1] - w
x = F.pad(x, (0, pad_col, 0, pad_row))
else:
raise NotImplementedError(f'Type {mode} is not implemented yet.')
patches = F.unfold(x, kernel, dilation=1, stride=stride)
b, _, pnum = patches.shape
patches = patches.transpose(1, 2).reshape(b, pnum, -1)
return patches | r"""simple im2col as matlab Args: x (Tensor): shape (b, c, h, w) kernel (int): kernel size mode (string): - sliding (default): rearranges sliding image neighborhoods of kernel size into columns with no zero-padding - distinct: rearranges discrete image blocks of kernel size into columns, zero pad right and bottom if necessary Return: flatten patch (Tensor): (b, h * w / kernel **2, kernel * kernel) |
167,875 | import math
import numpy as np
import torch
import torch.nn.functional as F
from .padding import ExactPadding2d, to_2tuple, symm_pad
to_2tuple = _ntuple(2)
def symm_pad(im: torch.Tensor, padding: Tuple[int, int, int, int]):
"""Symmetric padding same as tensorflow.
Ref: https://discuss.pytorch.org/t/symmetric-padding/19866/3
"""
h, w = im.shape[-2:]
left, right, top, bottom = padding
x_idx = np.arange(-left, w + right)
y_idx = np.arange(-top, h + bottom)
def reflect(x, minx, maxx):
""" Reflects an array around two points making a triangular waveform that ramps up
and down, allowing for pad lengths greater than the input length """
rng = maxx - minx
double_rng = 2 * rng
mod = np.fmod(x - minx, double_rng)
normed_mod = np.where(mod < 0, mod + double_rng, mod)
out = np.where(normed_mod >= rng, double_rng - normed_mod, normed_mod) + minx
return np.array(out, dtype=x.dtype)
x_pad = reflect(x_idx, -0.5, w - 0.5)
y_pad = reflect(y_idx, -0.5, h - 0.5)
xx, yy = np.meshgrid(x_pad, y_pad)
return im[..., yy, xx]
The provided code snippet includes necessary dependencies for implementing the `blockproc` function. Write a Python function `def blockproc(x, kernel, fun, border_size=None, pad_partial=False, pad_method='zero', **func_args)` to solve the following problem:
r"""blockproc function like matlab Difference: - Partial blocks is discarded (if exist) for fast GPU process. Args: x (tensor): shape (b, c, h, w) kernel (int or tuple): block size func (function): function to process each block border_size (int or tuple): border pixels to each block pad_partial: pad partial blocks to make them full-sized, default False pad_method: [zero, replicate, symmetric] how to pad partial block when pad_partial is set True Return: results (tensor): concatenated results of each block
Here is the function:
def blockproc(x, kernel, fun, border_size=None, pad_partial=False, pad_method='zero', **func_args):
r"""blockproc function like matlab
Difference:
- Partial blocks is discarded (if exist) for fast GPU process.
Args:
x (tensor): shape (b, c, h, w)
kernel (int or tuple): block size
func (function): function to process each block
border_size (int or tuple): border pixels to each block
pad_partial: pad partial blocks to make them full-sized, default False
pad_method: [zero, replicate, symmetric] how to pad partial block when pad_partial is set True
Return:
results (tensor): concatenated results of each block
"""
assert len(x.shape) == 4, f'Shape of input has to be (b, c, h, w) but got {x.shape}'
kernel = to_2tuple(kernel)
if pad_partial:
b, c, h, w = x.shape
stride = kernel
h2 = math.ceil(h / stride[0])
w2 = math.ceil(w / stride[1])
pad_row = (h2 - 1) * stride[0] + kernel[0] - h
pad_col = (w2 - 1) * stride[1] + kernel[1] - w
padding = (0, pad_col, 0, pad_row)
if pad_method == 'zero':
x = F.pad(x, padding, mode='constant')
elif pad_method == 'symmetric':
x = symm_pad(x, padding)
else:
x = F.pad(x, padding, mode=pad_method)
if border_size is not None:
raise NotImplementedError('Blockproc with border is not implemented yet')
else:
b, c, h, w = x.shape
block_size_h, block_size_w = kernel
num_block_h = math.floor(h / block_size_h)
num_block_w = math.floor(w / block_size_w)
# extract blocks in (row, column) manner, i.e., stored with column first
blocks = F.unfold(x, kernel, stride=kernel)
blocks = blocks.reshape(b, c, *kernel, num_block_h, num_block_w)
blocks = blocks.permute(5, 4, 0, 1, 2, 3).reshape(num_block_h * num_block_w * b, c, *kernel)
results = fun(blocks, func_args)
results = results.reshape(num_block_h * num_block_w, b, *results.shape[1:]).transpose(0, 1)
return results | r"""blockproc function like matlab Difference: - Partial blocks is discarded (if exist) for fast GPU process. Args: x (tensor): shape (b, c, h, w) kernel (int or tuple): block size func (function): function to process each block border_size (int or tuple): border pixels to each block pad_partial: pad partial blocks to make them full-sized, default False pad_method: [zero, replicate, symmetric] how to pad partial block when pad_partial is set True Return: results (tensor): concatenated results of each block |
167,876 | import math
import typing
import torch
from torch.nn import functional as F
def nearest_contribution(x: torch.Tensor) -> torch.Tensor:
range_around_0 = torch.logical_and(x.gt(-0.5), x.le(0.5))
cont = range_around_0.to(dtype=x.dtype)
return cont | null |
167,877 | import math
import typing
import torch
from torch.nn import functional as F
def linear_contribution(x: torch.Tensor) -> torch.Tensor:
ax = x.abs()
range_01 = ax.le(1)
cont = (1 - ax) * range_01.to(dtype=x.dtype)
return cont | null |
167,878 | import math
import typing
import torch
from torch.nn import functional as F
def cubic_contribution(x: torch.Tensor, a: float = -0.5) -> torch.Tensor:
ax = x.abs()
ax2 = ax * ax
ax3 = ax * ax2
range_01 = ax.le(1)
range_12 = torch.logical_and(ax.gt(1), ax.le(2))
cont_01 = (a + 2) * ax3 - (a + 3) * ax2 + 1
cont_01 = cont_01 * range_01.to(dtype=x.dtype)
cont_12 = (a * ax3) - (5 * a * ax2) + (8 * a * ax) - (4 * a)
cont_12 = cont_12 * range_12.to(dtype=x.dtype)
cont = cont_01 + cont_12
return cont
The provided code snippet includes necessary dependencies for implementing the `discrete_kernel` function. Write a Python function `def discrete_kernel(kernel: str, scale: float, antialiasing: bool = True) -> torch.Tensor` to solve the following problem:
For downsampling with integer scale only.
Here is the function:
def discrete_kernel(kernel: str, scale: float, antialiasing: bool = True) -> torch.Tensor:
'''
For downsampling with integer scale only.
'''
downsampling_factor = int(1 / scale)
if kernel == 'cubic':
kernel_size_orig = 4
else:
raise ValueError('Pass!')
if antialiasing:
kernel_size = kernel_size_orig * downsampling_factor
else:
kernel_size = kernel_size_orig
if downsampling_factor % 2 == 0:
a = kernel_size_orig * (0.5 - 1 / (2 * kernel_size))
else:
kernel_size -= 1
a = kernel_size_orig * (0.5 - 1 / (kernel_size + 1))
with torch.no_grad():
r = torch.linspace(-a, a, steps=kernel_size)
k = cubic_contribution(r).view(-1, 1)
k = torch.matmul(k, k.t())
k /= k.sum()
return k | For downsampling with integer scale only. |
167,879 | import math
import typing
import torch
from torch.nn import functional as F
def reshape_input(x: torch.Tensor) -> typing.Tuple[torch.Tensor, _I, _I, int, int]:
if x.dim() == 4:
b, c, h, w = x.size()
elif x.dim() == 3:
c, h, w = x.size()
b = None
elif x.dim() == 2:
h, w = x.size()
b = c = None
else:
raise ValueError('{}-dim Tensor is not supported!'.format(x.dim()))
x = x.view(-1, 1, h, w)
return x, b, c, h, w
def reshape_output(x: torch.Tensor, b: _I, c: _I) -> torch.Tensor:
rh = x.size(-2)
rw = x.size(-1)
# Back to the original dimension
if b is not None:
x = x.view(b, c, rh, rw) # 4-dim
else:
if c is not None:
x = x.view(c, rh, rw) # 3-dim
else:
x = x.view(rh, rw) # 2-dim
return x
def cast_input(x: torch.Tensor) -> typing.Tuple[torch.Tensor, _D]:
if x.dtype != torch.float32 or x.dtype != torch.float64:
dtype = x.dtype
x = x.float()
else:
dtype = None
return x, dtype
def cast_output(x: torch.Tensor, dtype: _D) -> torch.Tensor:
if dtype is not None:
if not dtype.is_floating_point:
x = x - x.detach() + x.round()
# To prevent over/underflow when converting types
if dtype is torch.uint8:
x = x.clamp(0, 255)
x = x.to(dtype=dtype)
return x
def resize_1d(x: torch.Tensor,
dim: int,
size: int,
scale: float,
kernel: str = 'cubic',
sigma: float = 2.0,
padding_type: str = 'reflect',
antialiasing: bool = True) -> torch.Tensor:
'''
Args:
x (torch.Tensor): A torch.Tensor of dimension (B x C, 1, H, W).
dim (int):
scale (float):
size (int):
Return:
'''
# Identity case
if scale == 1:
return x
# Default bicubic kernel with antialiasing (only when downsampling)
if kernel == 'cubic':
kernel_size = 4
else:
kernel_size = math.floor(6 * sigma)
if antialiasing and (scale < 1):
antialiasing_factor = scale
kernel_size = math.ceil(kernel_size / antialiasing_factor)
else:
antialiasing_factor = 1
# We allow margin to both sizes
kernel_size += 2
# Weights only depend on the shape of input and output,
# so we do not calculate gradients here.
with torch.no_grad():
pos = torch.linspace(
0,
size - 1,
steps=size,
dtype=x.dtype,
device=x.device,
)
pos = (pos + 0.5) / scale - 0.5
base = pos.floor() - (kernel_size // 2) + 1
dist = pos - base
weight = get_weight(
dist,
kernel_size,
kernel=kernel,
sigma=sigma,
antialiasing_factor=antialiasing_factor,
)
pad_pre, pad_post, base = get_padding(base, kernel_size, x.size(dim))
# To backpropagate through x
x_pad = padding(x, dim, pad_pre, pad_post, padding_type=padding_type)
unfold = reshape_tensor(x_pad, dim, kernel_size)
# Subsampling first
if dim == 2 or dim == -2:
sample = unfold[..., base, :]
weight = weight.view(1, kernel_size, sample.size(2), 1)
else:
sample = unfold[..., base]
weight = weight.view(1, kernel_size, 1, sample.size(3))
# Apply the kernel
x = sample * weight
x = x.sum(dim=1, keepdim=True)
return x
def downsampling_2d(x: torch.Tensor, k: torch.Tensor, scale: int, padding_type: str = 'reflect') -> torch.Tensor:
c = x.size(1)
k_h = k.size(-2)
k_w = k.size(-1)
k = k.to(dtype=x.dtype, device=x.device)
k = k.view(1, 1, k_h, k_w)
k = k.repeat(c, c, 1, 1)
e = torch.eye(c, dtype=k.dtype, device=k.device, requires_grad=False)
e = e.view(c, c, 1, 1)
k = k * e
pad_h = (k_h - scale) // 2
pad_w = (k_w - scale) // 2
x = padding(x, -2, pad_h, pad_h, padding_type=padding_type)
x = padding(x, -1, pad_w, pad_w, padding_type=padding_type)
y = F.conv2d(x, k, padding=0, stride=scale)
return y
The provided code snippet includes necessary dependencies for implementing the `imresize` function. Write a Python function `def imresize(x: torch.Tensor, scale: typing.Optional[float] = None, sizes: typing.Optional[typing.Tuple[int, int]] = None, kernel: typing.Union[str, torch.Tensor] = 'cubic', sigma: float = 2, rotation_degree: float = 0, padding_type: str = 'reflect', antialiasing: bool = True) -> torch.Tensor` to solve the following problem:
Args: x (torch.Tensor): scale (float): sizes (tuple(int, int)): kernel (str, default='cubic'): sigma (float, default=2): rotation_degree (float, default=0): padding_type (str, default='reflect'): antialiasing (bool, default=True): Return: torch.Tensor:
Here is the function:
def imresize(x: torch.Tensor,
scale: typing.Optional[float] = None,
sizes: typing.Optional[typing.Tuple[int, int]] = None,
kernel: typing.Union[str, torch.Tensor] = 'cubic',
sigma: float = 2,
rotation_degree: float = 0,
padding_type: str = 'reflect',
antialiasing: bool = True) -> torch.Tensor:
"""
Args:
x (torch.Tensor):
scale (float):
sizes (tuple(int, int)):
kernel (str, default='cubic'):
sigma (float, default=2):
rotation_degree (float, default=0):
padding_type (str, default='reflect'):
antialiasing (bool, default=True):
Return:
torch.Tensor:
"""
if scale is None and sizes is None:
raise ValueError('One of scale or sizes must be specified!')
if scale is not None and sizes is not None:
raise ValueError('Please specify scale or sizes to avoid conflict!')
x, b, c, h, w = reshape_input(x)
if sizes is None and scale is not None:
'''
# Check if we can apply the convolution algorithm
scale_inv = 1 / scale
if isinstance(kernel, str) and scale_inv.is_integer():
kernel = discrete_kernel(kernel, scale, antialiasing=antialiasing)
elif isinstance(kernel, torch.Tensor) and not scale_inv.is_integer():
raise ValueError(
'An integer downsampling factor '
'should be used with a predefined kernel!'
)
'''
# Determine output size
sizes = (math.ceil(h * scale), math.ceil(w * scale))
scales = (scale, scale)
if scale is None and sizes is not None:
scales = (sizes[0] / h, sizes[1] / w)
x, dtype = cast_input(x)
if isinstance(kernel, str) and sizes is not None:
# Core resizing module
x = resize_1d(
x,
-2,
size=sizes[0],
scale=scales[0],
kernel=kernel,
sigma=sigma,
padding_type=padding_type,
antialiasing=antialiasing)
x = resize_1d(
x,
-1,
size=sizes[1],
scale=scales[1],
kernel=kernel,
sigma=sigma,
padding_type=padding_type,
antialiasing=antialiasing)
elif isinstance(kernel, torch.Tensor) and scale is not None:
x = downsampling_2d(x, kernel, scale=int(1 / scale))
x = reshape_output(x, b, c)
x = cast_output(x, dtype)
return x | Args: x (torch.Tensor): scale (float): sizes (tuple(int, int)): kernel (str, default='cubic'): sigma (float, default=2): rotation_degree (float, default=0): padding_type (str, default='reflect'): antialiasing (bool, default=True): Return: torch.Tensor: |
167,880 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
def prepare_grid(m, n):
x = np.linspace(-(m // 2) / (m / 2), (m // 2) / (m / 2) - (1 - m % 2) * 2 / m, num=m)
y = np.linspace(-(n // 2) / (n / 2), (n // 2) / (n / 2) - (1 - n % 2) * 2 / n, num=n)
xv, yv = np.meshgrid(y, x)
angle = np.arctan2(yv, xv)
rad = np.sqrt(xv**2 + yv**2)
rad[m // 2][n // 2] = rad[m // 2][n // 2 - 1]
log_rad = np.log2(rad)
return log_rad, angle | null |
167,881 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
def rcosFn(width, position):
N = 256 # abritrary
X = np.pi * np.array(range(-N - 1, 2)) / 2 / N
Y = np.cos(X)**2
Y[0] = Y[1]
Y[N + 2] = Y[N + 1]
X = position + 2 * width / np.pi * (X + np.pi / 4)
return X, Y | null |
167,882 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
def pointOp(im, Y, X):
out = np.interp(im.flatten(), X, Y)
return np.reshape(out, im.shape) | null |
167,883 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
def getlist(coeff):
straight = [bands for scale in coeff[1:-1] for bands in scale]
straight = [coeff[0]] + straight + [coeff[-1]]
return straight | null |
167,884 | from scipy import stats
import numpy as np
from pyiqa.utils.registry import METRIC_REGISTRY
def calculate_2afc_score(d0, d1, gts, **kwargs):
scores = (d0 < d1) * (1 - gts) + (d0 > d1) * gts + (d0 == d1) * 0.5
return np.mean(scores) | null |
167,885 | from scipy import stats
from scipy.optimize import curve_fit
import numpy as np
from pyiqa.utils.registry import METRIC_REGISTRY
def fit_curve(x, y, curve_type='logistic_4params'):
r'''Fit the scale of predict scores to MOS scores using logistic regression suggested by VQEG.
The function with 4 params is more commonly used.
The 5 params function takes from DBCNN:
- https://github.com/zwx8981/DBCNN/blob/master/dbcnn/tools/verify_performance.m
'''
assert curve_type in [
'logistic_4params', 'logistic_5params'], f'curve type should be in [logistic_4params, logistic_5params], but got {curve_type}.'
betas_init_4params = [np.max(y), np.min(y), np.mean(x), np.std(x) / 4.]
def logistic_4params(x, beta1, beta2, beta3, beta4):
yhat = (beta1 - beta2) / (1 + np.exp(- (x - beta3) / beta4)) + beta2
return yhat
betas_init_5params = [10, 0, np.mean(y), 0.1, 0.1]
def logistic_5params(x, beta1, beta2, beta3, beta4, beta5):
logistic_part = 0.5 - 1. / (1 + np.exp(beta2 * (x - beta3)))
yhat = beta1 * logistic_part + beta4 * x + beta5
return yhat
if curve_type == 'logistic_4params':
logistic = logistic_4params
betas_init = betas_init_4params
elif curve_type == 'logistic_5params':
logistic = logistic_5params
betas_init = betas_init_5params
betas, _ = curve_fit(logistic, x, y, p0=betas_init)
yhat = logistic(x, *betas)
return yhat
def calculate_rmse(x, y, fit_scale=None, eps=1e-8):
if fit_scale is not None:
x = fit_curve(x, y, fit_scale)
return np.sqrt(np.mean((x - y) ** 2) + eps) | null |
167,886 | from scipy import stats
from scipy.optimize import curve_fit
import numpy as np
from pyiqa.utils.registry import METRIC_REGISTRY
def fit_curve(x, y, curve_type='logistic_4params'):
r'''Fit the scale of predict scores to MOS scores using logistic regression suggested by VQEG.
The function with 4 params is more commonly used.
The 5 params function takes from DBCNN:
- https://github.com/zwx8981/DBCNN/blob/master/dbcnn/tools/verify_performance.m
'''
assert curve_type in [
'logistic_4params', 'logistic_5params'], f'curve type should be in [logistic_4params, logistic_5params], but got {curve_type}.'
betas_init_4params = [np.max(y), np.min(y), np.mean(x), np.std(x) / 4.]
def logistic_4params(x, beta1, beta2, beta3, beta4):
yhat = (beta1 - beta2) / (1 + np.exp(- (x - beta3) / beta4)) + beta2
return yhat
betas_init_5params = [10, 0, np.mean(y), 0.1, 0.1]
def logistic_5params(x, beta1, beta2, beta3, beta4, beta5):
logistic_part = 0.5 - 1. / (1 + np.exp(beta2 * (x - beta3)))
yhat = beta1 * logistic_part + beta4 * x + beta5
return yhat
if curve_type == 'logistic_4params':
logistic = logistic_4params
betas_init = betas_init_4params
elif curve_type == 'logistic_5params':
logistic = logistic_5params
betas_init = betas_init_5params
betas, _ = curve_fit(logistic, x, y, p0=betas_init)
yhat = logistic(x, *betas)
return yhat
def calculate_plcc(x, y, fit_scale=None):
if fit_scale is not None:
x = fit_curve(x, y, fit_scale)
return stats.pearsonr(x, y)[0] | null |
167,887 | from scipy import stats
from scipy.optimize import curve_fit
import numpy as np
from pyiqa.utils.registry import METRIC_REGISTRY
def calculate_srcc(x, y):
return stats.spearmanr(x, y)[0] | null |
167,888 | from scipy import stats
from scipy.optimize import curve_fit
import numpy as np
from pyiqa.utils.registry import METRIC_REGISTRY
def calculate_krcc(x, y):
return stats.kendalltau(x, y)[0] | null |
167,889 | import fnmatch
import re
from .default_model_configs import DEFAULT_CONFIGS
from .utils import get_root_logger
from .models.inference_model import InferenceModel
DEFAULT_CONFIGS = OrderedDict({
'ahiq': {
'metric_opts': {
'type': 'AHIQ',
},
'metric_mode': 'FR',
},
'ckdn': {
'metric_opts': {
'type': 'CKDN',
},
'metric_mode': 'FR',
},
'lpips': {
'metric_opts': {
'type': 'LPIPS',
'net': 'alex',
'version': '0.1',
},
'metric_mode': 'FR',
'lower_better': True,
},
'lpips-vgg': {
'metric_opts': {
'type': 'LPIPS',
'net': 'vgg',
'version': '0.1',
},
'metric_mode': 'FR',
'lower_better': True,
},
'stlpips': {
'metric_opts': {
'type': 'STLPIPS',
'net': 'alex',
'variant': 'shift_tolerant',
},
'metric_mode': 'FR',
'lower_better': True,
},
'stlpips-vgg': {
'metric_opts': {
'type': 'STLPIPS',
'net': 'vgg',
'variant': 'shift_tolerant',
},
'metric_mode': 'FR',
'lower_better': True,
},
'dists': {
'metric_opts': {
'type': 'DISTS',
},
'metric_mode': 'FR',
'lower_better': True,
},
'ssim': {
'metric_opts': {
'type': 'SSIM',
'downsample': False,
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'ssimc': {
'metric_opts': {
'type': 'SSIM',
'downsample': False,
'test_y_channel': False,
},
'metric_mode': 'FR',
},
'psnr': {
'metric_opts': {
'type': 'PSNR',
'test_y_channel': False,
},
'metric_mode': 'FR',
},
'psnry': {
'metric_opts': {
'type': 'PSNR',
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'fsim': {
'metric_opts': {
'type': 'FSIM',
'chromatic': True,
},
'metric_mode': 'FR',
},
'ms_ssim': {
'metric_opts': {
'type': 'MS_SSIM',
'downsample': False,
'test_y_channel': True,
'is_prod': True,
},
'metric_mode': 'FR',
},
'vif': {
'metric_opts': {
'type': 'VIF',
},
'metric_mode': 'FR',
},
'gmsd': {
'metric_opts': {
'type': 'GMSD',
'test_y_channel': True,
},
'metric_mode': 'FR',
'lower_better': True,
},
'nlpd': {
'metric_opts': {
'type': 'NLPD',
'channels': 1,
'test_y_channel': True,
},
'metric_mode': 'FR',
'lower_better': True,
},
'vsi': {
'metric_opts': {
'type': 'VSI',
},
'metric_mode': 'FR',
},
'cw_ssim': {
'metric_opts': {
'type': 'CW_SSIM',
'channels': 1,
'level': 4,
'ori': 8,
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'mad': {
'metric_opts': {
'type': 'MAD',
},
'metric_mode': 'FR',
'lower_better': True,
},
# =============================================================
'niqe': {
'metric_opts': {
'type': 'NIQE',
'test_y_channel': True,
},
'metric_mode': 'NR',
'lower_better': True,
},
'ilniqe': {
'metric_opts': {
'type': 'ILNIQE',
},
'metric_mode': 'NR',
'lower_better': True,
},
'brisque': {
'metric_opts': {
'type': 'BRISQUE',
'test_y_channel': True,
},
'metric_mode': 'NR',
'lower_better': True,
},
'nrqm': {
'metric_opts': {
'type': 'NRQM',
},
'metric_mode': 'NR',
},
'pi': {
'metric_opts': {
'type': 'PI',
},
'metric_mode': 'NR',
'lower_better': True,
},
'cnniqa': {
'metric_opts': {
'type': 'CNNIQA',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq-ava': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'ava'
},
'metric_mode': 'NR',
},
'musiq-koniq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq-paq2piq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'paq2piq'
},
'metric_mode': 'NR',
},
'musiq-spaq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'spaq'
},
'metric_mode': 'NR',
},
'nima': {
'metric_opts': {
'type': 'NIMA',
'num_classes': 10,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-koniq': {
'metric_opts': {
'type': 'NIMA',
'train_dataset': 'koniq',
'num_classes': 1,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-spaq': {
'metric_opts': {
'type': 'NIMA',
'train_dataset': 'spaq',
'num_classes': 1,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-vgg16-ava': {
'metric_opts': {
'type': 'NIMA',
'num_classes': 10,
'base_model_name': 'vgg16',
},
'metric_mode': 'NR',
},
'pieapp': {
'metric_opts': {
'type': 'PieAPP',
},
'metric_mode': 'FR',
'lower_better': True,
},
'paq2piq': {
'metric_opts': {
'type': 'PAQ2PIQ',
},
'metric_mode': 'NR',
},
'dbcnn': {
'metric_opts': {
'type': 'DBCNN',
'pretrained': 'koniq'
},
'metric_mode': 'NR',
},
'fid': {
'metric_opts': {
'type': 'FID',
},
'metric_mode': 'NR',
'lower_better': True,
},
'maniqa': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'koniq',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'maniqa-koniq': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'koniq',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'maniqa-pipal': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'pipal',
},
'metric_mode': 'NR',
},
'maniqa-kadid': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'kadid',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'clipiqa': {
'metric_opts': {
'type': 'CLIPIQA',
},
'metric_mode': 'NR',
},
'clipiqa+': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+',
},
'metric_mode': 'NR',
},
'clipiqa+_vitL14_512': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+_vitL14_512',
'backbone': 'ViT-L/14',
'pos_embedding': True,
},
'metric_mode': 'NR',
},
'clipiqa+_rn50_512': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+_rn50_512',
'backbone': 'RN50',
'pos_embedding': True,
},
'metric_mode': 'NR',
},
'tres': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'koniq',
},
'metric_mode': 'NR',
},
'tres-koniq': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'koniq',
},
'metric_mode': 'NR',
},
'tres-flive': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'flive',
},
'metric_mode': 'NR',
},
'hyperiqa': {
'metric_opts': {
'type': 'HyperNet',
},
'metric_mode': 'NR',
},
'uranker': {
'metric_opts': {
'type': 'URanker',
},
'metric_mode': 'NR',
},
'clipscore': {
'metric_opts': {
'type': 'CLIPScore',
},
'metric_mode': 'NR', # Caption image similarity
},
'entropy': {
'metric_opts': {
'type': 'Entropy',
},
'metric_mode': 'NR',
},
'topiq_nr': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_koniq_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-flive': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_flive_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-spaq': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_spaq_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-face': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'topiq_nr_gfiqa_res50',
'use_ref': False,
'test_img_size': 512,
},
'metric_mode': 'NR',
},
'topiq_fr': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_fr_kadid_res50',
'use_ref': True,
},
'metric_mode': 'FR',
},
'topiq_fr-pipal': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_fr_pipal_res50',
'use_ref': True,
},
'metric_mode': 'FR',
},
'topiq_iaa': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'swin_base_patch4_window12_384',
'model_name': 'cfanet_iaa_ava_swin',
'use_ref': False,
'inter_dim': 512,
'num_heads': 8,
'num_class': 10,
},
'metric_mode': 'NR',
},
'topiq_iaa_res50': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_iaa_ava_res50',
'use_ref': False,
'inter_dim': 512,
'num_heads': 8,
'num_class': 10,
'test_img_size': 384,
},
'metric_mode': 'NR',
},
'laion_aes': {
'metric_opts': {
'type': 'LAIONAes',
},
'metric_mode': 'NR',
},
'liqe': {
'metric_opts': {
'type': 'LIQE',
'pretrained': 'koniq'
},
'metric_mode': 'NR',
},
'liqe_mix': {
'metric_opts': {
'type': 'LIQE',
'pretrained': 'mix'
},
'metric_mode': 'NR',
},
'wadiqam_fr': {
'metric_opts': {
'type': 'WaDIQaM',
'metric_type': 'FR',
'model_name': 'wadiqam_fr_kadid',
},
'metric_mode': 'FR',
},
'wadiqam_nr': {
'metric_opts': {
'type': 'WaDIQaM',
'metric_type': 'NR',
'model_name': 'wadiqam_nr_koniq',
},
'metric_mode': 'NR',
},
'qalign': {
'metric_opts': {
'type': 'QAlign',
},
'metric_mode': 'NR',
},
'unique': {
'metric_opts': {
'type': 'UNIQUE',
},
'metric_mode': 'NR',
}
})
class InferenceModel(torch.nn.Module):
"""Common interface for quality inference of images with default setting of each metric."""
def __init__(
self,
metric_name,
as_loss=False,
loss_weight=None,
loss_reduction='mean',
device=None,
seed=123,
**kwargs # Other metric options
):
super(InferenceModel, self).__init__()
self.metric_name = metric_name
# ============ set metric properties ===========
self.lower_better = DEFAULT_CONFIGS[metric_name].get('lower_better', False)
self.metric_mode = DEFAULT_CONFIGS[metric_name].get('metric_mode', None)
if self.metric_mode is None:
self.metric_mode = kwargs.pop('metric_mode')
elif 'metric_mode' in kwargs:
kwargs.pop('metric_mode')
if device is None:
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
else:
self.device = device
self.as_loss = as_loss
self.loss_weight = loss_weight
self.loss_reduction = loss_reduction
# =========== define metric model ===============
net_opts = OrderedDict()
# load default setting first
if metric_name in DEFAULT_CONFIGS.keys():
default_opt = DEFAULT_CONFIGS[metric_name]['metric_opts']
net_opts.update(default_opt)
# then update with custom setting
net_opts.update(kwargs)
network_type = net_opts.pop('type')
self.net = ARCH_REGISTRY.get(network_type)(**net_opts)
self.net = self.net.to(self.device)
self.net.eval()
set_random_seed(seed)
self.dummy_param = torch.nn.Parameter(torch.empty(0)).to(self.device)
def forward(self, target, ref=None, **kwargs):
device = self.dummy_param.device
with torch.set_grad_enabled(self.as_loss):
if 'fid' in self.metric_name:
output = self.net(target, ref, device=device, **kwargs)
else:
if not torch.is_tensor(target):
target = imread2tensor(target, rgb=True)
target = target.unsqueeze(0)
if self.metric_mode == 'FR':
assert ref is not None, 'Please specify reference image for Full Reference metric'
ref = imread2tensor(ref, rgb=True)
ref = ref.unsqueeze(0)
if self.metric_mode == 'FR':
assert ref is not None, 'Please specify reference image for Full Reference metric'
output = self.net(target.to(device), ref.to(device), **kwargs)
elif self.metric_mode == 'NR':
output = self.net(target.to(device), **kwargs)
if self.as_loss:
if isinstance(output, tuple):
output = output[0]
return weight_reduce_loss(output, self.loss_weight, self.loss_reduction)
else:
return output
def create_metric(metric_name, as_loss=False, device=None, **kwargs):
assert metric_name in DEFAULT_CONFIGS.keys(), f'Metric {metric_name} not implemented yet.'
metric = InferenceModel(metric_name, as_loss=as_loss, device=device, **kwargs)
logger = get_root_logger()
logger.info(f'Metric [{metric.net.__class__.__name__}] is created.')
return metric | null |
167,890 | import fnmatch
import re
from .default_model_configs import DEFAULT_CONFIGS
from .utils import get_root_logger
from .models.inference_model import InferenceModel
def _natural_key(string_):
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())]
DEFAULT_CONFIGS = OrderedDict({
'ahiq': {
'metric_opts': {
'type': 'AHIQ',
},
'metric_mode': 'FR',
},
'ckdn': {
'metric_opts': {
'type': 'CKDN',
},
'metric_mode': 'FR',
},
'lpips': {
'metric_opts': {
'type': 'LPIPS',
'net': 'alex',
'version': '0.1',
},
'metric_mode': 'FR',
'lower_better': True,
},
'lpips-vgg': {
'metric_opts': {
'type': 'LPIPS',
'net': 'vgg',
'version': '0.1',
},
'metric_mode': 'FR',
'lower_better': True,
},
'stlpips': {
'metric_opts': {
'type': 'STLPIPS',
'net': 'alex',
'variant': 'shift_tolerant',
},
'metric_mode': 'FR',
'lower_better': True,
},
'stlpips-vgg': {
'metric_opts': {
'type': 'STLPIPS',
'net': 'vgg',
'variant': 'shift_tolerant',
},
'metric_mode': 'FR',
'lower_better': True,
},
'dists': {
'metric_opts': {
'type': 'DISTS',
},
'metric_mode': 'FR',
'lower_better': True,
},
'ssim': {
'metric_opts': {
'type': 'SSIM',
'downsample': False,
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'ssimc': {
'metric_opts': {
'type': 'SSIM',
'downsample': False,
'test_y_channel': False,
},
'metric_mode': 'FR',
},
'psnr': {
'metric_opts': {
'type': 'PSNR',
'test_y_channel': False,
},
'metric_mode': 'FR',
},
'psnry': {
'metric_opts': {
'type': 'PSNR',
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'fsim': {
'metric_opts': {
'type': 'FSIM',
'chromatic': True,
},
'metric_mode': 'FR',
},
'ms_ssim': {
'metric_opts': {
'type': 'MS_SSIM',
'downsample': False,
'test_y_channel': True,
'is_prod': True,
},
'metric_mode': 'FR',
},
'vif': {
'metric_opts': {
'type': 'VIF',
},
'metric_mode': 'FR',
},
'gmsd': {
'metric_opts': {
'type': 'GMSD',
'test_y_channel': True,
},
'metric_mode': 'FR',
'lower_better': True,
},
'nlpd': {
'metric_opts': {
'type': 'NLPD',
'channels': 1,
'test_y_channel': True,
},
'metric_mode': 'FR',
'lower_better': True,
},
'vsi': {
'metric_opts': {
'type': 'VSI',
},
'metric_mode': 'FR',
},
'cw_ssim': {
'metric_opts': {
'type': 'CW_SSIM',
'channels': 1,
'level': 4,
'ori': 8,
'test_y_channel': True,
},
'metric_mode': 'FR',
},
'mad': {
'metric_opts': {
'type': 'MAD',
},
'metric_mode': 'FR',
'lower_better': True,
},
# =============================================================
'niqe': {
'metric_opts': {
'type': 'NIQE',
'test_y_channel': True,
},
'metric_mode': 'NR',
'lower_better': True,
},
'ilniqe': {
'metric_opts': {
'type': 'ILNIQE',
},
'metric_mode': 'NR',
'lower_better': True,
},
'brisque': {
'metric_opts': {
'type': 'BRISQUE',
'test_y_channel': True,
},
'metric_mode': 'NR',
'lower_better': True,
},
'nrqm': {
'metric_opts': {
'type': 'NRQM',
},
'metric_mode': 'NR',
},
'pi': {
'metric_opts': {
'type': 'PI',
},
'metric_mode': 'NR',
'lower_better': True,
},
'cnniqa': {
'metric_opts': {
'type': 'CNNIQA',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq-ava': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'ava'
},
'metric_mode': 'NR',
},
'musiq-koniq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'koniq10k'
},
'metric_mode': 'NR',
},
'musiq-paq2piq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'paq2piq'
},
'metric_mode': 'NR',
},
'musiq-spaq': {
'metric_opts': {
'type': 'MUSIQ',
'pretrained': 'spaq'
},
'metric_mode': 'NR',
},
'nima': {
'metric_opts': {
'type': 'NIMA',
'num_classes': 10,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-koniq': {
'metric_opts': {
'type': 'NIMA',
'train_dataset': 'koniq',
'num_classes': 1,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-spaq': {
'metric_opts': {
'type': 'NIMA',
'train_dataset': 'spaq',
'num_classes': 1,
'base_model_name': 'inception_resnet_v2',
},
'metric_mode': 'NR',
},
'nima-vgg16-ava': {
'metric_opts': {
'type': 'NIMA',
'num_classes': 10,
'base_model_name': 'vgg16',
},
'metric_mode': 'NR',
},
'pieapp': {
'metric_opts': {
'type': 'PieAPP',
},
'metric_mode': 'FR',
'lower_better': True,
},
'paq2piq': {
'metric_opts': {
'type': 'PAQ2PIQ',
},
'metric_mode': 'NR',
},
'dbcnn': {
'metric_opts': {
'type': 'DBCNN',
'pretrained': 'koniq'
},
'metric_mode': 'NR',
},
'fid': {
'metric_opts': {
'type': 'FID',
},
'metric_mode': 'NR',
'lower_better': True,
},
'maniqa': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'koniq',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'maniqa-koniq': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'koniq',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'maniqa-pipal': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'pipal',
},
'metric_mode': 'NR',
},
'maniqa-kadid': {
'metric_opts': {
'type': 'MANIQA',
'train_dataset': 'kadid',
'scale': 0.8,
},
'metric_mode': 'NR',
},
'clipiqa': {
'metric_opts': {
'type': 'CLIPIQA',
},
'metric_mode': 'NR',
},
'clipiqa+': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+',
},
'metric_mode': 'NR',
},
'clipiqa+_vitL14_512': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+_vitL14_512',
'backbone': 'ViT-L/14',
'pos_embedding': True,
},
'metric_mode': 'NR',
},
'clipiqa+_rn50_512': {
'metric_opts': {
'type': 'CLIPIQA',
'model_type': 'clipiqa+_rn50_512',
'backbone': 'RN50',
'pos_embedding': True,
},
'metric_mode': 'NR',
},
'tres': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'koniq',
},
'metric_mode': 'NR',
},
'tres-koniq': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'koniq',
},
'metric_mode': 'NR',
},
'tres-flive': {
'metric_opts': {
'type': 'TReS',
'train_dataset': 'flive',
},
'metric_mode': 'NR',
},
'hyperiqa': {
'metric_opts': {
'type': 'HyperNet',
},
'metric_mode': 'NR',
},
'uranker': {
'metric_opts': {
'type': 'URanker',
},
'metric_mode': 'NR',
},
'clipscore': {
'metric_opts': {
'type': 'CLIPScore',
},
'metric_mode': 'NR', # Caption image similarity
},
'entropy': {
'metric_opts': {
'type': 'Entropy',
},
'metric_mode': 'NR',
},
'topiq_nr': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_koniq_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-flive': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_flive_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-spaq': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_nr_spaq_res50',
'use_ref': False,
},
'metric_mode': 'NR',
},
'topiq_nr-face': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'topiq_nr_gfiqa_res50',
'use_ref': False,
'test_img_size': 512,
},
'metric_mode': 'NR',
},
'topiq_fr': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_fr_kadid_res50',
'use_ref': True,
},
'metric_mode': 'FR',
},
'topiq_fr-pipal': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_fr_pipal_res50',
'use_ref': True,
},
'metric_mode': 'FR',
},
'topiq_iaa': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'swin_base_patch4_window12_384',
'model_name': 'cfanet_iaa_ava_swin',
'use_ref': False,
'inter_dim': 512,
'num_heads': 8,
'num_class': 10,
},
'metric_mode': 'NR',
},
'topiq_iaa_res50': {
'metric_opts': {
'type': 'CFANet',
'semantic_model_name': 'resnet50',
'model_name': 'cfanet_iaa_ava_res50',
'use_ref': False,
'inter_dim': 512,
'num_heads': 8,
'num_class': 10,
'test_img_size': 384,
},
'metric_mode': 'NR',
},
'laion_aes': {
'metric_opts': {
'type': 'LAIONAes',
},
'metric_mode': 'NR',
},
'liqe': {
'metric_opts': {
'type': 'LIQE',
'pretrained': 'koniq'
},
'metric_mode': 'NR',
},
'liqe_mix': {
'metric_opts': {
'type': 'LIQE',
'pretrained': 'mix'
},
'metric_mode': 'NR',
},
'wadiqam_fr': {
'metric_opts': {
'type': 'WaDIQaM',
'metric_type': 'FR',
'model_name': 'wadiqam_fr_kadid',
},
'metric_mode': 'FR',
},
'wadiqam_nr': {
'metric_opts': {
'type': 'WaDIQaM',
'metric_type': 'NR',
'model_name': 'wadiqam_nr_koniq',
},
'metric_mode': 'NR',
},
'qalign': {
'metric_opts': {
'type': 'QAlign',
},
'metric_mode': 'NR',
},
'unique': {
'metric_opts': {
'type': 'UNIQUE',
},
'metric_mode': 'NR',
}
})
The provided code snippet includes necessary dependencies for implementing the `list_models` function. Write a Python function `def list_models(metric_mode=None, filter='', exclude_filters='')` to solve the following problem:
Return list of available model names, sorted alphabetically Args: filter (str) - Wildcard filter string that works with fnmatch exclude_filters (str or list[str]) - Wildcard filters to exclude models after including them with filter Example: model_list('*ssim*') -- returns all models including 'ssim'
Here is the function:
def list_models(metric_mode=None, filter='', exclude_filters=''):
""" Return list of available model names, sorted alphabetically
Args:
filter (str) - Wildcard filter string that works with fnmatch
exclude_filters (str or list[str]) - Wildcard filters to exclude models after including them with filter
Example:
model_list('*ssim*') -- returns all models including 'ssim'
"""
if metric_mode is None:
all_models = DEFAULT_CONFIGS.keys()
else:
assert metric_mode in ['FR', 'NR'], f'Metric mode only support [FR, NR], but got {metric_mode}'
all_models = [key for key in DEFAULT_CONFIGS.keys() if DEFAULT_CONFIGS[key]['metric_mode'] == metric_mode]
if filter:
models = []
include_filters = filter if isinstance(filter, (tuple, list)) else [filter]
for f in include_filters:
include_models = fnmatch.filter(all_models, f) # include these models
if len(include_models):
models = set(models).union(include_models)
else:
models = all_models
if exclude_filters:
if not isinstance(exclude_filters, (tuple, list)):
exclude_filters = [exclude_filters]
for xf in exclude_filters:
exclude_models = fnmatch.filter(models, xf) # exclude these models
if len(exclude_models):
models = set(models).difference(exclude_models)
return list(sorted(models, key=_natural_key)) | Return list of available model names, sorted alphabetically Args: filter (str) - Wildcard filter string that works with fnmatch exclude_filters (str or list[str]) - Wildcard filters to exclude models after including them with filter Example: model_list('*ssim*') -- returns all models including 'ssim' |
167,891 | import cv2
import random
import functools
from typing import Union
from PIL import Image
from collections.abc import Sequence
from imgaug import augmenters as iaa
import numpy as np
import torch
import torchvision.transforms as tf
import torchvision.transforms.functional as F
from pyiqa.archs.arch_util import to_2tuple
class PairedToTensor(tf.ToTensor):
"""Pair version of center crop"""
def to_tensor(self, x):
if isinstance(x, torch.Tensor):
return x
else:
return super().__call__(x)
def __call__(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
imgs[i] = self.to_tensor(imgs[i])
return imgs
else:
return self.to_tensor(imgs)
class ChangeColorSpace:
"""Pair version of center crop"""
def __init__(self, to_colorspace):
self.aug_op = iaa.color.ChangeColorspace(to_colorspace)
def __call__(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
tmpimg = self.aug_op.augment_image(np.array(imgs[i]))
imgs[i] = Image.fromarray(tmpimg)
return imgs
else:
imgs = self.aug_op.augment_image(np.array(imgs))
return Image.fromarray(imgs)
class PairedCenterCrop(tf.CenterCrop):
"""Pair version of center crop"""
def forward(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
imgs[i] = super().forward(imgs[i])
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedRandomCrop(tf.RandomCrop):
"""Pair version of random crop"""
def _pad(self, img):
if self.padding is not None:
img = F.pad(img, self.padding, self.fill, self.padding_mode)
width, height = img.size
# pad the width if needed
if self.pad_if_needed and width < self.size[1]:
padding = [self.size[1] - width, 0]
img = F.pad(img, padding, self.fill, self.padding_mode)
# pad the height if needed
if self.pad_if_needed and height < self.size[0]:
padding = [0, self.size[0] - height]
img = F.pad(img, padding, self.fill, self.padding_mode)
return img
def forward(self, imgs):
if _is_pair(imgs):
i, j, h, w = self.get_params(imgs[0], self.size)
for i in range(len(imgs)):
img = self._pad(imgs[i])
img = F.crop(img, i, j, h, w)
imgs[i] = img
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedRandomErasing(tf.RandomErasing):
"""Pair version of random erasing"""
def forward(self, imgs):
if _is_pair(imgs):
if torch.rand(1) < self.p:
# cast self.value to script acceptable type
if isinstance(self.value, (int, float)):
value = [self.value]
elif isinstance(self.value, str):
value = None
elif isinstance(self.value, tuple):
value = list(self.value)
else:
value = self.value
if value is not None and not (len(value) in (1, imgs[0].shape[-3])):
raise ValueError(
"If value is a sequence, it should have either a single value or "
f"{imgs[0].shape[-3]} (number of input channels)"
)
x, y, h, w, v = self.get_params(imgs[0], scale=self.scale, ratio=self.ratio, value=value)
for i in range(len(imgs)):
imgs[i] = F.erase(imgs[i], x, y, h, w, v, self.inplace)
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedRandomHorizontalFlip(tf.RandomHorizontalFlip):
"""Pair version of random hflip"""
def forward(self, imgs):
if _is_pair(imgs):
if torch.rand(1) < self.p:
for i in range(len(imgs)):
imgs[i] = F.hflip(imgs[i])
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedRandomVerticalFlip(tf.RandomVerticalFlip):
"""Pair version of random hflip"""
def forward(self, imgs):
if _is_pair(imgs):
if torch.rand(1) < self.p:
for i in range(len(imgs)):
imgs[i] = F.vflip(imgs[i])
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedRandomRot90(torch.nn.Module):
"""Pair version of random hflip"""
def __init__(self, p=0.5):
super().__init__()
self.p = p
def forward(self, imgs):
if _is_pair(imgs):
if torch.rand(1) < self.p:
for i in range(len(imgs)):
imgs[i] = F.rotate(imgs[i], 90)
return imgs
elif isinstance(imgs, Image.Image):
if torch.rand(1) < self.p:
imgs = F.rotate(imgs, 90)
return imgs
class PairedResize(tf.Resize):
"""Pair version of resize"""
def forward(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
imgs[i] = super().forward(imgs[i])
return imgs
elif isinstance(imgs, Image.Image):
return super().forward(imgs)
class PairedAdaptiveResize(tf.Resize):
"""ARP preserved resize when necessary"""
def forward(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
tmpimg = imgs[i]
min_size = min(tmpimg.size)
if min_size < self.size:
tmpimg = super().forward(tmpimg)
imgs[i] = tmpimg
return imgs
elif isinstance(imgs, Image.Image):
tmpimg = imgs
min_size = min(tmpimg.size)
if min_size < self.size:
tmpimg = super().forward(tmpimg)
return tmpimg
class PairedRandomARPResize(torch.nn.Module):
"""Pair version of resize"""
def __init__(self, size_range, interpolation=tf.InterpolationMode.BILINEAR, antialias=None):
super().__init__()
self.interpolation = interpolation
self.antialias = antialias
self.size_range = size_range
if not (isinstance(size_range, Sequence) and len(size_range) == 2):
raise TypeError(f"size_range should be sequence with 2 int. Got {size_range} with {type(size_range)}")
def forward(self, imgs):
min_size, max_size = sorted(self.size_range)
target_size = random.randint(min_size, max_size)
if _is_pair(imgs):
for i in range(len(imgs)):
imgs[i] = F.resize(imgs[i], target_size, self.interpolation)
return imgs
elif isinstance(imgs, Image.Image):
return F.resize(imgs, target_size, self.interpolation)
class PairedRandomSquareResize(torch.nn.Module):
"""Pair version of resize"""
def __init__(self, size_range, interpolation=tf.InterpolationMode.BILINEAR, antialias=None):
super().__init__()
self.interpolation = interpolation
self.antialias = antialias
self.size_range = size_range
if not (isinstance(size_range, Sequence) and len(size_range) == 2):
raise TypeError(f"size_range should be sequence with 2 int. Got {size_range} with {type(size_range)}")
def forward(self, imgs):
min_size, max_size = sorted(self.size_range)
target_size = random.randint(min_size, max_size)
target_size = (target_size, target_size)
if _is_pair(imgs):
for i in range(len(imgs)):
imgs[i] = F.resize(imgs[i], target_size, self.interpolation)
return imgs
elif isinstance(imgs, Image.Image):
return F.resize(imgs, target_size, self.interpolation)
class PairedAdaptivePadding(torch.nn.Module):
"""Pair version of resize"""
def __init__(self, target_size, fill=0, padding_mode='constant'):
super().__init__()
self.target_size = to_2tuple(target_size)
self.fill = fill
self.padding_mode = padding_mode
def get_padding(self, x):
w, h = x.size
th, tw = self.target_size
assert th >= h and tw >= w, f'Target size {self.target_size} should be larger than image size ({h}, {w})'
pad_row = th - h
pad_col = tw - w
pad_l, pad_r, pad_t, pad_b = (pad_col//2, pad_col - pad_col//2, pad_row//2, pad_row - pad_row//2)
return (pad_l, pad_t, pad_r, pad_b)
def forward(self, imgs):
if _is_pair(imgs):
for i in range(len(imgs)):
padding = self.get_padding(imgs[i])
imgs[i] = F.pad(imgs[i], padding, self.fill, self.padding_mode)
return imgs
elif isinstance(imgs, Image.Image):
padding = self.get_padding(imgs)
imgs = F.pad(imgs, padding, self.fill, self.padding_mode)
return imgs
def transform_mapping(key, args):
if key == 'hflip' and args:
return [PairedRandomHorizontalFlip()]
if key == 'vflip' and args:
return [PairedRandomVerticalFlip()]
elif key == 'random_crop':
return [PairedRandomCrop(args)]
elif key == 'center_crop':
return [PairedCenterCrop(args)]
elif key == 'resize':
return [PairedResize(args)]
elif key == 'adaptive_resize':
return [PairedAdaptiveResize(args)]
elif key == 'random_square_resize':
return [PairedRandomSquareResize(args)]
elif key == 'random_arp_resize':
return [PairedRandomARPResize(args)]
elif key == 'ada_pad':
return [PairedAdaptivePadding(args)]
elif key == 'rot90' and args:
return [PairedRandomRot90(args)]
elif key == 'randomerase':
return [PairedRandomErasing(**args)]
elif key == 'changecolor':
return [ChangeColorSpace(args)]
elif key == 'totensor' and args:
return [PairedToTensor()]
else:
return [] | null |
167,892 | import cv2
import random
import functools
from typing import Union
from PIL import Image
from collections.abc import Sequence
from imgaug import augmenters as iaa
import numpy as np
import torch
import torchvision.transforms as tf
import torchvision.transforms.functional as F
from pyiqa.archs.arch_util import to_2tuple
def _is_pair(x):
if isinstance(x, (tuple, list)) and len(x) >= 2:
return True | null |
167,893 | import cv2
import random
import functools
from typing import Union
from PIL import Image
from collections.abc import Sequence
from imgaug import augmenters as iaa
import numpy as np
import torch
import torchvision.transforms as tf
import torchvision.transforms.functional as F
from pyiqa.archs.arch_util import to_2tuple
The provided code snippet includes necessary dependencies for implementing the `augment` function. Write a Python function `def augment(imgs, hflip=True, rotation=True, flows=None, return_status=False)` to solve the following problem:
Augment: horizontal flips OR rotate (0, 90, 180, 270 degrees). We use vertical flip and transpose for rotation implementation. All the images in the list use the same augmentation. Args: imgs (list[ndarray] | ndarray): Images to be augmented. If the input is an ndarray, it will be transformed to a list. hflip (bool): Horizontal flip. Default: True. rotation (bool): Ratotation. Default: True. flows (list[ndarray]: Flows to be augmented. If the input is an ndarray, it will be transformed to a list. Dimension is (h, w, 2). Default: None. return_status (bool): Return the status of flip and rotation. Default: False. Returns: list[ndarray] | ndarray: Augmented images and flows. If returned results only have one element, just return ndarray.
Here is the function:
def augment(imgs, hflip=True, rotation=True, flows=None, return_status=False):
"""Augment: horizontal flips OR rotate (0, 90, 180, 270 degrees).
We use vertical flip and transpose for rotation implementation.
All the images in the list use the same augmentation.
Args:
imgs (list[ndarray] | ndarray): Images to be augmented. If the input
is an ndarray, it will be transformed to a list.
hflip (bool): Horizontal flip. Default: True.
rotation (bool): Ratotation. Default: True.
flows (list[ndarray]: Flows to be augmented. If the input is an
ndarray, it will be transformed to a list.
Dimension is (h, w, 2). Default: None.
return_status (bool): Return the status of flip and rotation.
Default: False.
Returns:
list[ndarray] | ndarray: Augmented images and flows. If returned
results only have one element, just return ndarray.
"""
hflip = hflip and random.random() < 0.5
vflip = rotation and random.random() < 0.5
rot90 = rotation and random.random() < 0.5
def _augment(img):
if hflip: # horizontal
cv2.flip(img, 1, img)
if vflip: # vertical
cv2.flip(img, 0, img)
if rot90:
img = img.transpose(1, 0, 2)
return img
def _augment_flow(flow):
if hflip: # horizontal
cv2.flip(flow, 1, flow)
flow[:, :, 0] *= -1
if vflip: # vertical
cv2.flip(flow, 0, flow)
flow[:, :, 1] *= -1
if rot90:
flow = flow.transpose(1, 0, 2)
flow = flow[:, :, [1, 0]]
return flow
if not isinstance(imgs, list):
imgs = [imgs]
imgs = [_augment(img) for img in imgs]
if len(imgs) == 1:
imgs = imgs[0]
if flows is not None:
if not isinstance(flows, list):
flows = [flows]
flows = [_augment_flow(flow) for flow in flows]
if len(flows) == 1:
flows = flows[0]
return imgs, flows
else:
if return_status:
return imgs, (hflip, vflip, rot90)
else:
return imgs | Augment: horizontal flips OR rotate (0, 90, 180, 270 degrees). We use vertical flip and transpose for rotation implementation. All the images in the list use the same augmentation. Args: imgs (list[ndarray] | ndarray): Images to be augmented. If the input is an ndarray, it will be transformed to a list. hflip (bool): Horizontal flip. Default: True. rotation (bool): Ratotation. Default: True. flows (list[ndarray]: Flows to be augmented. If the input is an ndarray, it will be transformed to a list. Dimension is (h, w, 2). Default: None. return_status (bool): Return the status of flip and rotation. Default: False. Returns: list[ndarray] | ndarray: Augmented images and flows. If returned results only have one element, just return ndarray. |
167,894 | import cv2
import random
import functools
from typing import Union
from PIL import Image
from collections.abc import Sequence
from imgaug import augmenters as iaa
import numpy as np
import torch
import torchvision.transforms as tf
import torchvision.transforms.functional as F
from pyiqa.archs.arch_util import to_2tuple
The provided code snippet includes necessary dependencies for implementing the `img_rotate` function. Write a Python function `def img_rotate(img, angle, center=None, scale=1.0)` to solve the following problem:
Rotate image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees. Positive values mean counter-clockwise rotation. center (tuple[int]): Rotation center. If the center is None, initialize it as the center of the image. Default: None. scale (float): Isotropic scale factor. Default: 1.0.
Here is the function:
def img_rotate(img, angle, center=None, scale=1.0):
"""Rotate image.
Args:
img (ndarray): Image to be rotated.
angle (float): Rotation angle in degrees. Positive values mean
counter-clockwise rotation.
center (tuple[int]): Rotation center. If the center is None,
initialize it as the center of the image. Default: None.
scale (float): Isotropic scale factor. Default: 1.0.
"""
(h, w) = img.shape[:2]
if center is None:
center = (w // 2, h // 2)
matrix = cv2.getRotationMatrix2D(center, angle, scale)
rotated_img = cv2.warpAffine(img, matrix, (w, h))
return rotated_img | Rotate image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees. Positive values mean counter-clockwise rotation. center (tuple[int]): Rotation center. If the center is None, initialize it as the center of the image. Default: None. scale (float): Isotropic scale factor. Default: 1.0. |
167,895 | from unittest.mock import patch
import numpy as np
import math
from os import path as osp
import torch
from torch.nn import functional as F
def resize_preserve_aspect_ratio(image, h, w, longer_side_length):
"""Aspect-ratio-preserving resizing with tf.image.ResizeMethod.GAUSSIAN.
Args:
image: The image tensor (n_crops, c, h, w).
h: Height of the input image.
w: Width of the input image.
longer_side_length: The length of the longer side after resizing.
Returns:
A tuple of [Image after resizing, Resized height, Resized width].
"""
# Computes the height and width after aspect-ratio-preserving resizing.
ratio = longer_side_length / max(h, w)
rh = round(h * ratio)
rw = round(w * ratio)
resized = F.interpolate(image, (rh, rw), mode='bicubic', align_corners=False)
return resized, rh, rw
def _extract_patches_and_positions_from_image(image, patch_size, patch_stride, hse_grid_size, n_crops, h, w, c,
scale_id, max_seq_len):
"""Extracts patches and positional embedding lookup indexes for a given image.
Args:
image: the input image of shape [n_crops, c, h, w]
patch_size: the extracted patch size.
patch_stride: stride for extracting patches.
hse_grid_size: grid size for hash-based spatial positional embedding.
n_crops: number of crops from the input image.
h: height of the image.
w: width of the image.
c: number of channels for the image.
scale_id: the scale id for the image in the multi-scale representation.
max_seq_len: maximum sequence length for the number of patches. If
max_seq_len = 0, no patch is returned. If max_seq_len < 0 then we return
all the patches.
Returns:
A concatenating vector of (patches, HSE, SCE, input mask). The tensor shape
is (n_crops, num_patches, patch_size * patch_size * c + 3).
"""
n_crops, c, h, w = image.shape
p = extract_image_patches(image, patch_size, patch_stride)
assert p.shape[1] == c * patch_size**2
count_h = _ceil_divide_int(h, patch_stride)
count_w = _ceil_divide_int(w, patch_stride)
# Shape (1, num_patches)
spatial_p = get_hashed_spatial_pos_emb_index(hse_grid_size, count_h, count_w)
# Shape (n_crops, 1, num_patches)
spatial_p = spatial_p.unsqueeze(1).repeat(n_crops, 1, 1)
scale_p = torch.ones_like(spatial_p) * scale_id
mask_p = torch.ones_like(spatial_p)
# Concatenating is a hacky way to pass both patches, positions and input
# mask to the model.
# Shape (n_crops, c * patch_size * patch_size + 3, num_patches)
out = torch.cat([p, spatial_p.to(p), scale_p.to(p), mask_p.to(p)], dim=1)
if max_seq_len >= 0:
out = _pad_or_cut_to_max_seq_len(out, max_seq_len)
return out
The provided code snippet includes necessary dependencies for implementing the `get_multiscale_patches` function. Write a Python function `def get_multiscale_patches(image, patch_size=32, patch_stride=32, hse_grid_size=10, longer_side_lengths=[224, 384], max_seq_len_from_original_res=None)` to solve the following problem:
Extracts image patches from multi-scale representation. Args: image: input image tensor with shape [n_crops, 3, h, w] patch_size: patch size. patch_stride: patch stride. hse_grid_size: Hash-based positional embedding grid size. longer_side_lengths: List of longer-side lengths for each scale in the multi-scale representation. max_seq_len_from_original_res: Maximum number of patches extracted from original resolution. <0 means use all the patches from the original resolution. None means we don't use original resolution input. Returns: A concatenating vector of (patches, HSE, SCE, input mask). The tensor shape is (n_crops, num_patches, patch_size * patch_size * c + 3).
Here is the function:
def get_multiscale_patches(image,
patch_size=32,
patch_stride=32,
hse_grid_size=10,
longer_side_lengths=[224, 384],
max_seq_len_from_original_res=None):
"""Extracts image patches from multi-scale representation.
Args:
image: input image tensor with shape [n_crops, 3, h, w]
patch_size: patch size.
patch_stride: patch stride.
hse_grid_size: Hash-based positional embedding grid size.
longer_side_lengths: List of longer-side lengths for each scale in the
multi-scale representation.
max_seq_len_from_original_res: Maximum number of patches extracted from
original resolution. <0 means use all the patches from the original
resolution. None means we don't use original resolution input.
Returns:
A concatenating vector of (patches, HSE, SCE, input mask). The tensor shape
is (n_crops, num_patches, patch_size * patch_size * c + 3).
"""
# Sorting the list to ensure a deterministic encoding of the scale position.
longer_side_lengths = sorted(longer_side_lengths)
if len(image.shape) == 3:
image = image.unsqueeze(0)
n_crops, c, h, w = image.shape
outputs = []
for scale_id, longer_size in enumerate(longer_side_lengths):
resized_image, rh, rw = resize_preserve_aspect_ratio(image, h, w, longer_size)
max_seq_len = int(np.ceil(longer_size / patch_stride)**2)
out = _extract_patches_and_positions_from_image(resized_image, patch_size, patch_stride, hse_grid_size, n_crops,
rh, rw, c, scale_id, max_seq_len)
outputs.append(out)
if max_seq_len_from_original_res is not None:
out = _extract_patches_and_positions_from_image(image, patch_size, patch_stride, hse_grid_size, n_crops, h, w,
c, len(longer_side_lengths), max_seq_len_from_original_res)
outputs.append(out)
outputs = torch.cat(outputs, dim=-1)
return outputs.transpose(1, 2) | Extracts image patches from multi-scale representation. Args: image: input image tensor with shape [n_crops, 3, h, w] patch_size: patch size. patch_stride: patch stride. hse_grid_size: Hash-based positional embedding grid size. longer_side_lengths: List of longer-side lengths for each scale in the multi-scale representation. max_seq_len_from_original_res: Maximum number of patches extracted from original resolution. <0 means use all the patches from the original resolution. None means we don't use original resolution input. Returns: A concatenating vector of (patches, HSE, SCE, input mask). The tensor shape is (n_crops, num_patches, patch_size * patch_size * c + 3). |
167,896 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `read_meta_info_file` function. Write a Python function `def read_meta_info_file(img_dir, meta_info_file, mode='nr', ref_dir=None)` to solve the following problem:
Generate paths and mos labels from an meta information file. Each line in the meta information file contains the image names and mos label, separated by a white space. Example of an meta information file: - For NR datasets: name, mos(mean), std ``` 100.bmp 32.56107532210109 19.12472638223644 ``` - For FR datasets: ref_name, dist_name, mos(mean), std ``` I01.bmp I01_01_1.bmp 5.51429 0.13013 ``` Args: img_dir (str): directory path containing images meta_info_file (str): Path to the meta information file. Returns: list[str, float]: image paths, mos label
Here is the function:
def read_meta_info_file(img_dir, meta_info_file, mode='nr', ref_dir=None):
"""Generate paths and mos labels from an meta information file.
Each line in the meta information file contains the image names and
mos label, separated by a white space.
Example of an meta information file:
- For NR datasets: name, mos(mean), std
```
100.bmp 32.56107532210109 19.12472638223644
```
- For FR datasets: ref_name, dist_name, mos(mean), std
```
I01.bmp I01_01_1.bmp 5.51429 0.13013
```
Args:
img_dir (str): directory path containing images
meta_info_file (str): Path to the meta information file.
Returns:
list[str, float]: image paths, mos label
"""
with open(meta_info_file, 'r') as fin:
csvreader = csv.reader(fin)
name_mos = list(csvreader)[1:]
paths_mos = []
for item in name_mos:
if mode == 'fr':
if ref_dir is None:
ref_dir = img_dir
ref_name, img_name, mos = item[:3]
ref_path = osp.join(ref_dir, ref_name)
img_path = osp.join(img_dir, img_name)
paths_mos.append([ref_path, img_path, float(mos)])
elif mode == 'nr':
img_name, mos = item[:2]
img_path = osp.join(img_dir, img_name)
paths_mos.append([img_path, float(mos)])
return paths_mos | Generate paths and mos labels from an meta information file. Each line in the meta information file contains the image names and mos label, separated by a white space. Example of an meta information file: - For NR datasets: name, mos(mean), std ``` 100.bmp 32.56107532210109 19.12472638223644 ``` - For FR datasets: ref_name, dist_name, mos(mean), std ``` I01.bmp I01_01_1.bmp 5.51429 0.13013 ``` Args: img_dir (str): directory path containing images meta_info_file (str): Path to the meta information file. Returns: list[str, float]: image paths, mos label |
167,897 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
def mod_crop(img, scale):
"""Mod crop images, used during testing.
Args:
img (ndarray): Input image.
scale (int): Scale factor.
Returns:
ndarray: Result image.
"""
img = img.copy()
if img.ndim in (2, 3):
h, w = img.shape[0], img.shape[1]
h_remainder, w_remainder = h % scale, w % scale
img = img[:h - h_remainder, :w - w_remainder, ...]
else:
raise ValueError(f'Wrong img ndim: {img.ndim}.')
return img
The provided code snippet includes necessary dependencies for implementing the `read_img_seq` function. Write a Python function `def read_img_seq(path, require_mod_crop=False, scale=1, return_imgname=False)` to solve the following problem:
Read a sequence of images from a given folder path. Args: path (list[str] | str): List of image paths or image folder path. require_mod_crop (bool): Require mod crop for each image. Default: False. scale (int): Scale factor for mod_crop. Default: 1. return_imgname(bool): Whether return image names. Default False. Returns: Tensor: size (t, c, h, w), RGB, [0, 1]. list[str]: Returned image name list.
Here is the function:
def read_img_seq(path, require_mod_crop=False, scale=1, return_imgname=False):
"""Read a sequence of images from a given folder path.
Args:
path (list[str] | str): List of image paths or image folder path.
require_mod_crop (bool): Require mod crop for each image.
Default: False.
scale (int): Scale factor for mod_crop. Default: 1.
return_imgname(bool): Whether return image names. Default False.
Returns:
Tensor: size (t, c, h, w), RGB, [0, 1].
list[str]: Returned image name list.
"""
if isinstance(path, list):
img_paths = path
else:
img_paths = sorted(list(scandir(path, full_path=True)))
imgs = [cv2.imread(v).astype(np.float32) / 255. for v in img_paths]
if require_mod_crop:
imgs = [mod_crop(img, scale) for img in imgs]
imgs = img2tensor(imgs, bgr2rgb=True, float32=True)
imgs = torch.stack(imgs, dim=0)
if return_imgname:
imgnames = [osp.splitext(osp.basename(path))[0] for path in img_paths]
return imgs, imgnames
else:
return imgs | Read a sequence of images from a given folder path. Args: path (list[str] | str): List of image paths or image folder path. require_mod_crop (bool): Require mod crop for each image. Default: False. scale (int): Scale factor for mod_crop. Default: 1. return_imgname(bool): Whether return image names. Default False. Returns: Tensor: size (t, c, h, w), RGB, [0, 1]. list[str]: Returned image name list. |
167,898 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `generate_frame_indices` function. Write a Python function `def generate_frame_indices(crt_idx, max_frame_num, num_frames, padding='reflection')` to solve the following problem:
Generate an index list for reading `num_frames` frames from a sequence of images. Args: crt_idx (int): Current center index. max_frame_num (int): Max number of the sequence of images (from 1). num_frames (int): Reading num_frames frames. padding (str): Padding mode, one of 'replicate' | 'reflection' | 'reflection_circle' | 'circle' Examples: current_idx = 0, num_frames = 5 The generated frame indices under different padding mode: replicate: [0, 0, 0, 1, 2] reflection: [2, 1, 0, 1, 2] reflection_circle: [4, 3, 0, 1, 2] circle: [3, 4, 0, 1, 2] Returns: list[int]: A list of indices.
Here is the function:
def generate_frame_indices(crt_idx, max_frame_num, num_frames, padding='reflection'):
"""Generate an index list for reading `num_frames` frames from a sequence
of images.
Args:
crt_idx (int): Current center index.
max_frame_num (int): Max number of the sequence of images (from 1).
num_frames (int): Reading num_frames frames.
padding (str): Padding mode, one of
'replicate' | 'reflection' | 'reflection_circle' | 'circle'
Examples: current_idx = 0, num_frames = 5
The generated frame indices under different padding mode:
replicate: [0, 0, 0, 1, 2]
reflection: [2, 1, 0, 1, 2]
reflection_circle: [4, 3, 0, 1, 2]
circle: [3, 4, 0, 1, 2]
Returns:
list[int]: A list of indices.
"""
assert num_frames % 2 == 1, 'num_frames should be an odd number.'
assert padding in ('replicate', 'reflection', 'reflection_circle', 'circle'), f'Wrong padding mode: {padding}.'
max_frame_num = max_frame_num - 1 # start from 0
num_pad = num_frames // 2
indices = []
for i in range(crt_idx - num_pad, crt_idx + num_pad + 1):
if i < 0:
if padding == 'replicate':
pad_idx = 0
elif padding == 'reflection':
pad_idx = -i
elif padding == 'reflection_circle':
pad_idx = crt_idx + num_pad - i
else:
pad_idx = num_frames + i
elif i > max_frame_num:
if padding == 'replicate':
pad_idx = max_frame_num
elif padding == 'reflection':
pad_idx = max_frame_num * 2 - i
elif padding == 'reflection_circle':
pad_idx = (crt_idx - num_pad) - (i - max_frame_num)
else:
pad_idx = i - num_frames
else:
pad_idx = i
indices.append(pad_idx)
return indices | Generate an index list for reading `num_frames` frames from a sequence of images. Args: crt_idx (int): Current center index. max_frame_num (int): Max number of the sequence of images (from 1). num_frames (int): Reading num_frames frames. padding (str): Padding mode, one of 'replicate' | 'reflection' | 'reflection_circle' | 'circle' Examples: current_idx = 0, num_frames = 5 The generated frame indices under different padding mode: replicate: [0, 0, 0, 1, 2] reflection: [2, 1, 0, 1, 2] reflection_circle: [4, 3, 0, 1, 2] circle: [3, 4, 0, 1, 2] Returns: list[int]: A list of indices. |
167,899 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_lmdb` function. Write a Python function `def paired_paths_from_lmdb(folders, keys)` to solve the following problem:
Generate paired paths from lmdb files. Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is: lq.lmdb ├── data.mdb ├── lock.mdb ├── meta_info.txt The data.mdb and lock.mdb are standard lmdb files and you can refer to https://lmdb.readthedocs.io/en/release/ for more details. The meta_info.txt is a specified txt file to record the meta information of our datasets. It will be automatically created when preparing datasets by our provided dataset tools. Each line in the txt file records 1)image name (with extension), 2)image shape, 3)compression level, separated by a white space. Example: `baboon.png (120,125,3) 1` We use the image name without extension as the lmdb key. Note that we use the same key for the corresponding lq and gt images. Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. Note that this key is different from lmdb keys. Returns: list[str]: Returned path list.
Here is the function:
def paired_paths_from_lmdb(folders, keys):
"""Generate paired paths from lmdb files.
Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is:
lq.lmdb
├── data.mdb
├── lock.mdb
├── meta_info.txt
The data.mdb and lock.mdb are standard lmdb files and you can refer to
https://lmdb.readthedocs.io/en/release/ for more details.
The meta_info.txt is a specified txt file to record the meta information
of our datasets. It will be automatically created when preparing
datasets by our provided dataset tools.
Each line in the txt file records
1)image name (with extension),
2)image shape,
3)compression level, separated by a white space.
Example: `baboon.png (120,125,3) 1`
We use the image name without extension as the lmdb key.
Note that we use the same key for the corresponding lq and gt images.
Args:
folders (list[str]): A list of folder path. The order of list should
be [input_folder, gt_folder].
keys (list[str]): A list of keys identifying folders. The order should
be in consistent with folders, e.g., ['lq', 'gt'].
Note that this key is different from lmdb keys.
Returns:
list[str]: Returned path list.
"""
assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. '
f'But got {len(folders)}')
assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}'
input_folder, gt_folder = folders
input_key, gt_key = keys
if not (input_folder.endswith('.lmdb') and gt_folder.endswith('.lmdb')):
raise ValueError(f'{input_key} folder and {gt_key} folder should both in lmdb '
f'formats. But received {input_key}: {input_folder}; '
f'{gt_key}: {gt_folder}')
# ensure that the two meta_info files are the same
with open(osp.join(input_folder, 'meta_info.txt')) as fin:
input_lmdb_keys = [line.split('.')[0] for line in fin]
with open(osp.join(gt_folder, 'meta_info.txt')) as fin:
gt_lmdb_keys = [line.split('.')[0] for line in fin]
if set(input_lmdb_keys) != set(gt_lmdb_keys):
raise ValueError(f'Keys in {input_key}_folder and {gt_key}_folder are different.')
else:
paths = []
for lmdb_key in sorted(input_lmdb_keys):
paths.append(dict([(f'{input_key}_path', lmdb_key), (f'{gt_key}_path', lmdb_key)]))
return paths | Generate paired paths from lmdb files. Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is: lq.lmdb ├── data.mdb ├── lock.mdb ├── meta_info.txt The data.mdb and lock.mdb are standard lmdb files and you can refer to https://lmdb.readthedocs.io/en/release/ for more details. The meta_info.txt is a specified txt file to record the meta information of our datasets. It will be automatically created when preparing datasets by our provided dataset tools. Each line in the txt file records 1)image name (with extension), 2)image shape, 3)compression level, separated by a white space. Example: `baboon.png (120,125,3) 1` We use the image name without extension as the lmdb key. Note that we use the same key for the corresponding lq and gt images. Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. Note that this key is different from lmdb keys. Returns: list[str]: Returned path list. |
167,900 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_meta_info_file` function. Write a Python function `def paired_paths_from_meta_info_file(folders, keys, meta_info_file, filename_tmpl)` to solve the following problem:
Generate paired paths from an meta information file. Each line in the meta information file contains the image names and image shape (usually for gt), separated by a white space. Example of an meta information file: ``` 0001_s001.png (480,480,3) 0001_s002.png (480,480,3) ``` Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. meta_info_file (str): Path to the meta information file. filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. Usually the filename_tmpl is for files in the input folder. Returns: list[str]: Returned path list.
Here is the function:
def paired_paths_from_meta_info_file(folders, keys, meta_info_file, filename_tmpl):
"""Generate paired paths from an meta information file.
Each line in the meta information file contains the image names and
image shape (usually for gt), separated by a white space.
Example of an meta information file:
```
0001_s001.png (480,480,3)
0001_s002.png (480,480,3)
```
Args:
folders (list[str]): A list of folder path. The order of list should
be [input_folder, gt_folder].
keys (list[str]): A list of keys identifying folders. The order should
be in consistent with folders, e.g., ['lq', 'gt'].
meta_info_file (str): Path to the meta information file.
filename_tmpl (str): Template for each filename. Note that the
template excludes the file extension. Usually the filename_tmpl is
for files in the input folder.
Returns:
list[str]: Returned path list.
"""
assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. '
f'But got {len(folders)}')
assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}'
input_folder, gt_folder = folders
input_key, gt_key = keys
with open(meta_info_file, 'r') as fin:
gt_names = [line.strip().split(' ')[0] for line in fin]
paths = []
for gt_name in gt_names:
basename, ext = osp.splitext(osp.basename(gt_name))
input_name = f'{filename_tmpl.format(basename)}{ext}'
input_path = osp.join(input_folder, input_name)
gt_path = osp.join(gt_folder, gt_name)
paths.append(dict([(f'{input_key}_path', input_path), (f'{gt_key}_path', gt_path)]))
return paths | Generate paired paths from an meta information file. Each line in the meta information file contains the image names and image shape (usually for gt), separated by a white space. Example of an meta information file: ``` 0001_s001.png (480,480,3) 0001_s002.png (480,480,3) ``` Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. meta_info_file (str): Path to the meta information file. filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. Usually the filename_tmpl is for files in the input folder. Returns: list[str]: Returned path list. |
167,901 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_folder` function. Write a Python function `def paired_paths_from_folder(folders, keys, filename_tmpl)` to solve the following problem:
Generate paired paths from folders. Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. Usually the filename_tmpl is for files in the input folder. Returns: list[str]: Returned path list.
Here is the function:
def paired_paths_from_folder(folders, keys, filename_tmpl):
"""Generate paired paths from folders.
Args:
folders (list[str]): A list of folder path. The order of list should
be [input_folder, gt_folder].
keys (list[str]): A list of keys identifying folders. The order should
be in consistent with folders, e.g., ['lq', 'gt'].
filename_tmpl (str): Template for each filename. Note that the
template excludes the file extension. Usually the filename_tmpl is
for files in the input folder.
Returns:
list[str]: Returned path list.
"""
assert len(folders) == 2, ('The len of folders should be 2 with [input_folder, gt_folder]. '
f'But got {len(folders)}')
assert len(keys) == 2, f'The len of keys should be 2 with [input_key, gt_key]. But got {len(keys)}'
input_folder, gt_folder = folders
input_key, gt_key = keys
input_paths = list(scandir(input_folder))
gt_paths = list(scandir(gt_folder))
assert len(input_paths) == len(gt_paths), (f'{input_key} and {gt_key} datasets have different number of images: '
f'{len(input_paths)}, {len(gt_paths)}.')
paths = []
for gt_path in gt_paths:
basename, ext = osp.splitext(osp.basename(gt_path))
input_name = f'{filename_tmpl.format(basename)}{ext}'
input_path = osp.join(input_folder, input_name)
assert input_name in input_paths, f'{input_name} is not in {input_key}_paths.'
gt_path = osp.join(gt_folder, gt_path)
paths.append(dict([(f'{input_key}_path', input_path), (f'{gt_key}_path', gt_path)]))
return paths | Generate paired paths from folders. Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. Usually the filename_tmpl is for files in the input folder. Returns: list[str]: Returned path list. |
167,902 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paths_from_folder` function. Write a Python function `def paths_from_folder(folder)` to solve the following problem:
Generate paths from folder. Args: folder (str): Folder path. Returns: list[str]: Returned path list.
Here is the function:
def paths_from_folder(folder):
"""Generate paths from folder.
Args:
folder (str): Folder path.
Returns:
list[str]: Returned path list.
"""
paths = list(scandir(folder))
paths = [osp.join(folder, path) for path in paths]
return paths | Generate paths from folder. Args: folder (str): Folder path. Returns: list[str]: Returned path list. |
167,903 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paths_from_lmdb` function. Write a Python function `def paths_from_lmdb(folder)` to solve the following problem:
Generate paths from lmdb. Args: folder (str): Folder path. Returns: list[str]: Returned path list.
Here is the function:
def paths_from_lmdb(folder):
"""Generate paths from lmdb.
Args:
folder (str): Folder path.
Returns:
list[str]: Returned path list.
"""
if not folder.endswith('.lmdb'):
raise ValueError(f'Folder {folder}folder should in lmdb format.')
with open(osp.join(folder, 'meta_info.txt')) as fin:
paths = [line.split('.')[0] for line in fin]
return paths | Generate paths from lmdb. Args: folder (str): Folder path. Returns: list[str]: Returned path list. |
167,904 | import cv2
import numpy as np
import torch
import os
import csv
from os import path as osp
from torch.nn import functional as F
from pyiqa.data.transforms import mod_crop
from pyiqa.utils import img2tensor, scandir
def generate_gaussian_kernel(kernel_size=13, sigma=1.6):
"""Generate Gaussian kernel used in `duf_downsample`.
Args:
kernel_size (int): Kernel size. Default: 13.
sigma (float): Sigma of the Gaussian kernel. Default: 1.6.
Returns:
np.array: The Gaussian kernel.
"""
from scipy.ndimage import filters as filters
kernel = np.zeros((kernel_size, kernel_size))
# set element at the middle to one, a dirac delta
kernel[kernel_size // 2, kernel_size // 2] = 1
# gaussian-smooth the dirac, resulting in a gaussian filter
return filters.gaussian_filter(kernel, sigma)
The provided code snippet includes necessary dependencies for implementing the `duf_downsample` function. Write a Python function `def duf_downsample(x, kernel_size=13, scale=4)` to solve the following problem:
Downsamping with Gaussian kernel used in the DUF official code. Args: x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w). kernel_size (int): Kernel size. Default: 13. scale (int): Downsampling factor. Supported scale: (2, 3, 4). Default: 4. Returns: Tensor: DUF downsampled frames.
Here is the function:
def duf_downsample(x, kernel_size=13, scale=4):
"""Downsamping with Gaussian kernel used in the DUF official code.
Args:
x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w).
kernel_size (int): Kernel size. Default: 13.
scale (int): Downsampling factor. Supported scale: (2, 3, 4).
Default: 4.
Returns:
Tensor: DUF downsampled frames.
"""
assert scale in (2, 3, 4), f'Only support scale (2, 3, 4), but got {scale}.'
squeeze_flag = False
if x.ndim == 4:
squeeze_flag = True
x = x.unsqueeze(0)
b, t, c, h, w = x.size()
x = x.view(-1, 1, h, w)
pad_w, pad_h = kernel_size // 2 + scale * 2, kernel_size // 2 + scale * 2
x = F.pad(x, (pad_w, pad_w, pad_h, pad_h), 'reflect')
gaussian_filter = generate_gaussian_kernel(kernel_size, 0.4 * scale)
gaussian_filter = torch.from_numpy(gaussian_filter).type_as(x).unsqueeze(0).unsqueeze(0)
x = F.conv2d(x, gaussian_filter, stride=scale)
x = x[:, :, 2:-2, 2:-2]
x = x.view(b, t, c, x.size(2), x.size(3))
if squeeze_flag:
x = x.squeeze(0)
return x | Downsamping with Gaussian kernel used in the DUF official code. Args: x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w). kernel_size (int): Kernel size. Default: 13. scale (int): Downsampling factor. Supported scale: (2, 3, 4). Default: 4. Returns: Tensor: DUF downsampled frames. |
167,905 | import torch
import torch.nn as nn
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.utils.color_util import to_y_channel
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `psnr` function. Write a Python function `def psnr(x, y, test_y_channel=False, data_range=1.0, eps=1e-8, color_space='yiq')` to solve the following problem:
r"""Compute Peak Signal-to-Noise Ratio for a batch of images. Supports both greyscale and color images with RGB channel order. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - y: A target tensor. Shape :math:`(N, C, H, W)`. - test_y_channel (Boolean): Convert RGB image to YCbCr format and computes PSNR only on luminance channel if `True`. Compute on all 3 channels otherwise. - data_range: Maximum value range of images (default 1.0). Returns: PSNR Index of similarity betwen two images.
Here is the function:
def psnr(x, y, test_y_channel=False, data_range=1.0, eps=1e-8, color_space='yiq'):
r"""Compute Peak Signal-to-Noise Ratio for a batch of images.
Supports both greyscale and color images with RGB channel order.
Args:
- x: An input tensor. Shape :math:`(N, C, H, W)`.
- y: A target tensor. Shape :math:`(N, C, H, W)`.
- test_y_channel (Boolean): Convert RGB image to YCbCr format and computes PSNR
only on luminance channel if `True`. Compute on all 3 channels otherwise.
- data_range: Maximum value range of images (default 1.0).
Returns:
PSNR Index of similarity betwen two images.
"""
if (x.shape[1] == 3) and test_y_channel:
# Convert RGB image to YCbCr and use Y-channel
x = to_y_channel(x, data_range, color_space)
y = to_y_channel(y, data_range, color_space)
mse = torch.mean((x - y)**2, dim=[1, 2, 3])
score = 10 * torch.log10(data_range**2 / (mse + eps))
return score | r"""Compute Peak Signal-to-Noise Ratio for a batch of images. Supports both greyscale and color images with RGB channel order. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - y: A target tensor. Shape :math:`(N, C, H, W)`. - test_y_channel (Boolean): Convert RGB image to YCbCr format and computes PSNR only on luminance channel if `True`. Compute on all 3 channels otherwise. - data_range: Maximum value range of images (default 1.0). Returns: PSNR Index of similarity betwen two images. |
167,906 | import hashlib
import os
import urllib
import warnings
from tqdm import tqdm
from typing import Tuple, Union, List
from collections import OrderedDict
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
_MODELS = {
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
"RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
"RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
"RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
"RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
"ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
"ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
"ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
}
def _download(url: str, root: str):
os.makedirs(root, exist_ok=True)
filename = os.path.basename(url)
expected_sha256 = url.split("/")[-2]
download_target = os.path.join(root, filename)
if os.path.exists(download_target) and not os.path.isfile(download_target):
raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target):
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
return download_target
else:
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
while True:
buffer = source.read(8192)
if not buffer:
break
output.write(buffer)
loop.update(len(buffer))
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
return download_target
def available_models() -> List[str]:
"""Returns the names of available CLIP models"""
return list(_MODELS.keys())
def build_model(state_dict: dict):
vit = "visual.proj" in state_dict
if vit:
vision_width = state_dict["visual.conv1.weight"].shape[0]
vision_layers = len([k for k in state_dict.keys() if k.startswith(
"visual.") and k.endswith(".attn.in_proj_weight")])
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
image_resolution = vision_patch_size * grid_size
else:
counts: list = [len(set(k.split(".")[2]
for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
vision_layers = tuple(counts)
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
vision_patch_size = None
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
image_resolution = output_width * 32
embed_dim = state_dict["text_projection"].shape[1]
context_length = state_dict["positional_embedding"].shape[0]
vocab_size = state_dict["token_embedding.weight"].shape[0]
transformer_width = state_dict["ln_final.weight"].shape[0]
transformer_heads = transformer_width // 64
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
model = CLIP(
embed_dim,
image_resolution, vision_layers, vision_width, vision_patch_size,
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
)
for key in ["input_resolution", "context_length", "vocab_size"]:
if key in state_dict:
del state_dict[key]
convert_weights(model)
model.load_state_dict(state_dict)
return model.eval()
The provided code snippet includes necessary dependencies for implementing the `load` function. Write a Python function `def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None)` to solve the following problem:
Load a CLIP model Parameters ---------- name : str A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict device : Union[str, torch.device] The device to put the loaded model jit : bool Whether to load the optimized JIT model or more hackable non-JIT model (default). download_root: str path to download the model files; by default, it uses "~/.cache/clip" Returns ------- model : torch.nn.Module The CLIP model preprocess : Callable[[PIL.Image], torch.Tensor] A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
Here is the function:
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
"""Load a CLIP model
Parameters
----------
name : str
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
device : Union[str, torch.device]
The device to put the loaded model
jit : bool
Whether to load the optimized JIT model or more hackable non-JIT model (default).
download_root: str
path to download the model files; by default, it uses "~/.cache/clip"
Returns
-------
model : torch.nn.Module
The CLIP model
preprocess : Callable[[PIL.Image], torch.Tensor]
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
"""
if name in _MODELS:
model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
elif os.path.isfile(name):
model_path = name
else:
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
with open(model_path, 'rb') as opened_file:
try:
# loading JIT archive
model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
state_dict = None
except RuntimeError:
# loading saved state dict
if jit:
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
jit = False
state_dict = torch.load(opened_file, map_location="cpu")
if not jit:
model = build_model(state_dict or model.state_dict()).to(device)
if str(device) == "cpu":
model.float()
return model
# patch the device names
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
def patch_device(module):
try:
graphs = [module.graph] if hasattr(module, "graph") else []
except RuntimeError:
graphs = []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("prim::Constant"):
if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
node.copyAttributes(device_node)
model.apply(patch_device)
patch_device(model.encode_image)
patch_device(model.encode_text)
# patch dtype to float32 on CPU
if str(device) == "cpu":
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
float_node = float_input.node()
def patch_float(module):
try:
graphs = [module.graph] if hasattr(module, "graph") else []
except RuntimeError:
graphs = []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("aten::to"):
inputs = list(node.inputs())
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
if inputs[i].node()["value"] == 5:
inputs[i].node().copyAttributes(float_node)
model.apply(patch_float)
patch_float(model.encode_image)
patch_float(model.encode_text)
model.float()
return model | Load a CLIP model Parameters ---------- name : str A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict device : Union[str, torch.device] The device to put the loaded model jit : bool Whether to load the optimized JIT model or more hackable non-JIT model (default). download_root: str path to download the model files; by default, it uses "~/.cache/clip" Returns ------- model : torch.nn.Module The CLIP model preprocess : Callable[[PIL.Image], torch.Tensor] A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input |
167,907 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from .arch_util import load_pretrained_network
FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth'
def _inception_v3(*args, **kwargs):
"""Wraps `torchvision.models.inception_v3`
Skips default weight inititialization if supported by torchvision version.
See https://github.com/mseitzer/pytorch-fid/issues/28.
"""
try:
version = tuple(map(int, torchvision.__version__.split('.')[:2]))
except ValueError:
# Just a caution against weird version strings
version = (0,)
if version >= (0, 6):
kwargs['init_weights'] = False
return torchvision.models.inception_v3(*args, **kwargs)
class FIDInceptionA(torchvision.models.inception.InceptionA):
"""InceptionA block patched for FID computation"""
def __init__(self, in_channels, pool_features):
super(FIDInceptionA, self).__init__(in_channels, pool_features)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branch5x5_2(branch5x5)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
# Patch: Tensorflow's average pool does not use the padded zero's in
# its average calculation
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
count_include_pad=False)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
class FIDInceptionC(torchvision.models.inception.InceptionC):
"""InceptionC block patched for FID computation"""
def __init__(self, in_channels, channels_7x7):
super(FIDInceptionC, self).__init__(in_channels, channels_7x7)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch7x7 = self.branch7x7_1(x)
branch7x7 = self.branch7x7_2(branch7x7)
branch7x7 = self.branch7x7_3(branch7x7)
branch7x7dbl = self.branch7x7dbl_1(x)
branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
# Patch: Tensorflow's average pool does not use the padded zero's in
# its average calculation
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
count_include_pad=False)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
return torch.cat(outputs, 1)
class FIDInceptionE_1(torchvision.models.inception.InceptionE):
"""First InceptionE block patched for FID computation"""
def __init__(self, in_channels):
super(FIDInceptionE_1, self).__init__(in_channels)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch3x3 = self.branch3x3_1(x)
branch3x3 = [
self.branch3x3_2a(branch3x3),
self.branch3x3_2b(branch3x3),
]
branch3x3 = torch.cat(branch3x3, 1)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = [
self.branch3x3dbl_3a(branch3x3dbl),
self.branch3x3dbl_3b(branch3x3dbl),
]
branch3x3dbl = torch.cat(branch3x3dbl, 1)
# Patch: Tensorflow's average pool does not use the padded zero's in
# its average calculation
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
count_include_pad=False)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
class FIDInceptionE_2(torchvision.models.inception.InceptionE):
"""Second InceptionE block patched for FID computation"""
def __init__(self, in_channels):
super(FIDInceptionE_2, self).__init__(in_channels)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch3x3 = self.branch3x3_1(x)
branch3x3 = [
self.branch3x3_2a(branch3x3),
self.branch3x3_2b(branch3x3),
]
branch3x3 = torch.cat(branch3x3, 1)
branch3x3dbl = self.branch3x3dbl_1(x)
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
branch3x3dbl = [
self.branch3x3dbl_3a(branch3x3dbl),
self.branch3x3dbl_3b(branch3x3dbl),
]
branch3x3dbl = torch.cat(branch3x3dbl, 1)
# Patch: The FID Inception model uses max pooling instead of average
# pooling. This is likely an error in this specific Inception
# implementation, as other Inception models use average pooling here
# (which matches the description in the paper).
branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
return torch.cat(outputs, 1)
def load_pretrained_network(net, model_path, strict=True, weight_keys=None):
if model_path.startswith("https://") or model_path.startswith("http://"):
model_path = load_file_from_url(model_path)
print(f"Loading pretrained model {net.__class__.__name__} from {model_path}")
state_dict = torch.load(model_path, map_location=torch.device("cpu"))
if weight_keys is not None:
state_dict = state_dict[weight_keys]
state_dict = clean_state_dict(state_dict)
net.load_state_dict(state_dict, strict=strict)
The provided code snippet includes necessary dependencies for implementing the `fid_inception_v3` function. Write a Python function `def fid_inception_v3()` to solve the following problem:
Build pretrained Inception model for FID computation The Inception model for FID computation uses a different set of weights and has a slightly different structure than torchvision's Inception. This method first constructs torchvision's Inception and then patches the necessary parts that are different in the FID Inception model.
Here is the function:
def fid_inception_v3():
"""Build pretrained Inception model for FID computation
The Inception model for FID computation uses a different set of weights
and has a slightly different structure than torchvision's Inception.
This method first constructs torchvision's Inception and then patches the
necessary parts that are different in the FID Inception model.
"""
inception = _inception_v3(num_classes=1008,
aux_logits=False,
pretrained=False)
inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128)
inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160)
inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160)
inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192)
inception.Mixed_7b = FIDInceptionE_1(1280)
inception.Mixed_7c = FIDInceptionE_2(2048)
load_pretrained_network(inception, FID_WEIGHTS_URL)
return inception | Build pretrained Inception model for FID computation The Inception model for FID computation uses a different set of weights and has a slightly different structure than torchvision's Inception. This method first constructs torchvision's Inception and then patches the necessary parts that are different in the FID Inception model. |
167,908 | import math
import copy
from typing import Optional, List
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
import torchvision.models as models
from .arch_util import load_pretrained_network
from pyiqa.utils.registry import ARCH_REGISTRY
from .arch_util import random_crop
The provided code snippet includes necessary dependencies for implementing the `_get_activation_fn` function. Write a Python function `def _get_activation_fn(activation)` to solve the following problem:
Return an activation function given a string
Here is the function:
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.") | Return an activation function given a string |
167,909 | import math
import copy
from typing import Optional, List
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
import torchvision.models as models
from .arch_util import load_pretrained_network
from pyiqa.utils.registry import ARCH_REGISTRY
from .arch_util import random_crop
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) | null |
167,910 | import torch
import torch.nn as nn
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.utils.color_util import to_y_channel
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `entropy` function. Write a Python function `def entropy(x, data_range=255., eps=1e-8, color_space='yiq')` to solve the following problem:
r"""Compute entropy of a gray scale image. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. Returns: Entropy of the image.
Here is the function:
def entropy(x, data_range=255., eps=1e-8, color_space='yiq'):
r"""Compute entropy of a gray scale image.
Args:
x: An input tensor. Shape :math:`(N, C, H, W)`.
Returns:
Entropy of the image.
"""
if (x.shape[1] == 3):
# Convert RGB image to gray scale and use Y-channel
x = to_y_channel(x, data_range, color_space)
# Compute histogram
hist = nn.functional.one_hot(x.long(), num_classes=int(data_range + 1)).sum(dim=[1, 2, 3])
hist = hist / hist.sum(dim=1, keepdim=True)
# Compute entropy
score = -torch.sum(hist * torch.log2(hist + eps), dim=1)
return score | r"""Compute entropy of a gray scale image. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. Returns: Entropy of the image. |
167,911 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def spatial_average(in_tens, keepdim=True):
return in_tens.mean([2, 3], keepdim=keepdim) | null |
167,912 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def upsample(in_tens, out_HW=(64, 64)): # assumes scale factor is same for H and W
in_H, in_W = in_tens.shape[2], in_tens.shape[3]
return nn.Upsample(size=out_HW, mode="bilinear", align_corners=False)(in_tens) | null |
167,913 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def normalize_tensor(in_feat, eps=1e-10):
norm_factor = torch.sqrt(torch.sum(in_feat**2, dim=1, keepdim=True))
return in_feat / (norm_factor + eps) | null |
167,914 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def get_pad_layer(pad_type):
if pad_type in ["refl", "reflect"]:
PadLayer = nn.ReflectionPad2d
elif pad_type in ["repl", "replicate"]:
PadLayer = nn.ReplicationPad2d
elif pad_type == "zero":
PadLayer = nn.ZeroPad2d
else:
print("Pad type [%s] not recognized" % pad_type)
return PadLayer | null |
167,915 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__init__()
self.features = features
self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, num_classes),
)
if init_weights:
self._initialize_weights()
def forward(self, x):
x = self.features(x)
# print(x.shape)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
if (
m.in_channels != m.out_channels
or m.out_channels != m.groups
or m.bias is not None
):
# don't want to reinitialize downsample layers, code assuming normal conv layers will not have these characteristics
nn.init.kaiming_normal_(
m.weight, mode="fan_out", nonlinearity="relu"
)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
else:
print("Not initializing")
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def make_layers(cfg, batch_norm=False, filter_size=1, pad_more=False, fconv=False):
layers = []
in_channels = 3
for v in cfg:
if v == "M":
# layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
layers += [
nn.MaxPool2d(kernel_size=2, stride=1),
Downsample(
filt_size=filter_size,
stride=2,
channels=in_channels,
pad_more=pad_more,
),
]
else:
if fconv:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=2)
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
else:
layers += [conv2d, nn.ReLU(inplace=True)]
in_channels = v
return nn.Sequential(*layers)
cfg = {
"A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"B": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"D": [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M",],
"E": [64, 64, "M", 128, 128, "M", 256, 256, 256, 256, "M", 512, 512, 512, 512, "M", 512, 512, 512, 512, "M",],
}
The provided code snippet includes necessary dependencies for implementing the `vgg16` function. Write a Python function `def vgg16(pretrained=False, filter_size=1, pad_more=False, fconv=False, **kwargs)` to solve the following problem:
VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def vgg16(pretrained=False, filter_size=1, pad_more=False, fconv=False, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs["init_weights"] = False
model = VGG(
make_layers(cfg["D"], filter_size=filter_size, pad_more=pad_more, fconv=fconv),
**kwargs,
)
# if pretrained:
# model.load_state_dict(model_zoo.load_url(model_urls['vgg16']))
return model | VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
167,916 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.fft import fftshift
import math
from pyiqa.matlab_utils import math_util
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.registry import ARCH_REGISTRY
MAX = nn.MaxPool2d((2, 2), stride=1, padding=1)
def make_csf(rows, cols, nfreq):
xvals = np.arange(-(cols - 1) / 2., (cols + 1) / 2.)
yvals = np.arange(-(rows - 1) / 2., (rows + 1) / 2.)
xplane, yplane = np.meshgrid(xvals, yvals) # generate mesh
plane = ((xplane + 1j * yplane) / cols) * 2 * nfreq
radfreq = np.abs(plane) # radial frequency
w = 0.7
s = (1 - w) / 2 * np.cos(4 * np.angle(plane)) + (1 + w) / 2
radfreq = radfreq / s
# Now generate the CSF
csf = 2.6 * (0.0192 + 0.114 * radfreq) * np.exp(-(0.114 * radfreq)**1.1)
csf[radfreq < 7.8909] = 0.9809
return np.transpose(csf)
def ical_std(x, p=16, s=4):
B, C, H, W = x.shape
x1 = extract_patches_2d(x, patch_shape=[p, p], step=[s, s])
mean, std = get_moments(x1)
mean = mean.reshape(B, C, (H - (p - s)) // s, (W - (p - s)) // s)
std = std.reshape(B, C, (H - (p - s)) // s, (W - (p - s)) // s)
return mean, std
def hi_index(ref_img, dst_img):
k = 0.02874
G = 0.5
C_slope = 1
Ci_thrsh = -5
Cd_thrsh = -5
ref = k * (ref_img + 1e-12)**(2.2 / 3)
dst = k * (torch.abs(dst_img) + 1e-12)**(2.2 / 3)
B, C, H, W = ref.shape
csf = make_csf(H, W, 32)
csf = torch.from_numpy(csf.reshape(1, 1, H, W, 1)).float().repeat(1, C, 1, 1, 2).to(ref.device)
x = torch.fft.fft2(ref)
x1 = math_util.batch_fftshift2d(x)
x2 = math_util.batch_ifftshift2d(x1 * csf)
ref = torch.fft.ifft2(x2).real
x = torch.fft.fft2(dst)
x1 = math_util.batch_fftshift2d(x)
x2 = math_util.batch_ifftshift2d(x1 * csf)
dst = torch.fft.ifft2(x2).real
m1_1, std_1 = ical_std(ref)
B, C, H1, W1 = m1_1.shape
std_1 = (-MAX(-std_1) / 2)[:, :, :H1, :W1]
_, std_2 = ical_std(dst - ref)
BSIZE = 16
eps = 1e-12
Ci_ref = torch.log(torch.abs((std_1 + eps) / (m1_1 + eps)))
Ci_dst = torch.log(torch.abs((std_2 + eps) / (m1_1 + eps)))
Ci_dst = Ci_dst.masked_fill(m1_1 < G, -1000)
idx1 = (Ci_ref > Ci_thrsh) & (Ci_dst > (C_slope * (Ci_ref - Ci_thrsh) + Cd_thrsh))
idx2 = (Ci_ref <= Ci_thrsh) & (Ci_dst > Cd_thrsh)
msk = Ci_ref.clone()
msk = msk.masked_fill(~idx1, 0)
msk = msk.masked_fill(~idx2, 0)
msk[idx1] = Ci_dst[idx1] - (C_slope * (Ci_ref[idx1] - Ci_thrsh) + Cd_thrsh)
msk[idx2] = Ci_dst[idx2] - Cd_thrsh
win = torch.ones((1, 1, BSIZE, BSIZE)).repeat(C, 1, 1, 1).to(ref.device) / BSIZE**2
xx = (ref_img - dst_img)**2
lmse = F.conv2d(xx, win, stride=4, padding=0, groups=C)
mp = msk * lmse
B, C, H, W = mp.shape
return torch.norm(mp.reshape(B, C, -1), dim=2) / math.sqrt(H * W) * 200 | null |
167,917 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.fft import fftshift
import math
from pyiqa.matlab_utils import math_util
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.registry import ARCH_REGISTRY
def ical_stat(x, p=16, s=4):
B, C, H, W = x.shape
x1 = extract_patches_2d(x, patch_shape=[p, p], step=[s, s])
_, std, skews, kurt = get_moments(x1, sk=True)
STD = std.reshape(B, C, (H - (p - s)) // s, (W - (p - s)) // s)
SKEWS = skews.reshape(B, C, (H - (p - s)) // s, (W - (p - s)) // s)
KURT = kurt.reshape(B, C, (H - (p - s)) // s, (W - (p - s)) // s)
return STD, SKEWS, KURT # different with original version
def gaborconvolve(im):
nscale = 5 # Number of wavelet scales.
norient = 4 # Number of filter orientations.
minWaveLength = 3 # Wavelength of smallest scale filter.
mult = 3 # Scaling factor between successive filters.
sigmaOnf = 0.55 # Ratio of the standard deviation of the
wavelength = [
minWaveLength, minWaveLength * mult, minWaveLength * mult**2, minWaveLength * mult**3, minWaveLength * mult**4
]
# Ratio of angular interval between filter orientations
dThetaOnSigma = 1.5
# Fourier transform of image
B, C, rows, cols = im.shape
# imagefft = torch.rfft(im,2, onesided=False)
imagefft = torch.fft.fft2(im)
# Pre-compute to speed up filter construction
x = np.ones((rows, 1)) * np.arange(-cols / 2., (cols / 2.)) / (cols / 2.)
y = np.dot(np.expand_dims(np.arange(-rows / 2., (rows / 2.)), 1), np.ones((1, cols)) / (rows / 2.))
# Matrix values contain *normalised* radius from centre.
radius = np.sqrt(x**2 + y**2)
# Get rid of the 0 radius value in the middle
radius[int(np.round(rows / 2 + 1)), int(np.round(cols / 2 + 1))] = 1
radius = np.log(radius + 1e-12)
# Matrix values contain polar angle.
theta = np.arctan2(-y, x)
sintheta = np.sin(theta)
costheta = np.cos(theta)
# Calculate the standard deviation
thetaSigma = math.pi / norient / dThetaOnSigma
logGabors = []
for s in range(nscale):
# Construct the filter - first calculate the radial filter component.
fo = 1.0 / wavelength[s] # Centre frequency of filter.
rfo = fo / 0.5 # Normalised radius from centre of frequency plane
# corresponding to fo.
tmp = -(2 * np.log(sigmaOnf)**2)
tmp2 = np.log(rfo)
logGabors.append(np.exp((radius - tmp2)**2 / tmp))
logGabors[s][int(np.round(rows / 2)), int(np.round(cols / 2))] = 0
E0 = [[], [], [], []]
for o in range(norient):
# Calculate filter angle.
angl = o * math.pi / norient
ds = sintheta * np.cos(angl) - costheta * np.sin(angl) # Difference in sine.
dc = costheta * np.cos(angl) + sintheta * np.sin(angl) # Difference in cosine.
dtheta = np.abs(np.arctan2(ds, dc)) # Absolute angular distance.
spread = np.exp((-dtheta**2) / (2 * thetaSigma**2)) # Calculate the angular filter component.
for s in range(nscale):
filter = fftshift(logGabors[s] * spread)
filter = torch.from_numpy(filter).reshape(1, 1, rows, cols).to(im.device)
e0 = torch.fft.ifft2(imagefft * filter)
E0[o].append(torch.stack((e0.real, e0.imag), -1))
return E0
def lo_index(ref, dst):
gabRef = gaborconvolve(ref)
gabDst = gaborconvolve(dst)
s = [0.5 / 13.25, 0.75 / 13.25, 1 / 13.25, 5 / 13.25, 6 / 13.25]
mp = 0
for gb_i in range(4):
for gb_j in range(5):
stdref, skwref, krtref = ical_stat(math_util.abs(gabRef[gb_i][gb_j]))
stddst, skwdst, krtdst = ical_stat(math_util.abs(gabDst[gb_i][gb_j]))
mp = mp + s[gb_i] * (
torch.abs(stdref - stddst) + 2 * torch.abs(skwref - skwdst) + torch.abs(krtref - krtdst))
B, C, rows, cols = mp.shape
return torch.norm(mp.reshape(B, C, -1), dim=2) / np.sqrt(rows * cols) | null |
167,918 | from typing import Tuple
import torch
import torch.nn.functional as F
from pyiqa.utils.color_util import to_y_channel
from pyiqa.matlab_utils import fspecial, imfilter, exact_padding_2d
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `preprocess_rgb` function. Write a Python function `def preprocess_rgb(x, test_y_channel, data_range: float = 1, color_space="yiq")` to solve the following problem:
Preprocesses an RGB image tensor. Args: - x (torch.Tensor): The input RGB image tensor. - test_y_channel (bool): Whether to test the Y channel. - data_range (float): The data range of the input tensor. Default is 1. - color_space (str): The color space of the input tensor. Default is "yiq". Returns: torch.Tensor: The preprocessed RGB image tensor.
Here is the function:
def preprocess_rgb(x, test_y_channel, data_range: float = 1, color_space="yiq"):
"""
Preprocesses an RGB image tensor.
Args:
- x (torch.Tensor): The input RGB image tensor.
- test_y_channel (bool): Whether to test the Y channel.
- data_range (float): The data range of the input tensor. Default is 1.
- color_space (str): The color space of the input tensor. Default is "yiq".
Returns:
torch.Tensor: The preprocessed RGB image tensor.
"""
if test_y_channel and x.shape[1] == 3:
x = to_y_channel(x, data_range, color_space)
else:
x = x * data_range
# use rounded uint8 value to make the input image same as MATLAB
if data_range == 255:
x = x - x.detach() + x.round()
return x | Preprocesses an RGB image tensor. Args: - x (torch.Tensor): The input RGB image tensor. - test_y_channel (bool): Whether to test the Y channel. - data_range (float): The data range of the input tensor. Default is 1. - color_space (str): The color space of the input tensor. Default is "yiq". Returns: torch.Tensor: The preprocessed RGB image tensor. |
167,919 | from typing import Tuple
import torch
import torch.nn.functional as F
from pyiqa.utils.color_util import to_y_channel
from pyiqa.matlab_utils import fspecial, imfilter, exact_padding_2d
The provided code snippet includes necessary dependencies for implementing the `torch_cov` function. Write a Python function `def torch_cov(tensor, rowvar=True, bias=False)` to solve the following problem:
r"""Estimate a covariance matrix (np.cov) Ref: https://gist.github.com/ModarTensai/5ab449acba9df1a26c12060240773110
Here is the function:
def torch_cov(tensor, rowvar=True, bias=False):
r"""Estimate a covariance matrix (np.cov)
Ref: https://gist.github.com/ModarTensai/5ab449acba9df1a26c12060240773110
"""
tensor = tensor if rowvar else tensor.transpose(-1, -2)
tensor = tensor - tensor.mean(dim=-1, keepdim=True)
factor = 1 / (tensor.shape[-1] - int(not bool(bias)))
return factor * tensor @ tensor.transpose(-1, -2) | r"""Estimate a covariance matrix (np.cov) Ref: https://gist.github.com/ModarTensai/5ab449acba9df1a26c12060240773110 |
167,920 | import torch
from pyiqa.utils.color_util import to_y_channel
from pyiqa.matlab_utils import imresize
from .func_util import estimate_ggd_param, estimate_aggd_param, normalize_img_with_guass
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.utils.registry import ARCH_REGISTRY
def natural_scene_statistics(luma: torch.Tensor, kernel_size: int = 7, sigma: float = 7. / 6) -> torch.Tensor:
luma_nrmlzd = normalize_img_with_guass(luma, kernel_size, sigma, padding='same')
alpha, sigma = estimate_ggd_param(luma_nrmlzd)
features = [alpha, sigma.pow(2)]
shifts = [(0, 1), (1, 0), (1, 1), (-1, 1)]
for shift in shifts:
shifted_luma_nrmlzd = torch.roll(luma_nrmlzd, shifts=shift, dims=(-2, -1))
alpha, sigma_l, sigma_r = estimate_aggd_param(luma_nrmlzd * shifted_luma_nrmlzd, return_sigma=True)
eta = (sigma_r - sigma_l
) * torch.exp(torch.lgamma(2. / alpha) - (torch.lgamma(1. / alpha) + torch.lgamma(3. / alpha)) / 2)
features.extend((alpha, eta, sigma_l.pow(2), sigma_r.pow(2)))
return torch.stack(features, dim=-1)
def scale_features(features: torch.Tensor) -> torch.Tensor:
lower_bound = -1
upper_bound = 1
# Feature range is taken from official implementation of BRISQUE on MATLAB.
# Source: https://live.ece.utexas.edu/research/Quality/index_algorithms.htm
feature_ranges = torch.tensor([[0.338, 10], [0.017204, 0.806612], [0.236, 1.642], [-0.123884, 0.20293],
[0.000155, 0.712298], [0.001122, 0.470257], [0.244, 1.641], [-0.123586, 0.179083],
[0.000152, 0.710456], [0.000975, 0.470984], [0.249, 1.555], [-0.135687, 0.100858],
[0.000174, 0.684173], [0.000913, 0.534174], [0.258, 1.561], [-0.143408, 0.100486],
[0.000179, 0.685696], [0.000888, 0.536508], [0.471, 3.264], [0.012809, 0.703171],
[0.218, 1.046], [-0.094876, 0.187459], [1.5e-005, 0.442057], [0.001272, 0.40803],
[0.222, 1.042], [-0.115772, 0.162604], [1.6e-005, 0.444362], [0.001374, 0.40243],
[0.227, 0.996], [-0.117188, 0.09832299999999999], [3e-005, 0.531903],
[0.001122, 0.369589], [0.228, 0.99], [-0.12243, 0.098658], [2.8e-005, 0.530092],
[0.001118, 0.370399]]).to(features)
scaled_features = lower_bound + (upper_bound - lower_bound) * (features - feature_ranges[..., 0]) / (
feature_ranges[..., 1] - feature_ranges[..., 0])
return scaled_features
def rbf_kernel(features: torch.Tensor, sv: torch.Tensor, gamma: float = 0.05) -> torch.Tensor:
dist = (features.unsqueeze(dim=-1) - sv.unsqueeze(dim=0)).pow(2).sum(dim=1)
return torch.exp(-dist * gamma)
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `brisque` function. Write a Python function `def brisque(x: torch.Tensor, kernel_size: int = 7, kernel_sigma: float = 7 / 6, test_y_channel: bool = True, pretrained_model_path: str = None) -> torch.Tensor` to solve the following problem:
r"""Interface of BRISQUE index. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - kernel_size: The side-length of the sliding window used in comparison. Must be an odd value. - kernel_sigma: Sigma of normal distribution. - data_range: Maximum value range of images (usually 1.0 or 255). - to_y_channel: Whether use the y-channel of YCBCR. pretrained_model_path: The model path. Returns: Value of BRISQUE index. References: Mittal, Anish, Anush Krishna Moorthy, and Alan Conrad Bovik. "No-reference image quality assessment in the spatial domain." IEEE Transactions on image processing 21, no. 12 (2012): 4695-4708.
Here is the function:
def brisque(x: torch.Tensor,
kernel_size: int = 7,
kernel_sigma: float = 7 / 6,
test_y_channel: bool = True,
pretrained_model_path: str = None) -> torch.Tensor:
r"""Interface of BRISQUE index.
Args:
- x: An input tensor. Shape :math:`(N, C, H, W)`.
- kernel_size: The side-length of the sliding window used in comparison. Must be an odd value.
- kernel_sigma: Sigma of normal distribution.
- data_range: Maximum value range of images (usually 1.0 or 255).
- to_y_channel: Whether use the y-channel of YCBCR.
pretrained_model_path: The model path.
Returns:
Value of BRISQUE index.
References:
Mittal, Anish, Anush Krishna Moorthy, and Alan Conrad Bovik.
"No-reference image quality assessment in the spatial domain."
IEEE Transactions on image processing 21, no. 12 (2012): 4695-4708.
"""
if test_y_channel and x.size(1) == 3:
x = to_y_channel(x, 255.)
else:
x = x * 255
features = []
num_of_scales = 2
for _ in range(num_of_scales):
features.append(natural_scene_statistics(x, kernel_size, kernel_sigma))
x = imresize(x, scale=0.5, antialiasing=True)
features = torch.cat(features, dim=-1)
scaled_features = scale_features(features)
if pretrained_model_path:
sv_coef, sv = torch.load(pretrained_model_path)
sv_coef = sv_coef.to(x)
sv = sv.to(x)
# gamma and rho are SVM model parameters taken from official implementation of BRISQUE on MATLAB
# Source: https://live.ece.utexas.edu/research/Quality/index_algorithms.htm
gamma = 0.05
rho = -153.591
sv.t_()
kernel_features = rbf_kernel(features=scaled_features, sv=sv, gamma=gamma)
score = kernel_features @ sv_coef
return score - rho | r"""Interface of BRISQUE index. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - kernel_size: The side-length of the sliding window used in comparison. Must be an odd value. - kernel_sigma: Sigma of normal distribution. - data_range: Maximum value range of images (usually 1.0 or 255). - to_y_channel: Whether use the y-channel of YCBCR. pretrained_model_path: The model path. Returns: Value of BRISQUE index. References: Mittal, Anish, Anush Krishna Moorthy, and Alan Conrad Bovik. "No-reference image quality assessment in the spatial domain." IEEE Transactions on image processing 21, no. 12 (2012): 4695-4708. |
167,921 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def upsample(in_tens, out_HW=(64, 64)): # assumes scale factor is same for H and W
return nn.Upsample(size=out_HW, mode='bilinear', align_corners=False)(in_tens) | null |
167,922 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def spatial_average(in_tens, keepdim=True):
return in_tens.mean([2, 3], keepdim=keepdim) | null |
167,923 | import torch
from torchvision import models
import torch.nn as nn
from collections import namedtuple
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def normalize_tensor(in_feat, eps=1e-10):
norm_factor = torch.sqrt(torch.sum(in_feat**2, dim=1, keepdim=True))
return in_feat / (norm_factor + eps) | null |
167,924 | import torch
import torch.nn as nn
import math
import torchvision as tv
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1)` to solve the following problem:
3x3 convolution with padding
Here is the function:
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=dilation,
groups=groups,
bias=False,
dilation=dilation) | 3x3 convolution with padding |
167,925 | import torch
import torch.nn as nn
import math
import torchvision as tv
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_planes, out_planes, stride=1)` to solve the following problem:
1x1 convolution
Here is the function:
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | 1x1 convolution |
167,926 | import torch
import torch.nn as nn
import math
import torchvision as tv
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
}
class ResNet(nn.Module):
def __init__(self,
block,
layers,
num_classes=1000,
zero_init_residual=False,
groups=1,
width_per_group=64,
replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
self.k = 3
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError('replace_stride_with_dilation should be None '
'or a 3-element tuple, got {}'.format(replace_stride_with_dilation))
self.groups = groups
self.base_width = width_per_group
self.head = 8
self.qse_1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
self.qse_2 = self._make_layer(block, 64, layers[0])
self.csp = self._make_layer(block, 128, layers[1], stride=2, dilate=False)
self.inplanes = 64
self.dte_1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
self.dte_2 = self._make_layer(block, 64, layers[0])
self.aux_csp = self._make_layer(block, 128, layers[1], stride=2, dilate=False)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc_ = nn.Sequential(
nn.Linear((512) * 1 * 1, 2048),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(2048, 2048),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(2048, 1),
)
self.fc1_ = nn.Sequential(
nn.Linear((512) * 1 * 1, 2048),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(2048, 2048),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(2048, 1),
)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(
block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation,
norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(
block(
self.inplanes,
planes,
groups=self.groups,
base_width=self.base_width,
dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x, y):
rest1 = x
dist1 = y
rest1 = self.qse_2(self.maxpool(self.qse_1(rest1)))
dist1 = self.dte_2(self.maxpool(self.dte_1(dist1)))
x = rest1 - dist1
x = self.csp(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
dr = torch.sigmoid(self.fc_(x))
return dr
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
keys = state_dict.keys()
for key in list(keys):
if 'conv1' in key:
state_dict[key.replace('conv1', 'qse_1')] = state_dict[key]
state_dict[key.replace('conv1', 'dte_1')] = state_dict[key]
if 'layer1' in key:
state_dict[key.replace('layer1', 'qse_2')] = state_dict[key]
state_dict[key.replace('layer1', 'dte_2')] = state_dict[key]
if 'layer2' in key:
state_dict[key.replace('layer2', 'csp')] = state_dict[key]
state_dict[key.replace('layer2', 'aux_csp')] = state_dict[key]
model.load_state_dict(state_dict, strict=False)
return model | null |
167,927 | import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch import nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size)` to solve the following problem:
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
Here is the function:
def window_partition(x, window_size):
"""
Args:
x: (B, H, W, C)
window_size (int): window size
Returns:
windows: (num_windows*B, window_size, window_size, C)
"""
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
return windows | Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
167,928 | import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch import nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size, H, W)` to solve the following problem:
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
Here is the function:
def window_reverse(windows, window_size, H, W):
"""
Args:
windows: (num_windows*B, window_size, window_size, C)
window_size (int): Window size
H (int): Height of image
W (int): Width of image
Returns:
x: (B, H, W, C)
"""
B = int(windows.shape[0] / (H * W / window_size / window_size))
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
return x | Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) |
167,929 | from collections import OrderedDict
import collections.abc
from itertools import repeat
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
import torchvision.transforms as T
from .constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from pyiqa.utils.download_util import load_file_from_url
The provided code snippet includes necessary dependencies for implementing the `dist_to_mos` function. Write a Python function `def dist_to_mos(dist_score: torch.Tensor) -> torch.Tensor` to solve the following problem:
Convert distribution prediction to mos score. For datasets with detailed score labels, such as AVA Args: dist_score (tensor): (*, C), C is the class number Output: mos_score (tensor): (*, 1)
Here is the function:
def dist_to_mos(dist_score: torch.Tensor) -> torch.Tensor:
"""Convert distribution prediction to mos score.
For datasets with detailed score labels, such as AVA
Args:
dist_score (tensor): (*, C), C is the class number
Output:
mos_score (tensor): (*, 1)
"""
num_classes = dist_score.shape[-1]
mos_score = dist_score * torch.arange(1, num_classes + 1).to(dist_score)
mos_score = mos_score.sum(dim=-1, keepdim=True)
return mos_score | Convert distribution prediction to mos score. For datasets with detailed score labels, such as AVA Args: dist_score (tensor): (*, C), C is the class number Output: mos_score (tensor): (*, 1) |
167,930 | from collections import OrderedDict
import collections.abc
from itertools import repeat
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
import torchvision.transforms as T
from .constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from pyiqa.utils.download_util import load_file_from_url
to_2tuple = _ntuple(2)
The provided code snippet includes necessary dependencies for implementing the `random_crop` function. Write a Python function `def random_crop(input_list, crop_size, crop_num)` to solve the following problem:
Randomly crops the input tensor(s) to the specified size and number of crops. Args: - input_list (list or tensor): List of input tensors or a single input tensor. - crop_size (int or tuple): Size of the crop. If an int is provided, a square crop of that size is used. If a tuple is provided, a crop of that size is used. - crop_num (int): Number of crops to generate. Returns: tensor or list of tensors: If a single input tensor is provided, a tensor of cropped images is returned. If a list of input tensors is provided, a list of tensors of cropped images is returned.
Here is the function:
def random_crop(input_list, crop_size, crop_num):
"""
Randomly crops the input tensor(s) to the specified size and number of crops.
Args:
- input_list (list or tensor): List of input tensors or a single input tensor.
- crop_size (int or tuple): Size of the crop. If an int is provided, a square crop of that size is used.
If a tuple is provided, a crop of that size is used.
- crop_num (int): Number of crops to generate.
Returns:
tensor or list of tensors: If a single input tensor is provided, a tensor of cropped images is returned.
If a list of input tensors is provided, a list of tensors of cropped images is returned.
"""
if not isinstance(input_list, collections.abc.Sequence):
input_list = [input_list]
b, c, h, w = input_list[0].shape
ch, cw = to_2tuple(crop_size)
if min(h, w) <= crop_size:
scale_factor = (crop_size + 1) / min(h, w)
input_list = [
F.interpolate(x, scale_factor=scale_factor, mode="bilinear")
for x in input_list
]
b, c, h, w = input_list[0].shape
crops_list = [[] for i in range(len(input_list))]
for i in range(crop_num):
sh = np.random.randint(0, h - ch + 1)
sw = np.random.randint(0, w - cw + 1)
for j in range(len(input_list)):
crops_list[j].append(input_list[j][..., sh : sh + ch, sw : sw + cw])
for i in range(len(crops_list)):
crops_list[i] = torch.stack(crops_list[i], dim=1).reshape(
b * crop_num, c, ch, cw
)
if len(crops_list) == 1:
crops_list = crops_list[0]
return crops_list | Randomly crops the input tensor(s) to the specified size and number of crops. Args: - input_list (list or tensor): List of input tensors or a single input tensor. - crop_size (int or tuple): Size of the crop. If an int is provided, a square crop of that size is used. If a tuple is provided, a crop of that size is used. - crop_num (int): Number of crops to generate. Returns: tensor or list of tensors: If a single input tensor is provided, a tensor of cropped images is returned. If a list of input tensors is provided, a list of tensors of cropped images is returned. |
167,931 | from collections import OrderedDict
import collections.abc
from itertools import repeat
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
import torchvision.transforms as T
from .constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from pyiqa.utils.download_util import load_file_from_url
OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
The provided code snippet includes necessary dependencies for implementing the `clip_preprocess_tensor` function. Write a Python function `def clip_preprocess_tensor(x: torch.Tensor, model)` to solve the following problem:
clip preprocess function with tensor input. NOTE: Results are slightly different with original preprocess function with PIL image input, because of differences in resize function.
Here is the function:
def clip_preprocess_tensor(x: torch.Tensor, model):
"""clip preprocess function with tensor input.
NOTE: Results are slightly different with original preprocess function with PIL image input, because of differences in resize function.
"""
# Bicubic interpolation
x = T.functional.resize(
x,
model.visual.input_resolution,
interpolation=T.InterpolationMode.BICUBIC,
antialias=True,
)
# Center crop
x = T.functional.center_crop(x, model.visual.input_resolution)
x = T.functional.normalize(x, OPENAI_CLIP_MEAN, OPENAI_CLIP_STD)
return x | clip preprocess function with tensor input. NOTE: Results are slightly different with original preprocess function with PIL image input, because of differences in resize function. |
167,932 | from collections import OrderedDict
import collections.abc
from itertools import repeat
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
import torchvision.transforms as T
from .constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from pyiqa.utils.download_util import load_file_from_url
def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable):
return x
return tuple(repeat(x, n))
return parse | null |
167,933 | from collections import OrderedDict
import collections.abc
from itertools import repeat
import numpy as np
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
import torchvision.transforms as T
from .constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from pyiqa.utils.download_util import load_file_from_url
The provided code snippet includes necessary dependencies for implementing the `default_init_weights` function. Write a Python function `def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs)` to solve the following problem:
r"""Initialize network weights. Args: - module_list (list[nn.Module] | nn.Module): Modules to be initialized. - scale (float): Scale initialized weights, especially for residual blocks. Default: 1. - bias_fill (float): The value to fill bias. Default: 0. - kwargs (dict): Other arguments for initialization function.
Here is the function:
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
r"""Initialize network weights.
Args:
- module_list (list[nn.Module] | nn.Module): Modules to be initialized.
- scale (float): Scale initialized weights, especially for residual
blocks. Default: 1.
- bias_fill (float): The value to fill bias. Default: 0.
- kwargs (dict): Other arguments for initialization function.
"""
if not isinstance(module_list, list):
module_list = [module_list]
for module in module_list:
for m in module.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, **kwargs)
m.weight.data *= scale
if m.bias is not None:
m.bias.data.fill_(bias_fill)
elif isinstance(m, nn.Linear):
init.kaiming_normal_(m.weight, **kwargs)
m.weight.data *= scale
if m.bias is not None:
m.bias.data.fill_(bias_fill)
elif isinstance(m, _BatchNorm):
init.constant_(m.weight, 1)
if m.bias is not None:
m.bias.data.fill_(bias_fill) | r"""Initialize network weights. Args: - module_list (list[nn.Module] | nn.Module): Modules to be initialized. - scale (float): Scale initialized weights, especially for residual blocks. Default: 1. - bias_fill (float): The value to fill bias. Default: 0. - kwargs (dict): Other arguments for initialization function. |
167,934 | import torch
from torch import nn
from torch.nn import functional as F
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.registry import ARCH_REGISTRY
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `gmsd` function. Write a Python function `def gmsd( x: torch.Tensor, y: torch.Tensor, T: int = 170, channels: int = 3, test_y_channel: bool = True, ) -> torch.Tensor` to solve the following problem:
r"""GMSD metric. Args: - x: A distortion tensor. Shape :math:`(N, C, H, W)`. - y: A reference tensor. Shape :math:`(N, C, H, W)`. - T: A positive constant that supplies numerical stability. - channels: Number of channels. - test_y_channel: bool, whether to use y channel on ycbcr.
Here is the function:
def gmsd(
x: torch.Tensor,
y: torch.Tensor,
T: int = 170,
channels: int = 3,
test_y_channel: bool = True,
) -> torch.Tensor:
r"""GMSD metric.
Args:
- x: A distortion tensor. Shape :math:`(N, C, H, W)`.
- y: A reference tensor. Shape :math:`(N, C, H, W)`.
- T: A positive constant that supplies numerical stability.
- channels: Number of channels.
- test_y_channel: bool, whether to use y channel on ycbcr.
"""
if test_y_channel:
x = to_y_channel(x, 255)
y = to_y_channel(y, 255)
channels = 1
else:
x = x * 255.
y = y * 255.
dx = (torch.Tensor([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) / 3.).unsqueeze(0).unsqueeze(0).repeat(channels, 1, 1,
1).to(x)
dy = (torch.Tensor([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) / 3.).unsqueeze(0).unsqueeze(0).repeat(channels, 1, 1,
1).to(x)
aveKernel = torch.ones(channels, 1, 2, 2).to(x) / 4.
Y1 = F.conv2d(x, aveKernel, stride=2, padding=0, groups=channels)
Y2 = F.conv2d(y, aveKernel, stride=2, padding=0, groups=channels)
IxY1 = F.conv2d(Y1, dx, stride=1, padding=1, groups=channels)
IyY1 = F.conv2d(Y1, dy, stride=1, padding=1, groups=channels)
gradientMap1 = torch.sqrt(IxY1**2 + IyY1**2 + 1e-12)
IxY2 = F.conv2d(Y2, dx, stride=1, padding=1, groups=channels)
IyY2 = F.conv2d(Y2, dy, stride=1, padding=1, groups=channels)
gradientMap2 = torch.sqrt(IxY2**2 + IyY2**2 + 1e-12)
quality_map = (2 * gradientMap1 * gradientMap2 + T) / (gradientMap1**2 + gradientMap2**2 + T)
score = torch.std(quality_map.view(quality_map.shape[0], -1), dim=1)
return score | r"""GMSD metric. Args: - x: A distortion tensor. Shape :math:`(N, C, H, W)`. - y: A reference tensor. Shape :math:`(N, C, H, W)`. - T: A positive constant that supplies numerical stability. - channels: Number of channels. - test_y_channel: bool, whether to use y channel on ycbcr. |
167,935 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import nn, einsum
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from einops import rearrange
from functools import partial
import math
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
def padding_img(img):
b, c, h, w = img.shape
h_out = math.ceil(h / 32) * 32
w_out = math.ceil(w / 32) * 32
left_pad = (w_out- w) // 2
right_pad = w_out - w - left_pad
top_pad = (h_out - h) // 2
bottom_pad = h_out - h - top_pad
img = nn.ZeroPad2d((left_pad, right_pad, top_pad, bottom_pad))(img)
return img
def build_historgram(img):
b, _, _, _ = img.shape
r_his = torch.histc(img[0][0], 64, min=0.0, max=1.0)
g_his = torch.histc(img[0][1], 64, min=0.0, max=1.0)
b_his = torch.histc(img[0][2], 64, min=0.0, max=1.0)
historgram = torch.cat((r_his, g_his, b_his)).unsqueeze(0).unsqueeze(0)
for i in range(1, b):
r_his = torch.histc(img[i][0], 64, min=0.0, max=1.0)
g_his = torch.histc(img[i][1], 64, min=0.0, max=1.0)
b_his = torch.histc(img[i][2], 64, min=0.0, max=1.0)
historgram_temp = torch.cat((r_his, g_his, b_his)).unsqueeze(0).unsqueeze(0)
historgram = torch.cat((historgram, historgram_temp), dim=0)
return historgram
def preprocessing(d_img_org):
d_img_org = padding_img(d_img_org)
x_his = build_historgram(d_img_org)
return d_img_org, x_his | null |
167,936 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .arch_util import dist_to_mos, load_pretrained_network
from pyiqa.matlab_utils import ExactPadding2d, exact_padding_2d
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.data.multiscale_trans_util import get_multiscale_patches
def drop_path(x, drop_prob: float = 0., training: bool = False):
if drop_prob == 0. or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0], ) + (1, ) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
random_tensor.floor_() # binarize
output = x.div(keep_prob) * random_tensor
return output | null |
167,937 | import math
import numpy as np
import scipy
import scipy.io
import torch
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.matlab_utils import imresize, fspecial, conv2d, imfilter, fitweibull, nancov, nanmean, blockproc
from .func_util import estimate_aggd_param, normalize_img_with_guass, diff_round
from pyiqa.archs.fsim_arch import _construct_filters
from pyiqa.utils.registry import ARCH_REGISTRY
def niqe(img: torch.Tensor,
mu_pris_param: torch.Tensor,
cov_pris_param: torch.Tensor,
block_size_h: int = 96,
block_size_w: int = 96) -> torch.Tensor:
"""Calculate NIQE (Natural Image Quality Evaluator) metric.
Args:
img (Tensor): Input image.
mu_pris_param (Tensor): Mean of a pre-defined multivariate Gaussian
model calculated on the pristine dataset.
cov_pris_param (Tensor): Covariance of a pre-defined multivariate
Gaussian model calculated on the pristine dataset.
gaussian_window (Tensor): A 7x7 Gaussian window used for smoothing the image.
block_size_h (int): Height of the blocks in to which image is divided.
Default: 96 (the official recommended value).
block_size_w (int): Width of the blocks in to which image is divided.
Default: 96 (the official recommended value).
"""
assert img.ndim == 4, ('Input image must be a gray or Y (of YCbCr) image with shape (b, c, h, w).')
# crop image
b, c, h, w = img.shape
num_block_h = math.floor(h / block_size_h)
num_block_w = math.floor(w / block_size_w)
img = img[..., 0:num_block_h * block_size_h, 0:num_block_w * block_size_w]
distparam = [] # dist param is actually the multiscale features
for scale in (1, 2): # perform on two scales (1, 2)
img_normalized = normalize_img_with_guass(img, padding='replicate')
distparam.append(blockproc(img_normalized, [block_size_h // scale, block_size_w // scale], fun=compute_feature))
if scale == 1:
img = imresize(img / 255., scale=0.5, antialiasing=True)
img = img * 255.
distparam = torch.cat(distparam, -1)
# fit a MVG (multivariate Gaussian) model to distorted patch features
mu_distparam = nanmean(distparam, dim=1)
cov_distparam = nancov(distparam)
# compute niqe quality, Eq. 10 in the paper
invcov_param = torch.linalg.pinv((cov_pris_param + cov_distparam) / 2)
diff = (mu_pris_param - mu_distparam).unsqueeze(1)
quality = torch.bmm(torch.bmm(diff, invcov_param), diff.transpose(1, 2)).squeeze()
quality = torch.sqrt(quality)
return quality
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
def diff_round(x: torch.Tensor) -> torch.Tensor:
r"""Differentiable round."""
return x - x.detach() + x.round()
The provided code snippet includes necessary dependencies for implementing the `calculate_niqe` function. Write a Python function `def calculate_niqe(img: torch.Tensor, crop_border: int = 0, test_y_channel: bool = True, pretrained_model_path: str = None, color_space: str = 'yiq', **kwargs) -> torch.Tensor` to solve the following problem:
Calculate NIQE (Natural Image Quality Evaluator) metric. Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'. pretrained_model_path (str): The pretrained model path. Returns: Tensor: NIQE result.
Here is the function:
def calculate_niqe(img: torch.Tensor,
crop_border: int = 0,
test_y_channel: bool = True,
pretrained_model_path: str = None,
color_space: str = 'yiq',
**kwargs) -> torch.Tensor:
"""Calculate NIQE (Natural Image Quality Evaluator) metric.
Args:
img (Tensor): Input image whose quality needs to be computed.
crop_border (int): Cropped pixels in each edge of an image. These
pixels are not involved in the metric calculation.
test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'.
pretrained_model_path (str): The pretrained model path.
Returns:
Tensor: NIQE result.
"""
params = scipy.io.loadmat(pretrained_model_path)
mu_pris_param = np.ravel(params['mu_prisparam'])
cov_pris_param = params['cov_prisparam']
mu_pris_param = torch.from_numpy(mu_pris_param).to(img)
cov_pris_param = torch.from_numpy(cov_pris_param).to(img)
mu_pris_param = mu_pris_param.repeat(img.size(0), 1)
cov_pris_param = cov_pris_param.repeat(img.size(0), 1, 1)
# NIQE only support gray image
if img.shape[1] == 3:
img = to_y_channel(img, 255, color_space)
elif img.shape[1] == 1:
img = img * 255
img = diff_round(img)
img = img.to(torch.float64)
if crop_border != 0:
img = img[..., crop_border:-crop_border, crop_border:-crop_border]
niqe_result = niqe(img, mu_pris_param, cov_pris_param)
return niqe_result | Calculate NIQE (Natural Image Quality Evaluator) metric. Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'. pretrained_model_path (str): The pretrained model path. Returns: Tensor: NIQE result. |
167,938 | import math
import numpy as np
import scipy
import scipy.io
import torch
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.matlab_utils import imresize, fspecial, conv2d, imfilter, fitweibull, nancov, nanmean, blockproc
from .func_util import estimate_aggd_param, normalize_img_with_guass, diff_round
from pyiqa.archs.fsim_arch import _construct_filters
from pyiqa.utils.registry import ARCH_REGISTRY
def ilniqe(img: torch.Tensor,
mu_pris_param: torch.Tensor,
cov_pris_param: torch.Tensor,
principleVectors: torch.Tensor,
meanOfSampleData: torch.Tensor,
resize: bool = True,
block_size_h: int = 84,
block_size_w: int = 84) -> torch.Tensor:
"""Calculate IL-NIQE (Integrated Local Natural Image Quality Evaluator) metric.
Args:
img (Tensor): Input image.
mu_pris_param (Tensor): Mean of a pre-defined multivariate Gaussian
model calculated on the pristine dataset.
cov_pris_param (Tensor): Covariance of a pre-defined multivariate
Gaussian model calculated on the pristine dataset.
principleVectors (Tensor): Features from official .mat file.
meanOfSampleData (Tensor): Features from official .mat file.
resize (Bloolean): resize image. Default: True.
block_size_h (int): Height of the blocks in to which image is divided.
Default: 84 (the official recommended value).
block_size_w (int): Width of the blocks in to which image is divided.
Default: 84 (the official recommended value).
"""
assert img.ndim == 4, ('Input image must be a gray or Y (of YCbCr) image with shape (b, c, h, w).')
sigmaForGauDerivative = 1.66
KforLog = 0.00001
normalizedWidth = 524
minWaveLength = 2.4
sigmaOnf = 0.55
mult = 1.31
dThetaOnSigma = 1.10
scaleFactorForLoG = 0.87
scaleFactorForGaussianDer = 0.28
sigmaForDownsample = 0.9
EPS = 1e-8
scales = 3
orientations = 4
infConst = 10000
# nanConst = 2000
if resize:
img = imresize(img, sizes=(normalizedWidth, normalizedWidth))
img = img.clamp(0.0, 255.0)
# crop image
b, c, h, w = img.shape
num_block_h = math.floor(h / block_size_h)
num_block_w = math.floor(w / block_size_w)
img = img[..., 0:num_block_h * block_size_h, 0:num_block_w * block_size_w]
ospace_weight = torch.tensor([
[0.3, 0.04, -0.35],
[0.34, -0.6, 0.17],
[0.06, 0.63, 0.27],
]).to(img)
O_img = img.permute(0, 2, 3, 1) @ ospace_weight.T
O_img = O_img.permute(0, 3, 1, 2)
distparam = [] # dist param is actually the multiscale features
for scale in (1, 2): # perform on two scales (1, 2)
struct_dis = normalize_img_with_guass(O_img[:, [2]], kernel_size=5, sigma=5. / 6, padding='replicate')
dx, dy = gauDerivative(sigmaForGauDerivative / (scale**scaleFactorForGaussianDer), device=img)
Ix = conv2d(O_img, dx.repeat(3, 1, 1, 1), groups=3)
Iy = conv2d(O_img, dy.repeat(3, 1, 1, 1), groups=3)
GM = torch.sqrt(Ix**2 + Iy**2 + EPS)
Ixy = torch.stack((Ix, Iy), dim=2).reshape(Ix.shape[0], Ix.shape[1] * 2,
*Ix.shape[2:]) # reshape to (IxO1, IxO1, IxO2, IyO2, IxO3, IyO3)
logRGB = torch.log(img + KforLog)
logRGBMS = logRGB - logRGB.mean(dim=(2, 3), keepdim=True)
Intensity = logRGBMS.sum(dim=1, keepdim=True) / np.sqrt(3)
BY = (logRGBMS[:, [0]] + logRGBMS[:, [1]] - 2 * logRGBMS[:, [2]]) / np.sqrt(6)
RG = (logRGBMS[:, [0]] - logRGBMS[:, [1]]) / np.sqrt(2)
compositeMat = torch.cat([struct_dis, GM, Intensity, BY, RG, Ixy], dim=1)
O3 = O_img[:, [2]]
# gabor filter in shape (b, ori * scale, h, w)
LGFilters = _construct_filters(
O3,
scales=scales,
orientations=orientations,
min_length=minWaveLength / (scale**scaleFactorForLoG),
sigma_f=sigmaOnf,
mult=mult,
delta_theta=dThetaOnSigma,
use_lowpass_filter=False)
# reformat to scale * ori
b, _, h, w = LGFilters.shape
LGFilters = LGFilters.reshape(b, orientations, scales, h, w).transpose(1, 2).reshape(b, -1, h, w)
# TODO: current filters needs to be transposed to get same results as matlab, find the bug
LGFilters = LGFilters.transpose(-1, -2)
fftIm = torch.fft.fft2(O3)
logResponse = []
partialDer = []
GM = []
for index in range(LGFilters.shape[1]):
filter = LGFilters[:, [index]]
response = torch.fft.ifft2(filter * fftIm)
realRes = torch.real(response)
imagRes = torch.imag(response)
partialXReal = conv2d(realRes, dx)
partialYReal = conv2d(realRes, dy)
realGM = torch.sqrt(partialXReal**2 + partialYReal**2 + EPS)
partialXImag = conv2d(imagRes, dx)
partialYImag = conv2d(imagRes, dy)
imagGM = torch.sqrt(partialXImag**2 + partialYImag**2 + EPS)
logResponse.append(realRes)
logResponse.append(imagRes)
partialDer.append(partialXReal)
partialDer.append(partialYReal)
partialDer.append(partialXImag)
partialDer.append(partialYImag)
GM.append(realGM)
GM.append(imagGM)
logResponse = torch.cat(logResponse, dim=1)
partialDer = torch.cat(partialDer, dim=1)
GM = torch.cat(GM, dim=1)
compositeMat = torch.cat((compositeMat, logResponse, partialDer, GM), dim=1)
distparam.append(blockproc(compositeMat, [block_size_h // scale,
block_size_w // scale], fun=compute_feature, ilniqe=True))
gauForDS = fspecial(math.ceil(6 * sigmaForDownsample), sigmaForDownsample).to(img)
filterResult = imfilter(O_img, gauForDS.repeat(3, 1, 1, 1), padding='replicate', groups=3)
O_img = filterResult[..., ::2, ::2]
filterResult = imfilter(img, gauForDS.repeat(3, 1, 1, 1), padding='replicate', groups=3)
img = filterResult[..., ::2, ::2]
distparam = torch.cat(distparam, dim=-1) # b, block_num, feature_num
distparam[distparam > infConst] = infConst
# fit a MVG (multivariate Gaussian) model to distorted patch features
coefficientsViaPCA = torch.bmm(
principleVectors.transpose(1, 2), (distparam - meanOfSampleData.unsqueeze(1)).transpose(1, 2))
final_features = coefficientsViaPCA.transpose(1, 2)
b, blk_num, feat_num = final_features.shape
# remove block features with nan and compute nonan cov
cov_distparam = nancov(final_features)
# replace nan in final features with mu
mu_final_features = nanmean(final_features, dim=1, keepdim=True)
final_features_withmu = torch.where(torch.isnan(final_features), mu_final_features, final_features)
# compute ilniqe quality
invcov_param = torch.linalg.pinv((cov_pris_param + cov_distparam) / 2)
diff = final_features_withmu - mu_pris_param.unsqueeze(1)
quality = (torch.bmm(diff, invcov_param) * diff).sum(dim=-1)
quality = torch.sqrt(quality).mean(dim=1)
return quality
def diff_round(x: torch.Tensor) -> torch.Tensor:
r"""Differentiable round."""
return x - x.detach() + x.round()
The provided code snippet includes necessary dependencies for implementing the `calculate_ilniqe` function. Write a Python function `def calculate_ilniqe(img: torch.Tensor, crop_border: int = 0, pretrained_model_path: str = None, **kwargs) -> torch.Tensor` to solve the following problem:
Calculate IL-NIQE metric. Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. pretrained_model_path (str): The pretrained model path. Returns: Tensor: IL-NIQE result.
Here is the function:
def calculate_ilniqe(img: torch.Tensor,
crop_border: int = 0,
pretrained_model_path: str = None,
**kwargs) -> torch.Tensor:
"""Calculate IL-NIQE metric.
Args:
img (Tensor): Input image whose quality needs to be computed.
crop_border (int): Cropped pixels in each edge of an image. These
pixels are not involved in the metric calculation.
pretrained_model_path (str): The pretrained model path.
Returns:
Tensor: IL-NIQE result.
"""
params = scipy.io.loadmat(pretrained_model_path)
img = img * 255.
img = diff_round(img)
# float64 precision is critical to be consistent with matlab codes
img = img.to(torch.float64)
mu_pris_param = np.ravel(params['templateModel'][0][0])
cov_pris_param = params['templateModel'][0][1]
meanOfSampleData = np.ravel(params['templateModel'][0][2])
principleVectors = params['templateModel'][0][3]
mu_pris_param = torch.from_numpy(mu_pris_param).to(img)
cov_pris_param = torch.from_numpy(cov_pris_param).to(img)
meanOfSampleData = torch.from_numpy(meanOfSampleData).to(img)
principleVectors = torch.from_numpy(principleVectors).to(img)
mu_pris_param = mu_pris_param.repeat(img.size(0), 1)
cov_pris_param = cov_pris_param.repeat(img.size(0), 1, 1)
meanOfSampleData = meanOfSampleData.repeat(img.size(0), 1)
principleVectors = principleVectors.repeat(img.size(0), 1, 1)
if crop_border != 0:
img = img[..., crop_border:-crop_border, crop_border:-crop_border]
ilniqe_result = ilniqe(img, mu_pris_param, cov_pris_param, principleVectors, meanOfSampleData)
return ilniqe_result | Calculate IL-NIQE metric. Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. pretrained_model_path (str): The pretrained model path. Returns: Tensor: IL-NIQE result. |
167,939 | import warnings
import functools
from typing import Union, Tuple
import torch
import torch.nn as nn
from torch.nn.functional import avg_pool2d, interpolate, pad
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.utils.color_util import rgb2lmn, rgb2lab
from .func_util import ifftshift, gradient_map, get_meshgrid, similarity_map, scharr_filter, safe_sqrt
def sdsp(x: torch.Tensor,
data_range: Union[int, float] = 255,
omega_0: float = 0.021,
sigma_f: float = 1.34,
sigma_d: float = 145.,
sigma_c: float = 0.001) -> torch.Tensor:
r"""SDSP algorithm for salient region detection from a given image.
Supports only colour images with RGB channel order.
Args:
x: Tensor. Shape :math:`(N, 3, H, W)`.
data_range: Maximum value range of images (usually 1.0 or 255).
omega_0: coefficient for log Gabor filter
sigma_f: coefficient for log Gabor filter
sigma_d: coefficient for the central areas, which have a bias towards attention
sigma_c: coefficient for the warm colors, which have a bias towards attention
Returns:
torch.Tensor: Visual saliency map
"""
x = x / data_range * 255
size = x.size()
size_to_use = (256, 256)
x = interpolate(input=x, size=size_to_use, mode='bilinear', align_corners=False)
x_lab = rgb2lab(x, data_range=255)
lg = _log_gabor(size_to_use, omega_0, sigma_f).to(x).view(1, 1, *size_to_use)
# torch version >= '1.8.0'
x_fft = torch.fft.fft2(x_lab)
x_ifft_real = torch.fft.ifft2(x_fft * lg).real
s_f = safe_sqrt(x_ifft_real.pow(2).sum(dim=1, keepdim=True))
coordinates = torch.stack(get_meshgrid(size_to_use), dim=0).to(x)
coordinates = coordinates * size_to_use[0] + 1
s_d = torch.exp(-torch.sum(coordinates**2, dim=0) / sigma_d**2).view(1, 1, *size_to_use)
eps = torch.finfo(x_lab.dtype).eps
min_x = x_lab.min(dim=-1, keepdim=True).values.min(dim=-2, keepdim=True).values
max_x = x_lab.max(dim=-1, keepdim=True).values.max(dim=-2, keepdim=True).values
normalized = (x_lab - min_x) / (max_x - min_x + eps)
norm = normalized[:, 1:].pow(2).sum(dim=1, keepdim=True)
s_c = 1 - torch.exp(-norm / sigma_c**2)
vs_m = s_f * s_d * s_c
vs_m = interpolate(vs_m, size[-2:], mode='bilinear', align_corners=True)
min_vs_m = vs_m.min(dim=-1, keepdim=True).values.min(dim=-2, keepdim=True).values
max_vs_m = vs_m.max(dim=-1, keepdim=True).values.max(dim=-2, keepdim=True).values
return (vs_m - min_vs_m) / (max_vs_m - min_vs_m + eps)
def rgb2lmn(x: torch.Tensor) -> torch.Tensor:
r"""Convert a batch of RGB images to a batch of LMN images
Args:
x: Batch of images with shape (N, 3, H, W). RGB colour space.
Returns:
Batch of images with shape (N, 3, H, W). LMN colour space.
"""
weights_rgb_to_lmn = torch.tensor([[0.06, 0.63, 0.27], [0.30, 0.04, -0.35], [0.34, -0.6, 0.17]]).t().to(x)
x_lmn = torch.matmul(x.permute(0, 2, 3, 1), weights_rgb_to_lmn).permute(0, 3, 1, 2)
return x_lmn
def scharr_filter() -> torch.Tensor:
r"""Utility function that returns a normalized 3x3 Scharr kernel in X direction
Returns:
kernel: Tensor with shape (1, 3, 3)
"""
return torch.tensor([[[-3.0, 0.0, 3.0], [-10.0, 0.0, 10.0], [-3.0, 0.0, 3.0]]]) / 16
def gradient_map(x: torch.Tensor, kernels: torch.Tensor) -> torch.Tensor:
r"""Compute gradient map for a given tensor and stack of kernels.
Args:
x: Tensor with shape (N, C, H, W).
kernels: Stack of tensors for gradient computation with shape (k_N, k_H, k_W)
Returns:
Gradients of x per-channel with shape (N, C, H, W)
"""
padding = kernels.size(-1) // 2
grads = torch.nn.functional.conv2d(x, kernels.to(x), padding=padding)
return safe_sqrt(torch.sum(grads**2, dim=-3, keepdim=True))
def similarity_map(
map_x: torch.Tensor, map_y: torch.Tensor, constant: float, alpha: float = 0.0
) -> torch.Tensor:
r"""Compute similarity_map between two tensors using Dice-like equation.
Args:
map_x: Tensor with map to be compared
map_y: Tensor with map to be compared
constant: Used for numerical stability
alpha: Masking coefficient. Substracts - `alpha` * map_x * map_y from denominator and nominator
"""
return (2.0 * map_x * map_y - alpha * map_x * map_y + constant) / (
map_x**2 + map_y**2 - alpha * map_x * map_y + constant + EPS
)
The provided code snippet includes necessary dependencies for implementing the `vsi` function. Write a Python function `def vsi(x: torch.Tensor, y: torch.Tensor, data_range: Union[int, float] = 1., c1: float = 1.27, c2: float = 386., c3: float = 130., alpha: float = 0.4, beta: float = 0.02, omega_0: float = 0.021, sigma_f: float = 1.34, sigma_d: float = 145., sigma_c: float = 0.001) -> torch.Tensor` to solve the following problem:
r"""Compute Visual Saliency-induced Index for a batch of images. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. data_range: Maximum value range of images (usually 1.0 or 255). c1: coefficient to calculate saliency component of VSI. c2: coefficient to calculate gradient component of VSI. c3: coefficient to calculate color component of VSI. alpha: power for gradient component of VSI. beta: power for color component of VSI. omega_0: coefficient to get log Gabor filter at SDSP. sigma_f: coefficient to get log Gabor filter at SDSP. sigma_d: coefficient to get SDSP. sigma_c: coefficient to get SDSP. Returns: Index of similarity between two images. Usually in [0, 1] range. References: L. Zhang, Y. Shen and H. Li, "VSI: A Visual Saliency-Induced Index for Perceptual Image Quality Assessment," IEEE Transactions on Image Processing, vol. 23, no. 10, pp. 4270-4281, Oct. 2014, doi: 10.1109/TIP.2014.2346028 https://ieeexplore.ieee.org/document/6873260 Note: The original method supports only RGB image.
Here is the function:
def vsi(x: torch.Tensor,
y: torch.Tensor,
data_range: Union[int, float] = 1.,
c1: float = 1.27,
c2: float = 386.,
c3: float = 130.,
alpha: float = 0.4,
beta: float = 0.02,
omega_0: float = 0.021,
sigma_f: float = 1.34,
sigma_d: float = 145.,
sigma_c: float = 0.001) -> torch.Tensor:
r"""Compute Visual Saliency-induced Index for a batch of images.
Args:
x: An input tensor. Shape :math:`(N, C, H, W)`.
y: A target tensor. Shape :math:`(N, C, H, W)`.
data_range: Maximum value range of images (usually 1.0 or 255).
c1: coefficient to calculate saliency component of VSI.
c2: coefficient to calculate gradient component of VSI.
c3: coefficient to calculate color component of VSI.
alpha: power for gradient component of VSI.
beta: power for color component of VSI.
omega_0: coefficient to get log Gabor filter at SDSP.
sigma_f: coefficient to get log Gabor filter at SDSP.
sigma_d: coefficient to get SDSP.
sigma_c: coefficient to get SDSP.
Returns:
Index of similarity between two images. Usually in [0, 1] range.
References:
L. Zhang, Y. Shen and H. Li, "VSI: A Visual Saliency-Induced Index for Perceptual
Image Quality Assessment," IEEE Transactions on Image Processing, vol. 23, no. 10,
pp. 4270-4281, Oct. 2014, doi: 10.1109/TIP.2014.2346028
https://ieeexplore.ieee.org/document/6873260
Note:
The original method supports only RGB image.
"""
x, y = x.double(), y.double()
if x.size(1) == 1:
x = x.repeat(1, 3, 1, 1)
y = y.repeat(1, 3, 1, 1)
warnings.warn('The original VSI supports only RGB images. The input images were converted to RGB by copying '
'the grey channel 3 times.')
# Scale to [0, 255] range to match scale of constant
x = x * 255. / data_range
y = y * 255. / data_range
vs_x = sdsp(x, data_range=255, omega_0=omega_0, sigma_f=sigma_f, sigma_d=sigma_d, sigma_c=sigma_c)
vs_y = sdsp(y, data_range=255, omega_0=omega_0, sigma_f=sigma_f, sigma_d=sigma_d, sigma_c=sigma_c)
# Convert to LMN colour space
x_lmn = rgb2lmn(x)
y_lmn = rgb2lmn(y)
# Averaging image if the size is large enough
kernel_size = max(1, round(min(vs_x.size()[-2:]) / 256))
padding = kernel_size // 2
if padding:
upper_pad = padding
bottom_pad = (kernel_size - 1) // 2
pad_to_use = [upper_pad, bottom_pad, upper_pad, bottom_pad]
mode = 'replicate'
vs_x = pad(vs_x, pad=pad_to_use, mode=mode)
vs_y = pad(vs_y, pad=pad_to_use, mode=mode)
x_lmn = pad(x_lmn, pad=pad_to_use, mode=mode)
y_lmn = pad(y_lmn, pad=pad_to_use, mode=mode)
vs_x = avg_pool2d(vs_x, kernel_size=kernel_size)
vs_y = avg_pool2d(vs_y, kernel_size=kernel_size)
x_lmn = avg_pool2d(x_lmn, kernel_size=kernel_size)
y_lmn = avg_pool2d(y_lmn, kernel_size=kernel_size)
# Calculate gradient map
kernels = torch.stack([scharr_filter(), scharr_filter().transpose(1, 2)]).to(x_lmn)
gm_x = gradient_map(x_lmn[:, :1], kernels)
gm_y = gradient_map(y_lmn[:, :1], kernels)
# Calculate all similarity maps
s_vs = similarity_map(vs_x, vs_y, c1)
s_gm = similarity_map(gm_x, gm_y, c2)
s_m = similarity_map(x_lmn[:, 1:2], y_lmn[:, 1:2], c3)
s_n = similarity_map(x_lmn[:, 2:], y_lmn[:, 2:], c3)
s_c = s_m * s_n
s_c_complex = [s_c.abs(), torch.atan2(torch.zeros_like(s_c), s_c)]
s_c_complex_pow = [s_c_complex[0]**beta, s_c_complex[1] * beta]
s_c_real_pow = s_c_complex_pow[0] * torch.cos(s_c_complex_pow[1])
s = s_vs * s_gm.pow(alpha) * s_c_real_pow
vs_max = torch.max(vs_x, vs_y)
eps = torch.finfo(vs_max.dtype).eps
output = s * vs_max
output = ((output.sum(dim=(-1, -2)) + eps) / (vs_max.sum(dim=(-1, -2)) + eps)).squeeze(-1)
return output | r"""Compute Visual Saliency-induced Index for a batch of images. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. data_range: Maximum value range of images (usually 1.0 or 255). c1: coefficient to calculate saliency component of VSI. c2: coefficient to calculate gradient component of VSI. c3: coefficient to calculate color component of VSI. alpha: power for gradient component of VSI. beta: power for color component of VSI. omega_0: coefficient to get log Gabor filter at SDSP. sigma_f: coefficient to get log Gabor filter at SDSP. sigma_d: coefficient to get SDSP. sigma_c: coefficient to get SDSP. Returns: Index of similarity between two images. Usually in [0, 1] range. References: L. Zhang, Y. Shen and H. Li, "VSI: A Visual Saliency-Induced Index for Perceptual Image Quality Assessment," IEEE Transactions on Image Processing, vol. 23, no. 10, pp. 4270-4281, Oct. 2014, doi: 10.1109/TIP.2014.2346028 https://ieeexplore.ieee.org/document/6873260 Note: The original method supports only RGB image. |
167,940 | import numpy as np
import torch
import torch.nn.functional as F
from pyiqa.utils.color_util import to_y_channel
from pyiqa.matlab_utils import fspecial, SCFpyr_PyTorch, math_util, filter2
from pyiqa.utils.registry import ARCH_REGISTRY
from .func_util import preprocess_rgb
def ssim(X,
Y,
win=None,
get_ssim_map=False,
get_cs=False,
get_weight=False,
downsample=False,
data_range=1.,
):
if win is None:
win = fspecial(11, 1.5, X.shape[1]).to(X)
C1 = (0.01 * data_range)**2
C2 = (0.03 * data_range)**2
# Averagepool image if the size is large enough
f = max(1, round(min(X.size()[-2:]) / 256))
# Downsample operation is used in official matlab code
if (f > 1) and downsample:
X = F.avg_pool2d(X, kernel_size=f)
Y = F.avg_pool2d(Y, kernel_size=f)
mu1 = filter2(X, win, 'valid')
mu2 = filter2(Y, win, 'valid')
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = filter2(X * X, win, 'valid') - mu1_sq
sigma2_sq = filter2(Y * Y, win, 'valid') - mu2_sq
sigma12 = filter2(X * Y, win, 'valid') - mu1_mu2
cs_map = (2 * sigma12 + C2) / (sigma1_sq + sigma2_sq + C2)
cs_map = F.relu(cs_map) # force the ssim response to be nonnegative to avoid negative results.
ssim_map = ((2 * mu1_mu2 + C1) / (mu1_sq + mu2_sq + C1)) * cs_map
ssim_val = ssim_map.mean([1, 2, 3])
if get_weight:
weights = torch.log((1 + sigma1_sq / C2) * (1 + sigma2_sq / C2))
return ssim_map, weights
if get_ssim_map:
return ssim_map
if get_cs:
return ssim_val, cs_map.mean([1, 2, 3])
return ssim_val
The provided code snippet includes necessary dependencies for implementing the `ms_ssim` function. Write a Python function `def ms_ssim(X, Y, win=None, data_range=1., downsample=False, test_y_channel=True, is_prod=True, color_space='yiq')` to solve the following problem:
r"""Compute Multiscale structural similarity for a batch of images. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. win: Window setting. downsample: Boolean, whether to downsample which mimics official SSIM matlab code. test_y_channel: Boolean, whether to use y channel on ycbcr. is_prod: Boolean, calculate product or sum between mcs and weight. Returns: Index of similarity betwen two images. Usually in [0, 1] interval.
Here is the function:
def ms_ssim(X, Y, win=None, data_range=1., downsample=False, test_y_channel=True, is_prod=True, color_space='yiq'):
r"""Compute Multiscale structural similarity for a batch of images.
Args:
x: An input tensor. Shape :math:`(N, C, H, W)`.
y: A target tensor. Shape :math:`(N, C, H, W)`.
win: Window setting.
downsample: Boolean, whether to downsample which mimics official SSIM matlab code.
test_y_channel: Boolean, whether to use y channel on ycbcr.
is_prod: Boolean, calculate product or sum between mcs and weight.
Returns:
Index of similarity betwen two images. Usually in [0, 1] interval.
"""
if not X.shape == Y.shape:
raise ValueError('Input images must have the same dimensions.')
weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(X)
levels = weights.shape[0]
mcs = []
for _ in range(levels):
ssim_val, cs = ssim(
X,
Y,
win=win,
get_cs=True,
downsample=downsample,
data_range=data_range,
)
mcs.append(cs)
padding = (X.shape[2] % 2, X.shape[3] % 2)
X = F.avg_pool2d(X, kernel_size=2, padding=padding)
Y = F.avg_pool2d(Y, kernel_size=2, padding=padding)
mcs = torch.stack(mcs, dim=0)
if is_prod:
msssim_val = torch.prod((mcs[:-1]**weights[:-1].unsqueeze(1)), dim=0) * (ssim_val**weights[-1])
else:
weights = weights / torch.sum(weights)
msssim_val = torch.sum((mcs[:-1] * weights[:-1].unsqueeze(1)), dim=0) + (ssim_val * weights[-1])
return msssim_val | r"""Compute Multiscale structural similarity for a batch of images. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. win: Window setting. downsample: Boolean, whether to downsample which mimics official SSIM matlab code. test_y_channel: Boolean, whether to use y channel on ycbcr. is_prod: Boolean, calculate product or sum between mcs and weight. Returns: Index of similarity betwen two images. Usually in [0, 1] interval. |
167,941 | import math
import functools
from typing import Tuple
import torch.nn as nn
import torch
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.utils.color_util import rgb2yiq
from .func_util import gradient_map, similarity_map, ifftshift, get_meshgrid
def _phase_congruency(x: torch.Tensor,
scales: int = 4,
orientations: int = 4,
min_length: int = 6,
mult: int = 2,
sigma_f: float = 0.55,
delta_theta: float = 1.2,
k: float = 2.0) -> torch.Tensor:
r"""Compute Phase Congruence for a batch of greyscale images
Args:
x: Tensor. Shape :math:`(N, 1, H, W)`.
scales: Number of wavelet scales
orientations: Number of filter orientations
min_length: Wavelength of smallest scale filter
mult: Scaling factor between successive filters
sigma_f: Ratio of the standard deviation of the Gaussian
describing the log Gabor filter's transfer function
in the frequency domain to the filter center frequency.
delta_theta: Ratio of angular interval between filter orientations
and the standard deviation of the angular Gaussian function
used to construct filters in the freq. plane.
k: No of standard deviations of the noise energy beyond the mean
at which we set the noise threshold point, below which phase
congruency values get penalized.
Returns:
Phase Congruency map with shape :math:`(N, H, W)`
"""
EPS = torch.finfo(x.dtype).eps
N, _, H, W = x.shape
# Fourier transform
filters = _construct_filters(x, scales, orientations, min_length, mult, sigma_f, delta_theta, k)
imagefft = torch.fft.fft2(x)
filters_ifft = torch.fft.ifft2(filters)
filters_ifft = filters_ifft.real * math.sqrt(H * W)
even_odd = torch.view_as_real(torch.fft.ifft2(imagefft * filters)).view(N, orientations, scales, H, W, 2)
# Amplitude of even & odd filter response. An = sqrt(real^2 + imag^2)
an = torch.sqrt(torch.sum(even_odd**2, dim=-1))
# Take filter at scale 0 and sum spatially
# Record mean squared filter value at smallest scale.
# This is used for noise estimation.
em_n = (filters.view(1, orientations, scales, H, W)[:, :, :1, ...]**2).sum(dim=[-2, -1], keepdims=True)
# Sum of even filter convolution results.
sum_e = even_odd[..., 0].sum(dim=2, keepdims=True)
# Sum of odd filter convolution results.
sum_o = even_odd[..., 1].sum(dim=2, keepdims=True)
# Get weighted mean filter response vector, this gives the weighted mean phase angle.
x_energy = torch.sqrt(sum_e**2 + sum_o**2) + EPS
mean_e = sum_e / x_energy
mean_o = sum_o / x_energy
# Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by
# using dot and cross products between the weighted mean filter response
# vector and the individual filter response vectors at each scale.
# This quantity is phase congruency multiplied by An, which we call energy.
# Extract even and odd convolution results.
even = even_odd[..., 0]
odd = even_odd[..., 1]
energy = (even * mean_e + odd * mean_o - torch.abs(even * mean_o - odd * mean_e)).sum(dim=2, keepdim=True)
# Compensate for noise
# We estimate the noise power from the energy squared response at the
# smallest scale. If the noise is Gaussian the energy squared will have a
# Chi-squared 2DOF pdf. We calculate the median energy squared response
# as this is a robust statistic. From this we estimate the mean.
# The estimate of noise power is obtained by dividing the mean squared
# energy value by the mean squared filter value
abs_eo = torch.sqrt(torch.sum(even_odd[:, :, :1, ...]**2, dim=-1)).reshape(N, orientations, 1, 1, H * W)
median_e2n = torch.median(abs_eo**2, dim=-1, keepdim=True).values
mean_e2n = -median_e2n / math.log(0.5)
# Estimate of noise power.
noise_power = mean_e2n / em_n
# Now estimate the total energy^2 due to noise
# Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj))
filters_ifft = filters_ifft.view(1, orientations, scales, H, W)
sum_an2 = torch.sum(filters_ifft**2, dim=-3, keepdim=True)
sum_ai_aj = torch.zeros(N, orientations, 1, H, W).to(x)
for s in range(scales - 1):
sum_ai_aj = sum_ai_aj + (filters_ifft[:, :, s:s + 1] * filters_ifft[:, :, s + 1:]).sum(dim=-3, keepdim=True)
sum_an2 = torch.sum(sum_an2, dim=[-1, -2], keepdim=True)
sum_ai_aj = torch.sum(sum_ai_aj, dim=[-1, -2], keepdim=True)
noise_energy2 = 2 * noise_power * sum_an2 + 4 * noise_power * sum_ai_aj
# Rayleigh parameter
tau = torch.sqrt(noise_energy2 / 2)
# Expected value of noise energy
noise_energy = tau * math.sqrt(math.pi / 2)
moise_energy_sigma = torch.sqrt((2 - math.pi / 2) * tau**2)
# Noise threshold
T = noise_energy + k * moise_energy_sigma
# The estimated noise effect calculated above is only valid for the PC_1 measure.
# The PC_2 measure does not lend itself readily to the same analysis. However
# empirically it seems that the noise effect is overestimated roughly by a factor
# of 1.7 for the filter parameters used here.
# Empirical rescaling of the estimated noise effect to suit the PC_2 phase congruency measure
T = T / 1.7
# Apply noise threshold
energy = torch.max(energy - T, torch.zeros_like(T))
eps = torch.finfo(energy.dtype).eps
energy_all = energy.sum(dim=[1, 2]) + eps
an_all = an.sum(dim=[1, 2]) + eps
result_pc = energy_all / an_all
return result_pc.unsqueeze(1)
def rgb2yiq(x: torch.Tensor) -> torch.Tensor:
r"""Convert a batch of RGB images to a batch of YIQ images
Args:
x: Batch of images with shape (N, 3, H, W). RGB colour space.
Returns:
Batch of images with shape (N, 3, H, W). YIQ colour space.
"""
yiq_weights = torch.tensor([[0.299, 0.587, 0.114], [0.5959, -0.2746, -0.3213], [0.2115, -0.5227, 0.3112]]).t().to(x)
x_yiq = torch.matmul(x.permute(0, 2, 3, 1), yiq_weights).permute(0, 3, 1, 2)
return x_yiq
def gradient_map(x: torch.Tensor, kernels: torch.Tensor) -> torch.Tensor:
r"""Compute gradient map for a given tensor and stack of kernels.
Args:
x: Tensor with shape (N, C, H, W).
kernels: Stack of tensors for gradient computation with shape (k_N, k_H, k_W)
Returns:
Gradients of x per-channel with shape (N, C, H, W)
"""
padding = kernels.size(-1) // 2
grads = torch.nn.functional.conv2d(x, kernels.to(x), padding=padding)
return safe_sqrt(torch.sum(grads**2, dim=-3, keepdim=True))
def similarity_map(
map_x: torch.Tensor, map_y: torch.Tensor, constant: float, alpha: float = 0.0
) -> torch.Tensor:
r"""Compute similarity_map between two tensors using Dice-like equation.
Args:
map_x: Tensor with map to be compared
map_y: Tensor with map to be compared
constant: Used for numerical stability
alpha: Masking coefficient. Substracts - `alpha` * map_x * map_y from denominator and nominator
"""
return (2.0 * map_x * map_y - alpha * map_x * map_y + constant) / (
map_x**2 + map_y**2 - alpha * map_x * map_y + constant + EPS
)
The provided code snippet includes necessary dependencies for implementing the `fsim` function. Write a Python function `def fsim(x: torch.Tensor, y: torch.Tensor, chromatic: bool = True, scales: int = 4, orientations: int = 4, min_length: int = 6, mult: int = 2, sigma_f: float = 0.55, delta_theta: float = 1.2, k: float = 2.0) -> torch.Tensor` to solve the following problem:
r"""Compute Feature Similarity Index Measure for a batch of images. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - y: A target tensor. Shape :math:`(N, C, H, W)`. - chromatic: Flag to compute FSIMc, which also takes into account chromatic components - scales: Number of wavelets used for computation of phase congruensy maps - orientations: Number of filter orientations used for computation of phase congruensy maps - min_length: Wavelength of smallest scale filter - mult: Scaling factor between successive filters - sigma_f: Ratio of the standard deviation of the Gaussian describing the log Gabor filter's transfer function in the frequency domain to the filter center frequency. - delta_theta: Ratio of angular interval between filter orientations and the standard deviation of the angular Gaussian function used to construct filters in the frequency plane. - k: No of standard deviations of the noise energy beyond the mean at which we set the noise threshold point, below which phase congruency values get penalized. Returns: - Index of similarity betwen two images. Usually in [0, 1] interval. Can be bigger than 1 for predicted :math:`x` images with higher contrast than the original ones. References: L. Zhang, L. Zhang, X. Mou and D. Zhang, "FSIM: A Feature Similarity Index for Image Quality Assessment," IEEE Transactions on Image Processing, vol. 20, no. 8, pp. 2378-2386, Aug. 2011, doi: 10.1109/TIP.2011.2109730. https://ieeexplore.ieee.org/document/5705575
Here is the function:
def fsim(x: torch.Tensor,
y: torch.Tensor,
chromatic: bool = True,
scales: int = 4,
orientations: int = 4,
min_length: int = 6,
mult: int = 2,
sigma_f: float = 0.55,
delta_theta: float = 1.2,
k: float = 2.0) -> torch.Tensor:
r"""Compute Feature Similarity Index Measure for a batch of images.
Args:
- x: An input tensor. Shape :math:`(N, C, H, W)`.
- y: A target tensor. Shape :math:`(N, C, H, W)`.
- chromatic: Flag to compute FSIMc, which also takes into account chromatic components
- scales: Number of wavelets used for computation of phase congruensy maps
- orientations: Number of filter orientations used for computation of phase congruensy maps
- min_length: Wavelength of smallest scale filter
- mult: Scaling factor between successive filters
- sigma_f: Ratio of the standard deviation of the Gaussian describing the log Gabor filter's
transfer function in the frequency domain to the filter center frequency.
- delta_theta: Ratio of angular interval between filter orientations and the standard deviation
of the angular Gaussian function used to construct filters in the frequency plane.
- k: No of standard deviations of the noise energy beyond the mean at which we set the noise
threshold point, below which phase congruency values get penalized.
Returns:
- Index of similarity betwen two images. Usually in [0, 1] interval.
Can be bigger than 1 for predicted :math:`x` images with higher contrast than the original ones.
References:
L. Zhang, L. Zhang, X. Mou and D. Zhang, "FSIM: A Feature Similarity Index for Image Quality Assessment,"
IEEE Transactions on Image Processing, vol. 20, no. 8, pp. 2378-2386, Aug. 2011, doi: 10.1109/TIP.2011.2109730.
https://ieeexplore.ieee.org/document/5705575
"""
# Rescale to [0, 255] range, because all constant are calculated for this factor
x = x / float(1.0) * 255
y = y / float(1.0) * 255
# Apply average pooling
kernel_size = max(1, round(min(x.shape[-2:]) / 256))
x = torch.nn.functional.avg_pool2d(x, kernel_size)
y = torch.nn.functional.avg_pool2d(y, kernel_size)
num_channels = x.size(1)
# Convert RGB to YIQ color space
if num_channels == 3:
x_yiq = rgb2yiq(x)
y_yiq = rgb2yiq(y)
x_lum = x_yiq[:, :1]
y_lum = y_yiq[:, :1]
x_i = x_yiq[:, 1:2]
y_i = y_yiq[:, 1:2]
x_q = x_yiq[:, 2:]
y_q = y_yiq[:, 2:]
else:
x_lum = x
y_lum = y
# Compute phase congruency maps
pc_x = _phase_congruency(
x_lum,
scales=scales,
orientations=orientations,
min_length=min_length,
mult=mult,
sigma_f=sigma_f,
delta_theta=delta_theta,
k=k)
pc_y = _phase_congruency(
y_lum,
scales=scales,
orientations=orientations,
min_length=min_length,
mult=mult,
sigma_f=sigma_f,
delta_theta=delta_theta,
k=k)
# Gradient maps
scharr_filter = torch.tensor([[[-3., 0., 3.], [-10., 0., 10.], [-3., 0., 3.]]]) / 16
kernels = torch.stack([scharr_filter, scharr_filter.transpose(-1, -2)])
grad_map_x = gradient_map(x_lum, kernels)
grad_map_y = gradient_map(y_lum, kernels)
# Constants from the paper
T1, T2, T3, T4, lmbda = 0.85, 160, 200, 200, 0.03
# Compute FSIM
PC = similarity_map(pc_x, pc_y, T1)
GM = similarity_map(grad_map_x, grad_map_y, T2)
pc_max = torch.where(pc_x > pc_y, pc_x, pc_y)
score = GM * PC * pc_max # torch.sum(score)/torch.sum(pc_max)
if chromatic:
assert num_channels == 3, 'Chromatic component can be computed only for RGB images!'
S_I = similarity_map(x_i, y_i, T3)
S_Q = similarity_map(x_q, y_q, T4)
score = score * torch.abs(S_I * S_Q)**lmbda
# Complex gradients will work in PyTorch 1.6.0
# score = score * torch.real((S_I * S_Q).to(torch.complex64) ** lmbda)
result = score.sum(dim=[1, 2, 3]) / pc_max.sum(dim=[1, 2, 3])
return result | r"""Compute Feature Similarity Index Measure for a batch of images. Args: - x: An input tensor. Shape :math:`(N, C, H, W)`. - y: A target tensor. Shape :math:`(N, C, H, W)`. - chromatic: Flag to compute FSIMc, which also takes into account chromatic components - scales: Number of wavelets used for computation of phase congruensy maps - orientations: Number of filter orientations used for computation of phase congruensy maps - min_length: Wavelength of smallest scale filter - mult: Scaling factor between successive filters - sigma_f: Ratio of the standard deviation of the Gaussian describing the log Gabor filter's transfer function in the frequency domain to the filter center frequency. - delta_theta: Ratio of angular interval between filter orientations and the standard deviation of the angular Gaussian function used to construct filters in the frequency plane. - k: No of standard deviations of the noise energy beyond the mean at which we set the noise threshold point, below which phase congruency values get penalized. Returns: - Index of similarity betwen two images. Usually in [0, 1] interval. Can be bigger than 1 for predicted :math:`x` images with higher contrast than the original ones. References: L. Zhang, L. Zhang, X. Mou and D. Zhang, "FSIM: A Feature Similarity Index for Image Quality Assessment," IEEE Transactions on Image Processing, vol. 20, no. 8, pp. 2378-2386, Aug. 2011, doi: 10.1109/TIP.2011.2109730. https://ieeexplore.ieee.org/document/5705575 |
167,942 | import os
from tqdm import tqdm
from glob import glob
import numpy as np
from scipy import linalg
from PIL import Image
import torch
from torch import nn
import torchvision
from .inception import InceptionV3
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.utils.img_util import is_image_file
from pyiqa.utils.registry import ARCH_REGISTRY
default_model_urls = {
'ffhq_clean_trainval70k_512.npz': 'https://github.com/chaofengc/IQA-PyTorch/releases/download/v0.1-weights/ffhq_clean_trainval70k_512.npz',
'ffhq_clean_trainval70k_512_kid.npz': 'https://github.com/chaofengc/IQA-PyTorch/releases/download/v0.1-weights/ffhq_clean_trainval70k_512_kid.npz',
}
def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
"""Load file form http url, will download models if necessary.
Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py
Args:
url (str): URL to be downloaded.
model_dir (str): The path to save the downloaded model. Should be a full path. If None, use pytorch hub_dir.
Default: None.
progress (bool): Whether to show the download progress. Default: True.
file_name (str): The downloaded file name. If None, use the file name in the url. Default: None.
Returns:
str: The path to the downloaded file.
"""
if model_dir is None: # use the pytorch hub_dir
hub_dir = get_dir()
model_dir = os.path.join(hub_dir, 'checkpoints')
os.makedirs(model_dir, exist_ok=True)
parts = urlparse(url)
filename = os.path.basename(parts.path)
if file_name is not None:
filename = file_name
cached_file = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(cached_file):
print(f'Downloading: "{url}" to {cached_file}\n')
download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
return cached_file
The provided code snippet includes necessary dependencies for implementing the `get_reference_statistics` function. Write a Python function `def get_reference_statistics(name, res, mode="clean", split="test", metric="FID")` to solve the following problem:
r""" Load precomputed reference statistics for commonly used datasets
Here is the function:
def get_reference_statistics(name, res, mode="clean", split="test", metric="FID"):
r"""
Load precomputed reference statistics for commonly used datasets
"""
base_url = "https://www.cs.cmu.edu/~clean-fid/stats"
if split == "custom":
res = "na"
if metric == "FID":
rel_path = (f"{name}_{mode}_{split}_{res}.npz").lower()
url = f"{base_url}/{rel_path}"
if rel_path in default_model_urls.keys():
fpath = load_file_from_url(default_model_urls[rel_path])
else:
fpath = load_file_from_url(url)
stats = np.load(fpath)
mu, sigma = stats["mu"], stats["sigma"]
return mu, sigma
elif metric == "KID":
rel_path = (f"{name}_{mode}_{split}_{res}_kid.npz").lower()
url = f"{base_url}/{rel_path}"
if rel_path in default_model_urls.keys():
fpath = load_file_from_url(default_model_urls[rel_path])
else:
fpath = load_file_from_url(url)
stats = np.load(fpath)
return stats["feats"] | r""" Load precomputed reference statistics for commonly used datasets |
167,943 | import os
from tqdm import tqdm
from glob import glob
import numpy as np
from scipy import linalg
from PIL import Image
import torch
from torch import nn
import torchvision
from .inception import InceptionV3
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.utils.img_util import is_image_file
from pyiqa.utils.registry import ARCH_REGISTRY
The provided code snippet includes necessary dependencies for implementing the `frechet_distance` function. Write a Python function `def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6)` to solve the following problem:
Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Danica J. Sutherland. Params: mu1 : Numpy array containing the activations of a layer of the inception net (like returned by the function 'get_predictions') for generated samples. mu2 : The sample mean over activations, precalculated on an representative data set. sigma1: The covariance matrix over activations for generated samples. sigma2: The covariance matrix over activations, precalculated on an representative data set.
Here is the function:
def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""
Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable version by Danica J. Sutherland.
Params:
mu1 : Numpy array containing the activations of a layer of the
inception net (like returned by the function 'get_predictions')
for generated samples.
mu2 : The sample mean over activations, precalculated on an
representative data set.
sigma1: The covariance matrix over activations for generated samples.
sigma2: The covariance matrix over activations, precalculated on an
representative data set.
"""
mu1 = np.atleast_1d(mu1)
mu2 = np.atleast_1d(mu2)
sigma1 = np.atleast_2d(sigma1)
sigma2 = np.atleast_2d(sigma2)
assert mu1.shape == mu2.shape, \
'Training and test mean vectors have different lengths'
assert sigma1.shape == sigma2.shape, \
'Training and test covariances have different dimensions'
diff = mu1 - mu2
# Product might be almost singular
covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
if not np.isfinite(covmean).all():
msg = ('fid calculation produces singular product; '
'adding %s to diagonal of cov estimates') % eps
print(msg)
offset = np.eye(sigma1.shape[0]) * eps
covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
# Numerical error might give slight imaginary component
if np.iscomplexobj(covmean):
if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
m = np.max(np.abs(covmean.imag))
raise ValueError('Imaginary component {}'.format(m))
covmean = covmean.real
tr_covmean = np.trace(covmean)
return (diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean) | Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Danica J. Sutherland. Params: mu1 : Numpy array containing the activations of a layer of the inception net (like returned by the function 'get_predictions') for generated samples. mu2 : The sample mean over activations, precalculated on an representative data set. sigma1: The covariance matrix over activations for generated samples. sigma2: The covariance matrix over activations, precalculated on an representative data set. |
167,944 | import os
from tqdm import tqdm
from glob import glob
import numpy as np
from scipy import linalg
from PIL import Image
import torch
from torch import nn
import torchvision
from .inception import InceptionV3
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.utils.img_util import is_image_file
from pyiqa.utils.registry import ARCH_REGISTRY
The provided code snippet includes necessary dependencies for implementing the `kernel_distance` function. Write a Python function `def kernel_distance(feats1, feats2, num_subsets=100, max_subset_size=1000)` to solve the following problem:
r""" Compute the KID score given the sets of features
Here is the function:
def kernel_distance(feats1, feats2, num_subsets=100, max_subset_size=1000):
r"""
Compute the KID score given the sets of features
"""
n = feats1.shape[1]
m = min(min(feats1.shape[0], feats2.shape[0]), max_subset_size)
t = 0
for _subset_idx in range(num_subsets):
x = feats2[np.random.choice(feats2.shape[0], m, replace=False)]
y = feats1[np.random.choice(feats1.shape[0], m, replace=False)]
a = (x @ x.T / n + 1) ** 3 + (y @ y.T / n + 1) ** 3
b = (x @ y.T / n + 1) ** 3
t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m
kid = t / num_subsets / m
return float(kid) | r""" Compute the KID score given the sets of features |
167,945 | import os
from tqdm import tqdm
from glob import glob
import numpy as np
from scipy import linalg
from PIL import Image
import torch
from torch import nn
import torchvision
from .inception import InceptionV3
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.utils.img_util import is_image_file
from pyiqa.utils.registry import ARCH_REGISTRY
def get_file_paths(dir, max_dataset_size=float("inf"), followlinks=True):
images = []
assert os.path.isdir(dir), '%s is not a valid directory' % dir
for root, _, fnames in sorted(os.walk(dir, followlinks=followlinks)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(path)
return images[:min(max_dataset_size, len(images))]
class ResizeDataset(torch.utils.data.Dataset):
"""
A placeholder Dataset that enables parallelizing the resize operation
using multiple CPU cores
files: list of all files in the folder
mode:
- clean: use PIL resize before calculate features
- legacy_pytorch: do not resize here, but before pytorch model
"""
def __init__(self, files, mode, size=(299, 299)):
self.files = files
self.transforms = torchvision.transforms.ToTensor()
self.size = size
self.mode = mode
def __len__(self):
return len(self.files)
def __getitem__(self, i):
path = str(self.files[i])
img_pil = Image.open(path).convert('RGB')
if self.mode == 'clean':
def resize_single_channel(x_np):
img = Image.fromarray(x_np.astype(np.float32), mode='F')
img = img.resize(self.size, resample=Image.BICUBIC)
return np.asarray(img).clip(0, 255).reshape(*self.size, 1)
img_np = np.array(img_pil)
img_np = [resize_single_channel(img_np[:, :, idx]) for idx in range(3)]
img_np = np.concatenate(img_np, axis=2).astype(np.float32)
img_np = (img_np - 128) / 128
img_t = torch.tensor(img_np).permute(2, 0, 1)
else:
img_np = np.array(img_pil).clip(0, 255)
img_t = self.transforms(img_np)
img_t = nn.functional.interpolate(img_t.unsqueeze(0),
size=self.size,
mode='bilinear',
align_corners=False)
img_t = img_t.squeeze(0)
return img_t
The provided code snippet includes necessary dependencies for implementing the `get_folder_features` function. Write a Python function `def get_folder_features(fdir, model=None, num_workers=12, batch_size=32, device=torch.device("cuda"), mode="clean", description="", verbose=True, )` to solve the following problem:
r""" Compute the inception features for a folder of image files
Here is the function:
def get_folder_features(fdir, model=None, num_workers=12,
batch_size=32,
device=torch.device("cuda"),
mode="clean",
description="",
verbose=True,
):
r"""
Compute the inception features for a folder of image files
"""
files = get_file_paths(fdir)
if verbose:
print(f"Found {len(files)} images in the folder {fdir}")
dataset = ResizeDataset(files, mode=mode)
dataloader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size, shuffle=False,
drop_last=False, num_workers=num_workers)
# collect all inception features
if verbose:
pbar = tqdm(dataloader, desc=description)
else:
pbar = dataloader
if mode == 'clean':
normalize_input = False
else:
normalize_input = True
l_feats = []
with torch.no_grad():
for batch in pbar:
feat = model(batch.to(device), False, normalize_input)
feat = feat[0].squeeze(-1).squeeze(-1).detach().cpu().numpy()
l_feats.append(feat)
np_feats = np.concatenate(l_feats)
return np_feats | r""" Compute the inception features for a folder of image files |
167,946 | import math
import scipy.io
import torch
from torch import Tensor
import torch.nn.functional as F
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.utils.color_util import to_y_channel
from pyiqa.utils.download_util import load_file_from_url
from pyiqa.matlab_utils import imresize, fspecial, SCFpyr_PyTorch, dct2d, im2col, ExactPadding2d
from pyiqa.archs.func_util import extract_2d_patches
from pyiqa.archs.ssim_arch import ssim as ssim_func
from pyiqa.archs.niqe_arch import NIQE
from warnings import warn
def nrqm(
img: Tensor,
linear_param,
rf_param,
) -> Tensor:
"""Calculate NRQM
Args:
img (Tensor): Input image.
linear_param (np.array): (4, 1) linear regression params
rf_param: params of 3 random forest for 3 kinds of features
"""
assert img.ndim == 4, ('Input image must be a gray or Y (of YCbCr) image with shape (b, c, h, w).')
# crop image
b, c, h, w = img.shape
img = img.double()
img_pyr = get_guass_pyramid(img / 255.)
# DCT features
f1 = []
for im in img_pyr:
f1.append(block_dct(im))
f1 = torch.cat(f1, dim=1)
# gsm features
f2 = global_gsm(img)
# svd features
f3 = []
for im in img_pyr:
col = im2col(im, 5, 'distinct')
_, s, _ = torch.linalg.svd(col, full_matrices=False)
f3.append(s)
f3 = torch.cat(f3, dim=1)
# Random forest regression. Currently not differentiable and only support CPU
preds = torch.ones(b, 1)
for feat, rf in zip([f1, f2, f3], rf_param):
tmp_pred = random_forest_regression(feat, *rf)
preds = torch.cat((preds, tmp_pred), dim=1)
quality = preds @ torch.tensor(linear_param)
return quality.squeeze()
def to_y_channel(img: torch.Tensor, out_data_range: float = 1., color_space: str = 'yiq') -> torch.Tensor:
r"""Change to Y channel
Args:
image tensor: tensor with shape (N, 3, H, W) in range [0, 1].
Returns:
image tensor: Y channel of the input tensor
"""
assert img.ndim == 4 and img.shape[1] == 3, 'input image tensor should be RGB image batches with shape (N, 3, H, W)'
color_space = color_space.lower()
if color_space == 'yiq':
img = rgb2yiq(img)
elif color_space == 'ycbcr':
img = rgb2ycbcr(img)
elif color_space == 'lhm':
img = rgb2lhm(img)
out_img = img[:, [0], :, :] * out_data_range
if out_data_range >= 255:
# differentiable round with pytorch
out_img = out_img - out_img.detach() + out_img.round()
return out_img
The provided code snippet includes necessary dependencies for implementing the `calculate_nrqm` function. Write a Python function `def calculate_nrqm(img: torch.Tensor, crop_border: int = 0, test_y_channel: bool = True, pretrained_model_path: str = None, color_space: str = 'yiq', **kwargs) -> torch.Tensor` to solve the following problem:
Calculate NRQM Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'. pretrained_model_path (String): The pretrained model path. Returns: Tensor: NIQE result.
Here is the function:
def calculate_nrqm(img: torch.Tensor,
crop_border: int = 0,
test_y_channel: bool = True,
pretrained_model_path: str = None,
color_space: str = 'yiq',
**kwargs) -> torch.Tensor:
"""Calculate NRQM
Args:
img (Tensor): Input image whose quality needs to be computed.
crop_border (int): Cropped pixels in each edge of an image. These
pixels are not involved in the metric calculation.
test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'.
pretrained_model_path (String): The pretrained model path.
Returns:
Tensor: NIQE result.
"""
params = scipy.io.loadmat(pretrained_model_path)['model']
linear_param = params['linear'][0, 0]
rf_params_list = []
for i in range(3):
tmp_list = []
tmp_param = params['rf'][0, 0][0, i][0, 0]
tmp_list.append(tmp_param[0]) # ldau
tmp_list.append(tmp_param[1]) # rdau
tmp_list.append(tmp_param[4]) # threshold value
tmp_list.append(tmp_param[5]) # pred value
tmp_list.append(tmp_param[6]) # best attribute index
rf_params_list.append(tmp_list)
if test_y_channel and img.shape[1] == 3:
img = to_y_channel(img, 255, color_space)
if crop_border != 0:
img = img[..., crop_border:-crop_border, crop_border:-crop_border]
nrqm_result = nrqm(img, linear_param, rf_params_list)
return nrqm_result.to(img) | Calculate NRQM Args: img (Tensor): Input image whose quality needs to be computed. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the metric calculation. test_y_channel (Bool): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'. pretrained_model_path (String): The pretrained model path. Returns: Tensor: NIQE result. |
167,947 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _cfg(url='', **kwargs):
return {
'url': url,
'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True,
'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
'first_conv': 'patch_embed.proj', 'classifier': 'head',
**kwargs
} | null |
167,948 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size: int)` to solve the following problem:
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
Here is the function:
def window_partition(x, window_size: int):
"""
Args:
x: (B, H, W, C)
window_size (int): window size
Returns:
windows: (num_windows*B, window_size, window_size, C)
"""
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
return windows | Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
167,949 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size: int, H: int, W: int)` to solve the following problem:
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
Here is the function:
def window_reverse(windows, window_size: int, H: int, W: int):
"""
Args:
windows: (num_windows*B, window_size, window_size, C)
window_size (int): Window size
H (int): Height of image
W (int): Width of image
Returns:
x: (B, H, W, C)
"""
B = int(windows.shape[0] / (H * W / window_size / window_size))
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
return x | Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) |
167,950 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def get_relative_position_index(win_h, win_w):
# get pair-wise relative position index for each token inside the window
coords = torch.stack(torch.meshgrid([torch.arange(win_h), torch.arange(win_w)])) # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += win_h - 1 # shift to start from 0
relative_coords[:, :, 1] += win_w - 1
relative_coords[:, :, 0] *= 2 * win_w - 1
return relative_coords.sum(-1) # Wh*Ww, Wh*Ww | null |
167,951 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_base_patch4_window12_384` function. Write a Python function `def swin_base_patch4_window12_384(pretrained=False, **kwargs)` to solve the following problem:
Swin-B @ 384x384, pretrained ImageNet-22k, fine tune 1k
Here is the function:
def swin_base_patch4_window12_384(pretrained=False, **kwargs):
""" Swin-B @ 384x384, pretrained ImageNet-22k, fine tune 1k
"""
model_kwargs = dict(
patch_size=4, window_size=12, embed_dim=128, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), **kwargs)
return _create_swin_transformer('swin_base_patch4_window12_384', pretrained=pretrained, **model_kwargs) | Swin-B @ 384x384, pretrained ImageNet-22k, fine tune 1k |
167,952 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_base_patch4_window7_224` function. Write a Python function `def swin_base_patch4_window7_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-B @ 224x224, pretrained ImageNet-22k, fine tune 1k
Here is the function:
def swin_base_patch4_window7_224(pretrained=False, **kwargs):
""" Swin-B @ 224x224, pretrained ImageNet-22k, fine tune 1k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=128, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), **kwargs)
return _create_swin_transformer('swin_base_patch4_window7_224', pretrained=pretrained, **model_kwargs) | Swin-B @ 224x224, pretrained ImageNet-22k, fine tune 1k |
167,953 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_large_patch4_window12_384` function. Write a Python function `def swin_large_patch4_window12_384(pretrained=False, **kwargs)` to solve the following problem:
Swin-L @ 384x384, pretrained ImageNet-22k, fine tune 1k
Here is the function:
def swin_large_patch4_window12_384(pretrained=False, **kwargs):
""" Swin-L @ 384x384, pretrained ImageNet-22k, fine tune 1k
"""
model_kwargs = dict(
patch_size=4, window_size=12, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), **kwargs)
return _create_swin_transformer('swin_large_patch4_window12_384', pretrained=pretrained, **model_kwargs) | Swin-L @ 384x384, pretrained ImageNet-22k, fine tune 1k |
167,954 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_large_patch4_window7_224` function. Write a Python function `def swin_large_patch4_window7_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-L @ 224x224, pretrained ImageNet-22k, fine tune 1k
Here is the function:
def swin_large_patch4_window7_224(pretrained=False, **kwargs):
""" Swin-L @ 224x224, pretrained ImageNet-22k, fine tune 1k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), **kwargs)
return _create_swin_transformer('swin_large_patch4_window7_224', pretrained=pretrained, **model_kwargs) | Swin-L @ 224x224, pretrained ImageNet-22k, fine tune 1k |
167,955 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_small_patch4_window7_224` function. Write a Python function `def swin_small_patch4_window7_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-S @ 224x224, trained ImageNet-1k
Here is the function:
def swin_small_patch4_window7_224(pretrained=False, **kwargs):
""" Swin-S @ 224x224, trained ImageNet-1k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=96, depths=(2, 2, 18, 2), num_heads=(3, 6, 12, 24), **kwargs)
return _create_swin_transformer('swin_small_patch4_window7_224', pretrained=pretrained, **model_kwargs) | Swin-S @ 224x224, trained ImageNet-1k |
167,956 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_tiny_patch4_window7_224` function. Write a Python function `def swin_tiny_patch4_window7_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-T @ 224x224, trained ImageNet-1k
Here is the function:
def swin_tiny_patch4_window7_224(pretrained=False, **kwargs):
""" Swin-T @ 224x224, trained ImageNet-1k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), **kwargs)
return _create_swin_transformer('swin_tiny_patch4_window7_224', pretrained=pretrained, **model_kwargs) | Swin-T @ 224x224, trained ImageNet-1k |
167,957 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_base_patch4_window12_384_in22k` function. Write a Python function `def swin_base_patch4_window12_384_in22k(pretrained=False, **kwargs)` to solve the following problem:
Swin-B @ 384x384, trained ImageNet-22k
Here is the function:
def swin_base_patch4_window12_384_in22k(pretrained=False, **kwargs):
""" Swin-B @ 384x384, trained ImageNet-22k
"""
model_kwargs = dict(
patch_size=4, window_size=12, embed_dim=128, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), **kwargs)
return _create_swin_transformer('swin_base_patch4_window12_384_in22k', pretrained=pretrained, **model_kwargs) | Swin-B @ 384x384, trained ImageNet-22k |
167,958 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_base_patch4_window7_224_in22k` function. Write a Python function `def swin_base_patch4_window7_224_in22k(pretrained=False, **kwargs)` to solve the following problem:
Swin-B @ 224x224, trained ImageNet-22k
Here is the function:
def swin_base_patch4_window7_224_in22k(pretrained=False, **kwargs):
""" Swin-B @ 224x224, trained ImageNet-22k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=128, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), **kwargs)
return _create_swin_transformer('swin_base_patch4_window7_224_in22k', pretrained=pretrained, **model_kwargs) | Swin-B @ 224x224, trained ImageNet-22k |
167,959 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_large_patch4_window12_384_in22k` function. Write a Python function `def swin_large_patch4_window12_384_in22k(pretrained=False, **kwargs)` to solve the following problem:
Swin-L @ 384x384, trained ImageNet-22k
Here is the function:
def swin_large_patch4_window12_384_in22k(pretrained=False, **kwargs):
""" Swin-L @ 384x384, trained ImageNet-22k
"""
model_kwargs = dict(
patch_size=4, window_size=12, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), **kwargs)
return _create_swin_transformer('swin_large_patch4_window12_384_in22k', pretrained=pretrained, **model_kwargs) | Swin-L @ 384x384, trained ImageNet-22k |
167,960 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_large_patch4_window7_224_in22k` function. Write a Python function `def swin_large_patch4_window7_224_in22k(pretrained=False, **kwargs)` to solve the following problem:
Swin-L @ 224x224, trained ImageNet-22k
Here is the function:
def swin_large_patch4_window7_224_in22k(pretrained=False, **kwargs):
""" Swin-L @ 224x224, trained ImageNet-22k
"""
model_kwargs = dict(
patch_size=4, window_size=7, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), **kwargs)
return _create_swin_transformer('swin_large_patch4_window7_224_in22k', pretrained=pretrained, **model_kwargs) | Swin-L @ 224x224, trained ImageNet-22k |
167,961 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_s3_tiny_224` function. Write a Python function `def swin_s3_tiny_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-S3-T @ 224x224, ImageNet-1k. https://arxiv.org/abs/2111.14725
Here is the function:
def swin_s3_tiny_224(pretrained=False, **kwargs):
""" Swin-S3-T @ 224x224, ImageNet-1k. https://arxiv.org/abs/2111.14725
"""
model_kwargs = dict(
patch_size=4, window_size=(7, 7, 14, 7), embed_dim=96, depths=(2, 2, 6, 2),
num_heads=(3, 6, 12, 24), **kwargs)
return _create_swin_transformer('swin_s3_tiny_224', pretrained=pretrained, **model_kwargs) | Swin-S3-T @ 224x224, ImageNet-1k. https://arxiv.org/abs/2111.14725 |
167,962 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_s3_small_224` function. Write a Python function `def swin_s3_small_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-S3-S @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725
Here is the function:
def swin_s3_small_224(pretrained=False, **kwargs):
""" Swin-S3-S @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725
"""
model_kwargs = dict(
patch_size=4, window_size=(14, 14, 14, 7), embed_dim=96, depths=(2, 2, 18, 2),
num_heads=(3, 6, 12, 24), **kwargs)
return _create_swin_transformer('swin_s3_small_224', pretrained=pretrained, **model_kwargs) | Swin-S3-S @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725 |
167,963 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
def _create_swin_transformer(variant, pretrained=False, **kwargs):
model = build_model_with_cfg(
SwinTransformer, variant, pretrained,
pretrained_filter_fn=checkpoint_filter_fn,
**kwargs
)
return model
The provided code snippet includes necessary dependencies for implementing the `swin_s3_base_224` function. Write a Python function `def swin_s3_base_224(pretrained=False, **kwargs)` to solve the following problem:
Swin-S3-B @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725
Here is the function:
def swin_s3_base_224(pretrained=False, **kwargs):
""" Swin-S3-B @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725
"""
model_kwargs = dict(
patch_size=4, window_size=(7, 7, 14, 7), embed_dim=96, depths=(2, 2, 30, 2),
num_heads=(3, 6, 12, 24), **kwargs)
return _create_swin_transformer('swin_s3_base_224', pretrained=pretrained, **model_kwargs) | Swin-S3-B @ 224x224, trained ImageNet-1k. https://arxiv.org/abs/2111.14725 |
167,964 | import math
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models._builder import build_model_with_cfg
from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert
default_cfgs = {
'swin_base_patch4_window12_384': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384_22kto1k.pth',
input_size=(3, 384, 384), crop_pct=1.0),
'swin_base_patch4_window7_224': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22kto1k.pth',
),
'swin_large_patch4_window12_384': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window12_384_22kto1k.pth',
input_size=(3, 384, 384), crop_pct=1.0),
'swin_large_patch4_window7_224': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window7_224_22kto1k.pth',
),
'swin_small_patch4_window7_224': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth',
),
'swin_tiny_patch4_window7_224': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth',
),
'swin_base_patch4_window12_384_in22k': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384_22k.pth',
input_size=(3, 384, 384), crop_pct=1.0, num_classes=21841),
'swin_base_patch4_window7_224_in22k': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22k.pth',
num_classes=21841),
'swin_large_patch4_window12_384_in22k': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window12_384_22k.pth',
input_size=(3, 384, 384), crop_pct=1.0, num_classes=21841),
'swin_large_patch4_window7_224_in22k': _cfg(
url='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window7_224_22k.pth',
num_classes=21841),
'swin_s3_tiny_224': _cfg(
url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/s3_t-1d53f6a8.pth'
),
'swin_s3_small_224': _cfg(
url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/s3_s-3bb4c69d.pth'
),
'swin_s3_base_224': _cfg(
url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/s3_b-a1e95db4.pth'
)
}
def create_swin(name, **kwargs):
return eval(name)(pretrained_cfg=default_cfgs[name], **kwargs) | null |
167,965 | import torch
from torch import nn
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from .constants import OPENAI_CLIP_MEAN
from pyiqa.utils.registry import ARCH_REGISTRY
from transformers import CLIPImageProcessor
import torchvision.transforms.functional as F
from PIL import Image
OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
def expand2square(pil_img):
background_color = tuple(int(x*255) for x in OPENAI_CLIP_MEAN)
width, height = pil_img.size
maxwh = max(width, height)
result = Image.new(pil_img.mode, (maxwh, maxwh), background_color)
result.paste(pil_img, ((maxwh - width) // 2, (maxwh - height) // 2))
return result | null |
167,966 | import torch
import torch.nn as nn
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network
from typing import Union, List, cast
def make_layers(cfg: List[Union[str, int]]) -> nn.Sequential:
layers: List[nn.Module] = []
in_channels = 3
for v in cfg:
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
v = cast(int, v)
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
layers += [conv2d, nn.ReLU(inplace=True)]
in_channels = v
return nn.Sequential(*layers) | null |
167,967 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops.deform_conv import DeformConv2d
import numpy as np
from einops import repeat
import timm
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.archs.arch_util import load_pretrained_network, to_2tuple
def get_sinusoid_encoding_table(n_seq, d_hidn):
def cal_angle(position, i_hidn):
return position / np.power(10000, 2 * (i_hidn // 2) / d_hidn)
def get_posi_angle_vec(position):
return [cal_angle(position, i_hidn) for i_hidn in range(d_hidn)]
sinusoid_table = np.array([get_posi_angle_vec(i_seq) for i_seq in range(n_seq)])
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # even index sin
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # odd index cos
return sinusoid_table | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.