id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
2,560 |
def score(input):
if input[12] >= 9.725:
if input[12] >= 19.23:
var0 = 3.5343752
else:
var0 = 5.5722494
else:
if input[5] >= 6.941:
var0 = 11.1947155
else:
var0 = 7.4582143
if input[12] >= 5.1549997:
if input[12] >= 15... | null |
2,561 |
def score(input):
if input[12] > 9.725000000000003:
if input[12] > 16.205000000000002:
var0 = 21.71499740307178
else:
var0 = 22.322292901846218
else:
if input[5] > 7.418000000000001:
var0 = 24.75760617150803
else:
var0 = 23.029104... | null |
2,562 |
def score(input):
return 36.367080746577244 + input[0] * -0.10861311354908008 + input[1] * 0.046461486329936456 + input[2] * 0.027432259970172148 + input[3] * 2.6160671309537777 + input[4] * -17.51793656329737 + input[5] * 3.7674418196772255 + input[6] * -0.000021581753164971046 + input[7] * -1.4711768622633645 +... | null |
2,563 | from fontTools.ttLib import TTFont, woff2
from afdko.otf2ttf import otf_to_ttf
from os import path, getcwd, makedirs, listdir, remove, walk
from subprocess import run
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
from ttfautohint import ttfautohint
from enum import Enum, unique
import shu... | null |
2,564 | from fontTools.ttLib import TTFont, woff2
from afdko.otf2ttf import otf_to_ttf
from os import path, getcwd, makedirs, listdir, remove, walk
from subprocess import run
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
from ttfautohint import ttfautohint
from enum import Enum, unique
import shu... | null |
2,565 | from fontTools.ttLib import TTFont, woff2
from afdko.otf2ttf import otf_to_ttf
from os import path, getcwd, makedirs, listdir, remove, walk
from subprocess import run
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
from ttfautohint import ttfautohint
from enum import Enum, unique
import shu... | null |
2,566 | from fontTools.ttLib import TTFont, woff2
from afdko.otf2ttf import otf_to_ttf
from os import path, getcwd, makedirs, listdir, remove, walk
from subprocess import run
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
from ttfautohint import ttfautohint
from enum import Enum, unique
import shu... | null |
2,567 | from fontTools.ttLib import TTFont, woff2
from afdko.otf2ttf import otf_to_ttf
from os import path, getcwd, makedirs, listdir, remove, walk
from subprocess import run
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
from ttfautohint import ttfautohint
from enum import Enum, unique
import shu... | null |
2,568 | import argparse, os, sys, datetime, glob, importlib, csv
import numpy as np
import time
import torch
import torchvision
import pytorch_lightning as pl
from packaging import version
from omegaconf import OmegaConf
from torch.utils.data import random_split, DataLoader, Dataset, Subset
from functools import partial
from P... | null |
2,569 | import argparse, os, sys, datetime, glob, importlib, csv
import numpy as np
import time
import torch
import torchvision
import pytorch_lightning as pl
from packaging import version
from omegaconf import OmegaConf
from torch.utils.data import random_split, DataLoader, Dataset, Subset
from functools import partial
from P... | null |
2,570 | import argparse, os, sys, datetime, glob, importlib, csv
import numpy as np
import time
import torch
import torchvision
import pytorch_lightning as pl
from packaging import version
from omegaconf import OmegaConf
from torch.utils.data import random_split, DataLoader, Dataset, Subset
from functools import partial
from P... | null |
2,571 | import argparse, os, sys, datetime, glob, importlib, csv
import numpy as np
import time
import torch
import torchvision
import pytorch_lightning as pl
from packaging import version
from omegaconf import OmegaConf
from torch.utils.data import random_split, DataLoader, Dataset, Subset
from functools import partial
from P... | null |
2,572 | import argparse, os, sys, datetime, glob, importlib, csv
import numpy as np
import time
import torch
import torchvision
import pytorch_lightning as pl
from packaging import version
from omegaconf import OmegaConf
from torch.utils.data import random_split, DataLoader, Dataset, Subset
from functools import partial
from P... | null |
2,573 | import sys
import os
import cv2
import torch
import torch.nn.functional as F
import gradio as gr
import torchvision
from torchvision.transforms.functional import normalize
from ldm.util import instantiate_from_config
from torch import autocast
import PIL
import numpy as np
from pytorch_lightning import seed_everything
... | null |
2,574 | import sys
import os
import cv2
import torch
import torch.nn.functional as F
import gradio as gr
import torchvision
from torchvision.transforms.functional import normalize
from ldm.util import instantiate_from_config
from torch import autocast
import PIL
import numpy as np
from pytorch_lightning import seed_everything
... | Run a single prediction on the model |
2,575 | import datetime
import logging
import math
import time
import torch
from os import path as osp
from basicsr.data import build_dataloader, build_dataset
from basicsr.data.data_sampler import EnlargedSampler
from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from basicsr.models import build_model
... | null |
2,576 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from basicsr.utils.registry import LOSS_REGISTRY
The provided code snippet includes necessary dependencies for implementing the `r1_penalty` function. Write a Python function `def r1_penalty(... | R1 regularization for discriminator. The core idea is to penalize the gradient on real data alone: when the generator distribution produces the true data distribution and the discriminator is equal to 0 on the data manifold, the gradient penalty ensures that the discriminator cannot create a non-zero gradient orthogona... |
2,577 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from basicsr.utils.registry import LOSS_REGISTRY
def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01):
noise = torch.randn_like(fake_img) / math.sqrt(fake_img.shape[2] *... | null |
2,578 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from basicsr.utils.registry import LOSS_REGISTRY
The provided code snippet includes necessary dependencies for implementing the `gradient_penalty_loss` function. Write a Python function `def ... | Calculate gradient penalty for wgan-gp. Args: discriminator (nn.Module): Network for the discriminator. real_data (Tensor): Real input data. fake_data (Tensor): Fake input data. weight (Tensor): Weight tensor. Default: None. Returns: Tensor: A tensor for gradient penalty. |
2,579 | import functools
import torch
from torch.nn import functional as F
def weight_reduce_loss(loss, weight=None, reduction='mean'):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights. Default: None.
reduction (str): Sam... | Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated... |
2,580 | import functools
import torch
from torch.nn import functional as F
def get_local_weights(residual, ksize):
"""Get local weights for generating the artifact map of LDL.
It is only called by the `get_refined_artifact_map` function.
Args:
residual (Tensor): Residual between predicted and ground truth i... | Calculate the artifact map of LDL (Details or Artifacts: A Locally Discriminative Learning Approach to Realistic Image Super-Resolution. In CVPR 2022) Args: img_gt (Tensor): ground truth images. img_output (Tensor): output images given by the optimizing model. img_ema (Tensor): output images given by the ema model. ksi... |
2,581 | import torch
from torch import nn as nn
from torch.nn import functional as F
from basicsr.archs.vgg_arch import VGGFeatureExtractor
from basicsr.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def l1_loss(pred, target):
return F.l1_loss(pred, target, reduction='none') | null |
2,582 | import torch
from torch import nn as nn
from torch.nn import functional as F
from basicsr.archs.vgg_arch import VGGFeatureExtractor
from basicsr.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def mse_loss(pred, target):
return F.mse_loss(pred, target, reduction='none') | null |
2,583 | import torch
from torch import nn as nn
from torch.nn import functional as F
from basicsr.archs.vgg_arch import VGGFeatureExtractor
from basicsr.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def charbonnier_loss(pred, target, eps=1e-12):
return torch.sqrt((pred - target)**2 + eps) | null |
2,584 | import cv2
import math
import numpy as np
import os
from scipy.ndimage import convolve
from scipy.special import gamma
from basicsr.metrics.metric_util import reorder_image, to_y_channel
from basicsr.utils.matlab_functions import imresize
from basicsr.utils.registry import METRIC_REGISTRY
def niqe(img, mu_pris_param, c... | Calculate NIQE (Natural Image Quality Evaluator) metric. ``Paper: Making a "Completely Blind" Image Quality Analyzer`` This implementation could produce almost the same results as the official MATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zip > MATLAB R2021a result for tests/data/baboon.png: 5.... |
2,585 | import numpy as np
import torch
import torch.nn as nn
from scipy import linalg
from tqdm import tqdm
from basicsr.archs.inception import InceptionV3
class InceptionV3(nn.Module):
"""Pretrained InceptionV3 network returning feature maps"""
# Index of default block of inception to return,
# corresponds to o... | null |
2,586 | import numpy as np
import torch
import torch.nn as nn
from scipy import linalg
from tqdm import tqdm
from basicsr.archs.inception import InceptionV3
The provided code snippet includes necessary dependencies for implementing the `extract_inception_features` function. Write a Python function `def extract_inception_featu... | Extract inception features. Args: data_generator (generator): A data generator. inception (nn.Module): Inception model. len_generator (int): Length of the data_generator to show the progressbar. Default: None. device (str): Device. Default: cuda. Returns: Tensor: Extracted features. |
2,587 | import numpy as np
import torch
import torch.nn as nn
from scipy import linalg
from tqdm import tqdm
from basicsr.archs.inception import InceptionV3
The provided code snippet includes necessary dependencies for implementing the `calculate_fid` function. Write a Python function `def calculate_fid(mu1, sigma1, mu2, sigm... | 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 Dougal J. Sutherland. Args: mu1 (np.array): The sample mean over activations. sigma1 (np.array)... |
2,588 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
from basicsr.metrics.metric_util import reorder_image, to_y_channel
from basicsr.utils.color_util import rgb2ycbcr_pt
from basicsr.utils.registry import METRIC_REGISTRY
def reorder_image(img, input_order='HWC'):
"""Reorder images to 'HWC' o... | Calculate PSNR (Peak Signal-to-Noise Ratio). Reference: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Args: img (ndarray): Images with range [0, 255]. img2 (ndarray): Images with range [0, 255]. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the calculation. inpu... |
2,589 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
from basicsr.metrics.metric_util import reorder_image, to_y_channel
from basicsr.utils.color_util import rgb2ycbcr_pt
from basicsr.utils.registry import METRIC_REGISTRY
def rgb2ycbcr_pt(img, y_only=False):
"""Convert RGB images to YCbCr ima... | Calculate PSNR (Peak Signal-to-Noise Ratio) (PyTorch version). Reference: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Args: img (Tensor): Images with range [0, 1], shape (n, 3/1, h, w). img2 (Tensor): Images with range [0, 1], shape (n, 3/1, h, w). crop_border (int): Cropped pixels in each edge of an image... |
2,590 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
from basicsr.metrics.metric_util import reorder_image, to_y_channel
from basicsr.utils.color_util import rgb2ycbcr_pt
from basicsr.utils.registry import METRIC_REGISTRY
def _ssim(img, img2):
"""Calculate SSIM (structural similarity) for one ... | Calculate SSIM (structural similarity). ``Paper: Image quality assessment: From error visibility to structural similarity`` The results are the same as that of the official released MATLAB code in https://ece.uwaterloo.ca/~z70wang/research/ssim/. For three-channel images, SSIM is calculated for each channel and then av... |
2,591 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
from basicsr.metrics.metric_util import reorder_image, to_y_channel
from basicsr.utils.color_util import rgb2ycbcr_pt
from basicsr.utils.registry import METRIC_REGISTRY
def _ssim_pth(img, img2):
"""Calculate SSIM (structural similarity) (PyT... | Calculate SSIM (structural similarity) (PyTorch version). ``Paper: Image quality assessment: From error visibility to structural similarity`` The results are the same as that of the official released MATLAB code in https://ece.uwaterloo.ca/~z70wang/research/ssim/. For three-channel images, SSIM is calculated for each c... |
2,592 | import cv2
import random
import torch
The provided code snippet includes necessary dependencies for implementing the `paired_random_crop` function. Write a Python function `def paired_random_crop(img_gts, img_lqs, gt_patch_size, scale, gt_path=None)` to solve the following problem:
Paired random crop. Support Numpy ar... | Paired random crop. Support Numpy array and Tensor inputs. It crops lists of lq and gt images with corresponding locations. Args: img_gts (list[ndarray] | ndarray | list[Tensor] | Tensor): GT images. Note that all images should have the same shape. If the input is an ndarray, it will be transformed to a list containing... |
2,593 | import cv2
import random
import torch
def triplet_random_crop(img_gts, img_lqs, img_segs, gt_patch_size, scale, gt_path=None):
if not isinstance(img_gts, list):
img_gts = [img_gts]
if not isinstance(img_lqs, list):
img_lqs = [img_lqs]
if not isinstance(img_segs, list):
img_segs = [... | null |
2,594 | import cv2
import random
import torch
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, 18... | 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... |
2,595 | import cv2
import random
import torch
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):... | 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. |
2,596 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
The provided code snippet includes necessary dependencies for imp... | Calculate the CDF of the standard bivariate Gaussian distribution. Used in skewed Gaussian distribution. Args: d_matrix (ndarrasy): skew matrix. grid (ndarray): generated by :func:`mesh_grid`, with the shape (K, K, 2), K is the kernel size. Returns: cdf (ndarray): skewed cdf. |
2,597 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def random_bivariate_Gaussian(kernel_size,
sigma_x_range,
... | Randomly generate mixed kernels. Args: kernel_list (tuple): a list name of kernel types, support ['iso', 'aniso', 'skew', 'generalized', 'plateau_iso', 'plateau_aniso'] kernel_prob (tuple): corresponding kernel probability for each kernel type kernel_size (int): sigma_x_range (tuple): [0.6, 5] sigma_y_range (tuple): [0... |
2,598 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
The provided code snippet includes necessary dependencies for imp... | 2D sinc filter Reference: https://dsp.stackexchange.com/questions/58301/2-d-circularly-symmetric-low-pass-filter Args: cutoff (float): cutoff frequency in radians (pi is max) kernel_size (int): horizontal and vertical size, must be odd. pad_to (int): pad kernel size to desired size, must be odd or zero. |
2,599 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def generate_gaussian_noise(img, sigma=10, gray_noise=False):
... | Add Gaussian noise. Args: img (Numpy array): Input image, shape (h, w, c), range [0, 1], float32. sigma (float): Noise scale (measured in range 255). Default: 10. Returns: (Numpy array): Returned noisy image, shape (h, w, c), range[0, 1], float32. |
2,600 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def generate_gaussian_noise_pt(img, sigma=10, gray_noise=0):
"""Add Gaussian noise (PyTorch version).
A... | Add Gaussian noise (PyTorch version). Args: img (Tensor): Shape (b, c, h, w), range[0, 1], float32. scale (float | Tensor): Noise scale. Default: 1.0. Returns: (Tensor): Returned noisy image, shape (b, c, h, w), range[0, 1], float32. |
2,601 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_generate_gaussian_noise(img, sigma_range=(0, 10), gray_... | null |
2,602 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def random_generate_gaussian_noise_pt(img, sigma_range=(0, 10), gray_prob=0):
sigma = torch.rand(
i... | null |
2,603 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def generate_poisson_noise(img, scale=1.0, gray_noise=False):
... | Add poisson noise. Args: img (Numpy array): Input image, shape (h, w, c), range [0, 1], float32. scale (float): Noise scale. Default: 1.0. gray_noise (bool): Whether generate gray noise. Default: False. Returns: (Numpy array): Returned noisy image, shape (h, w, c), range[0, 1], float32. |
2,604 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def generate_poisson_noise_pt(img, scale=1.0, gray_noise=0):
"""Generate a batch of poisson noise (PyTorch ... | Add poisson noise to a batch of images (PyTorch version). Args: img (Tensor): Input image, shape (b, c, h, w), range [0, 1], float32. scale (float | Tensor): Noise scale. Number or Tensor with shape (b). Default: 1.0. gray_noise (float | Tensor): 0-1 number or Tensor with shape (b). 0 for False, 1 for True. Default: 0.... |
2,605 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_generate_poisson_noise(img, scale_range=(0, 1.0), gray_... | null |
2,606 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def random_generate_poisson_noise_pt(img, scale_range=(0, 1.0), gray_prob=0):
scale = torch.rand(
i... | null |
2,607 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_add_speckle_noise(imgs, speckle_std):
std_range = ... | null |
2,608 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
def random_add_speckle_noise_pt(img, speckle_std):
std_range = speckle_std
std_l = std_range[0]
st... | null |
2,609 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_add_saltpepper_noise(imgs, saltpepper_amount, saltpepp... | null |
2,610 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_add_saltpepper_noise_pt(imgs, saltpepper_amount, saltp... | null |
2,611 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def random_add_screen_noise(imgs, linewidth, space):
#screen_... | null |
2,612 | import cv2
import math
import numpy as np
import random
import torch
from scipy import special
from scipy.stats import multivariate_normal
from torchvision.transforms.functional_tensor import rgb_to_grayscale
np.seterr(divide='ignore', invalid='ignore')
def add_jpg_compression(img, quality=90):
"""Add JPG compressi... | Randomly add JPG compression artifacts. Args: img (Numpy array): Input image, shape (h, w, c), range [0, 1], float32. quality_range (tuple[float] | list[float]): JPG compression quality range. 0 for lowest quality, 100 for best quality. Default: (90, 100). Returns: (Numpy array): Returned image after JPG, shape (h, w, ... |
2,613 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
def mod_crop(img, scale):
"""Mod crop images, used during testing.
Args:
img (ndarray): Input image.
... | 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... |
2,614 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `generate_frame_indices` function. Write a... | 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... |
2,615 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_lmdb` function. Write a... | 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... |
2,616 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_meta_info_file` functio... | 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 ... |
2,617 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_meta_info_file_2` funct... | 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 ... |
2,618 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_folder` function. Write... | 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... |
2,619 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paths_from_folder` function. Write a Pyth... | Generate paths from folder. Args: folder (str): Folder path. Returns: list[str]: Returned path list. |
2,620 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
The provided code snippet includes necessary dependencies for implementing the `paths_from_lmdb` function. Write a Python... | Generate paths from lmdb. Args: folder (str): Folder path. Returns: list[str]: Returned path list. |
2,621 | import cv2
import numpy as np
import torch
from os import path as osp
from torch.nn import functional as F
from basicsr.data.transforms import mod_crop
from basicsr.utils import img2tensor, scandir
def generate_gaussian_kernel(kernel_size=13, sigma=1.6):
"""Generate Gaussian kernel used in `duf_downsample`.
Arg... | 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. |
2,622 | import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu
from basicsr.ops.upfirdn2d import upfirdn2d
from basicsr.utils.registry import ARCH_REGISTRY
The provided code snippet includes necessary dependencies for ... | Make resampling kernel for UpFirDn. Args: k (list[int]): A list indicating the 1D resample kernel magnitude. Returns: Tensor: 2D resampled kernel. |
2,623 | import os
import torch
from collections import OrderedDict
from torch import nn as nn
from torchvision.models import vgg as vgg
from basicsr.utils.registry import ARCH_REGISTRY
The provided code snippet includes necessary dependencies for implementing the `insert_bn` function. Write a Python function `def insert_bn(na... | Insert bn layer after each conv. Args: names (list): The list of layer names. Returns: list: The list of layer names with bn layers. |
2,624 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.model_zoo import load_url
from torchvision import models
FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth'
LOCAL_FID_WEIGHTS = 'experiments/pretrain... | 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 Incep... |
2,625 | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from torch.nn.utils import spectral_norm
def lip2d(x, logit, kernel=3, stride=2, padding=1):
weight = logit.exp()
return F.avg_pool2d(x * weight, kernel, stride, padding) / F.avg_pool2d(weight, kernel, stride... | null |
2,626 | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from torch.nn.utils import spectral_norm
def get_nonspade_norm_layer(norm_type='instance'):
# helper function to get # output channels of the previous layer
def get_out_channel(layer):
if hasattr(laye... | null |
2,627 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.nn.utils.spectral_norm import spectral_norm
def calc_mean_std(feat, eps=1e-5):
"""Calculate mean and std for adaptive_instance_normalization.
Args:
feat (Tensor): 4D tensor.
eps (flo... | Adaptive instance normalization. Adjust the reference features to have the similar color and illuminations as those in the degradate features. Args: content_feat (Tensor): The reference feature. style_feat (Tensor): The degradate features. |
2,628 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.nn.utils.spectral_norm import spectral_norm
def AttentionBlock(in_channel):
return nn.Sequential(
spectral_norm(nn.Conv2d(in_channel, in_channel, 3, 1, 1)), nn.LeakyReLU(0.2, True),
spe... | null |
2,629 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.nn.utils.spectral_norm import spectral_norm
The provided code snippet includes necessary dependencies for implementing the `conv_block` function. Write a Python function `def conv_block(in_channels, out_ch... | Conv block used in MSDilationBlock. |
2,630 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | 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. |
2,631 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | Make layers by stacking the same blocks. Args: basic_block (nn.module): nn.module class for basic block. num_basic_block (int): number of blocks. Returns: nn.Sequential: Stacked blocks in nn.Sequential. |
2,632 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | Warp an image or feature map with optical flow. Args: x (Tensor): Tensor with size (n, c, h, w). flow (Tensor): Tensor with size (n, h, w, 2), normal value. interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'. padding_mode (str): 'zeros' or 'border' or 'reflection'. Default: 'zeros'. align_corners (bool): B... |
2,633 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | Resize a flow according to ratio or shape. Args: flow (Tensor): Precomputed flow. shape [N, 2, H, W]. size_type (str): 'ratio' or 'shape'. sizes (list[int | float]): the ratio for resizing or the final output shape. 1) The order of ratio should be [ratio_h, ratio_w]. For downsampling, the ratio should be smaller than 1... |
2,634 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | Pixel unshuffle. Args: x (Tensor): Input feature with shape (b, c, hh, hw). scale (int): Downsample ratio. Returns: Tensor: the pixel unshuffled feature. |
2,635 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | r"""Fills the input Tensor with values drawn from a truncated normal distribution. From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:... |
2,636 | import collections.abc
import math
import torch
import torchvision
import warnings
from distutils.version import LooseVersion
from itertools import repeat
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
from basicsr.ops.... | null |
2,637 | import math
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from basicsr.utils.registry import ARCH_REGISTRY
from .arch_util import to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def d... | Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py |
2,638 | import math
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from basicsr.utils.registry import ARCH_REGISTRY
from .arch_util import to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function... | Args: x: (b, h, w, c) window_size (int): window size Returns: windows: (num_windows*b, window_size, window_size, c) |
2,639 | import math
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from basicsr.utils.registry import ARCH_REGISTRY
from .arch_util import to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `... | 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) |
2,640 | import os
import torch
from torch.autograd import Function
from torch.nn import functional as F
class UpFirDn2d(Function):
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
... | null |
2,641 | import os
import torch
from torch import nn
from torch.autograd import Function
class FusedLeakyReLUFunction(Function):
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale)
ctx.sav... | null |
2,642 | import math
from collections import Counter
from torch.optim.lr_scheduler import _LRScheduler
The provided code snippet includes necessary dependencies for implementing the `get_position_from_periods` function. Write a Python function `def get_position_from_periods(iteration, cumulative_period)` to solve the following... | Get the position from a period list. It will return the index of the right-closest number in the period list. For example, the cumulative_period = [100, 200, 300, 400], if iteration == 50, return 0; if iteration == 210, return 2; if iteration == 300, return 2. Args: iteration (int): Current iteration. cumulative_period... |
2,643 | import functools
import os
import subprocess
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def get_dist_info():
if dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
worl... | null |
2,644 | import cv2
import lmdb
import sys
from multiprocessing import Pool
from os import path as osp
from tqdm import tqdm
def read_img_worker(path, key, compress_level):
"""Read image worker.
Args:
path (str): Image path.
key (str): Image key.
compress_level (int): Compress level when encoding... | Make lmdb from images. Contents of lmdb. The file structure is: :: example.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 inform... |
2,645 | import math
import os
import requests
from torch.hub import download_url_to_file, get_dir
from tqdm import tqdm
from urllib.parse import urlparse
from .misc import sizeof_fmt
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
retur... | Download files from google drive. Reference: https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive Args: file_id (str): File id. save_path (str): Save path. |
2,646 | import math
import os
import requests
from torch.hub import download_url_to_file, get_dir
from tqdm import tqdm
from urllib.parse import urlparse
from .misc import sizeof_fmt
The provided code snippet includes necessary dependencies for implementing the `load_file_from_url` function. Write a Python function `def load_... | Load file form http url, will download models if necessary. Reference: 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. progres... |
2,647 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `img2tensor` function. Write a Python function `def img2tensor(imgs, bgr2rgb=True, float32=True)` to solve the following problem:
Numpy... | Numpy array to tensor. Args: imgs (list[ndarray] | ndarray): Input images. bgr2rgb (bool): Whether to change bgr to rgb. float32 (bool): Whether to change to float32. Returns: list[tensor] | tensor: Tensor images. If returned results only have one element, just return tensor. |
2,648 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `tensor2img` function. Write a Python function `def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1))` to solve the f... | Convert torch Tensors into image numpy arrays. After clamping to [min, max], values will be normalized to [0, 1]. Args: tensor (Tensor or list[Tensor]): Accept shapes: 1) 4D mini-batch Tensor of shape (B x 3/1 x H x W); 2) 3D Tensor of shape (3/1 x H x W); 3) 2D Tensor of shape (H x W). Tensor channel should be in RGB ... |
2,649 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `tensor2img_fast` function. Write a Python function `def tensor2img_fast(tensor, rgb2bgr=True, min_max=(0, 1))` to solve the following ... | This implementation is slightly faster than tensor2img. It now only supports torch tensor with shape (1, c, h, w). Args: tensor (Tensor): Now only support torch tensor with (1, c, h, w). rgb2bgr (bool): Whether to change rgb to bgr. Default: True. min_max (tuple[int]): min and max values for clamp. |
2,650 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `imfrombytes` function. Write a Python function `def imfrombytes(content, flag='color', float32=False)` to solve the following problem:... | Read an image from bytes. Args: content (bytes): Image bytes got from files or other streams. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale` and `unchanged`. float32 (bool): Whether to change to float32., If True, will also norm to [0, 1]. Default: False. Returns: nda... |
2,651 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `imwrite` function. Write a Python function `def imwrite(img, file_path, params=None, auto_mkdir=True)` to solve the following problem:... | Write image to file. Args: img (ndarray): Image array to be written. file_path (str): Image file path. params (None or list): Same as opencv's :func:`imwrite` interface. auto_mkdir (bool): If the parent folder of `file_path` does not exist, whether to create it automatically. Returns: bool: Successful or not. |
2,652 | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
The provided code snippet includes necessary dependencies for implementing the `crop_border` function. Write a Python function `def crop_border(imgs, crop_border)` to solve the following problem:
Crop borders of im... | Crop borders of images. Args: imgs (list[ndarray] | ndarray): Images with shape (h, w, c). crop_border (int): Crop border for each end of height and weight. Returns: list[ndarray]: Cropped images. |
2,653 | import numpy as np
import os
import random
import time
import torch
from os import path as osp
from .dist_util import master_only
The provided code snippet includes necessary dependencies for implementing the `set_random_seed` function. Write a Python function `def set_random_seed(seed)` to solve the following problem... | Set random seeds. |
2,654 | import numpy as np
import os
import random
import time
import torch
from os import path as osp
from .dist_util import master_only
def mkdir_and_rename(path):
"""mkdirs. If path exists, rename it with timestamp and create a new one.
Args:
path (str): Folder path.
"""
if osp.exists(path):
... | Make dirs for experiments. |
2,655 | import numpy as np
import os
import random
import time
import torch
from os import path as osp
from .dist_util import master_only
The provided code snippet includes necessary dependencies for implementing the `scandir` function. Write a Python function `def scandir(dir_path, suffix=None, recursive=False, full_path=Fal... | Scan a directory to find the interested files. Args: dir_path (str): Path of the directory. suffix (str | tuple(str), optional): File suffix that we are interested in. Default: None. recursive (bool, optional): If set to True, recursively scan the directory. Default: False. full_path (bool, optional): If set to True, i... |
2,656 | import numpy as np
import os
import random
import time
import torch
from os import path as osp
from .dist_util import master_only
The provided code snippet includes necessary dependencies for implementing the `check_resume` function. Write a Python function `def check_resume(opt, resume_iter)` to solve the following p... | Check resume states and pretrain_network paths. Args: opt (dict): Options. resume_iter (int): Resume iteration. |
2,657 | import cv2
import numpy as np
import os
def dequantize_flow(dx, dy, max_val=0.02, denorm=True):
"""Recover from quantized flow.
Args:
dx (ndarray): Quantized dx.
dy (ndarray): Quantized dy.
max_val (float): Maximum value used when quantizing.
denorm (bool): Whether to multiply fl... | Read an optical flow map. Args: flow_path (ndarray or str): Flow path. quantize (bool): whether to read quantized pair, if set to True, remaining args will be passed to :func:`dequantize_flow`. concat_axis (int): The axis that dx and dy are concatenated, can be either 0 or 1. Ignored if quantize is False. Returns: ndar... |
2,658 | import cv2
import numpy as np
import os
def quantize_flow(flow, max_val=0.02, norm=True):
"""Quantize flow to [0, 255].
After this step, the size of flow will be much smaller, and can be
dumped as jpeg images.
Args:
flow (ndarray): (h, w, 2) array of optical flow.
max_val (float): Maximu... | Write optical flow to file. If the flow is not quantized, it will be saved as a .flo file losslessly, otherwise a jpeg image which is lossy but of much smaller size. (dx and dy will be concatenated horizontally into a single image if quantize is True.) Args: flow (ndarray): (h, w, 2) array of optical flow. filename (st... |
2,659 | import cv2
import numpy as np
import torch
from torch.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `filter2D` function. Write a Python function `def filter2D(img, kernel)` to solve the following problem:
PyTorch version of cv2.filter2D Args: img (Tensor): (b,... | PyTorch version of cv2.filter2D Args: img (Tensor): (b, c, h, w) kernel (Tensor): (b, k, k) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.