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, c... | 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)... | 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/refere... | 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 ... |
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 followi... | 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... |
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 = ... | 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 f... | 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')` ... | 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 ne... |
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... | 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 ... |
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) *... | 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.si... | 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... | 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 = posi... | 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 c... | 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 c... | 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':... | 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':... | 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_2tupl... | 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_2tupl... | 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_2tupl... | 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): H... |
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_2tupl... | 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 ten... | 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 represent... |
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` fun... | 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_... |
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):... | 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. Retur... |
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` ... | 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_circl... |
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` ... | 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 sp... |
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_i... | 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 ... |
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... | 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 tha... |
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` funct... | 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` functio... | 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_dow... | 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, ... | 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... |
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/afeb0e10f9e5... | 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... |
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 `torchvisi... | 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 Incept... |
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 impor... | 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 impor... | 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, ... | 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... | 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 facto... | 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 = to... | 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", "refl... | 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_clas... | 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 mak... | 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
... | 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 channe... | 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 p... |
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 tor... | 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_statisti... | 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 u... |
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=o... | 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)... | 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_pla... | 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_pla... | 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,
... | 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_parti... | 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_rever... | 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 i... | 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 i... | 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.... |
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 i... | 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 i... | 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 i... | 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:
... | 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_p... | 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_pat... | 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_ag... | 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'. p... |
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_ag... | 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... | 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 grad... |
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,
... | 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 chan... |
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,
sca... | 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 ... |
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 py... | 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 py... | 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 inc... |
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 py... | 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 py... | 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, dct... | 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 pretrai... |
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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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, t... | 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 = (... | 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:
i... | 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_... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.