id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
151,106 | import numpy as np
from skimage import measure
from scipy import linalg
import torch
import torch.nn as nn
import torch.nn.functional as F
from core.utils import to_tensors
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""Numpy implementation of the Frechet Distance.
The Frechet distance b... | Given two distribution of features, compute the FID score between them Params: real_activations: list[ndarray] fake_activations: list[ndarray] |
151,107 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.video.raft import RAFT
from backend.inpaint.video.model.modules.flow_loss_utils import flow_warp, ternary_loss2
The provided code snippet includes necessary dependencies for implementing the `initialize_RAFT` functi... | Initializes the RAFT model. |
151,108 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.video.raft import RAFT
from backend.inpaint.video.model.modules.flow_loss_utils import flow_warp, ternary_loss2
def smoothness_deltas(flow):
"""
flow: [b, c, h, w]
"""
mask_x = create_mask(flow, [[0, ... | null |
151,109 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.video.raft import RAFT
from backend.inpaint.video.model.modules.flow_loss_utils import flow_warp, ternary_loss2
def charbonnier_loss(x, mask=None, truncate=None, alpha=0.45, beta=1.0, epsilon=0.001):
"""
Comp... | null |
151,110 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.video.raft import RAFT
from backend.inpaint.video.model.modules.flow_loss_utils import flow_warp, ternary_loss2
def flow_warp(x,
flow,
interpolation='bilinear',
padding_mode... | null |
151,111 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.video.raft import RAFT
from backend.inpaint.video.model.modules.flow_loss_utils import flow_warp, ternary_loss2
The provided code snippet includes necessary dependencies for implementing the `edgeLoss` function. Wri... | Args: preds_edges: with shape [b, c, h , w] edges: with shape [b, c, h, w] Returns: Edge losses |
151,112 | import math
from functools import reduce
import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size, n_head)` to solve the following problem:
... | Args: x: shape is (B, T, H, W, C) window_size (tuple[int]): window size Returns: windows: (B, num_windows_h, num_windows_w, n_head, T, window_size, window_size, C//n_head) |
151,115 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def flow_warp(x,
flow,
interpolation='bilinear',
padding_mode='zeros',
align_corners=True):
"""Warp an image or a feature map with optical flow.
Args:
x (Tensor):... | null |
151,116 | import os
import torch
from collections import OrderedDict
from torch import nn as nn
from torchvision.models import vgg as vgg
The provided code snippet includes necessary dependencies for implementing the `insert_bn` function. Write a Python function `def insert_bn(names)` to solve the following problem:
Insert bn l... | Insert bn layer after each conv. Args: names (list): The list of layer names. Returns: list: The list of layer names with bn layers. |
151,117 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from einops import rearrange
from backend.inpaint.video.model.modules.base_module import BaseNetwork
from backend.inpaint.video.model.modules.sparse_transformer import TemporalSparseTransformerBlock, SoftSplit, SoftComp
from backend.i... | null |
151,118 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from einops import rearrange
from backend.inpaint.video.model.modules.base_module import BaseNetwork
from backend.inpaint.video.model.modules.sparse_transformer import TemporalSparseTransformerBlock, SoftSplit, SoftComp
from backend.i... | null |
151,119 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
r"""Function that returns... | r"""Compute the first and second order volume derivative in x, y and d using a diff operator. Args: input: input features tensor with shape :math:`(B, C, D, H, W)`. mode: derivatives modality, can be: `sobel` or `diff`. order: the order of the derivatives. Return: the spatial gradients of the input feature map with sha... |
151,120 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:
r"""Compute the first orde... | r"""Compute the Sobel operator and returns the magnitude per channel. .. image:: _static/img/sobel.png Args: input: the input image with shape :math:`(B,C,H,W)`. normalized: if True, L1 norm of the kernel is set to 1. eps: regularization number to avoid NaN during backprop. Return: the sobel edge gradient magnitudes ma... |
151,121 | from typing import List
import torch
import torch.nn.functional as F
from .kernels import normalize_kernel2d
def _compute_padding(kernel_size: List[int]) -> List[int]:
"""Compute padding tuple."""
# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
# https://pytorch.org/docs/stable/nn.h... | r"""Convolve a tensor with a 3d kernel. The function applies a given kernel to a tensor. The kernel is applied independently at each depth channel of the tensor. Before applying the kernel, the function applies padding according to the specified mode so that the output remains in the same shape. Args: input: the input ... |
151,122 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
The provided code snippet includes necessary dependencies for implementing the `get_box_kernel2d` function. Write a Python function `def get_box_kernel2d(kernel_size: Tuple[int, int]) -> torch.Tensor` to solve the following problem... | r"""Utility function that returns a box filter. |
151,123 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
The provided code snippet includes necessary dependencies for implementing the `get_binary_kernel2d` function. Write a Python function `def get_binary_kernel2d(window_size: Tuple[int, int]) -> torch.Tensor` to solve the following p... | r"""Create a binary kernel to extract the patches. If the window size is HxW will create a (H*W)xHxW kernel. |
151,124 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
def gaussian_discrete(window_size, sigma) -> torch.Tensor:
r"""Discrete Gaussian kernel based on the modified Bessel functions.
Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convu... | r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions. Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py. Args: kernel_size: filter size. It should be odd and positive. sigma: gaussian standard deviation. force_even: overrides req... |
151,125 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:
r"""Discrete Gaussian by interpolating the error function.
Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convut... | r"""Function that returns Gaussian filter coefficients by interpolating the error function, adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py. Args: kernel_size: filter size. It should be odd and positive. sigma: gaussian standard deviation. force_even: overrides requir... |
151,126 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
def laplacian_1d(window_size) -> torch.Tensor:
r"""One could also use the Laplacian of Gaussian formula to design the filter."""
filter_1d = torch.ones(window_size)
filter_1d[window_size // 2] = 1 - window_size
lapla... | r"""Function that returns the coefficients of a 1D Laplacian filter. Args: kernel_size: filter size. It should be odd and positive. Returns: 1D tensor with laplacian filter coefficients. Shape: - Output: math:`(\text{kernel_size})` Examples: >>> get_laplacian_kernel1d(3) tensor([ 1., -2., 1.]) >>> get_laplacian_kernel1... |
151,127 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
The provided code snippet includes necessary dependencies for implementing the `get_laplacian_kernel2d` function. Write a Python function `def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor` to solve the following problem... | r"""Function that returns Gaussian filter matrix coefficients. Args: kernel_size: filter size should be odd. Returns: 2D tensor with laplacian filter matrix coefficients. Shape: - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)` Examples: >>> get_laplacian_kernel2d(3) tensor([[ 1., 1., 1.], [ 1., -8., 1.], ... |
151,128 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
Args:
kernel_size: height and width of the kernel.
norm: if... | Generate pascal filter kernel by kernel size. Args: kernel_size: height and width of the kernel. norm: if to normalize the kernel or not. Default: True. Returns: kernel shaped as :math:`(kernel_size, kernel_size)` Examples: >>> get_pascal_kernel_2d(1) tensor([[1.]]) >>> get_pascal_kernel_2d(4) tensor([[0.0156, 0.0469, ... |
151,129 | import math
from math import sqrt
from typing import List, Optional, Tuple
import torch
def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
r"""Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0... | r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker. Args: kernel_size: The size of the kernel for the filter. It should be positive. Returns: 2D tensor with Hanning filter coefficients. .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right) Shape: - Output: math:`(\text{kernel_size[0], ... |
151,130 | import math
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from .gaussian import gaussian_blur2d
from .kernels import get_canny_nms_kernel, get_hysteresis_kernel
from .sobel import spatial_gradient
def rgb_to_grayscale(image, rgb_weights = None):
if len(image.shape) < 3 ... | r"""Find edges of the input image and filters them using the Canny algorithm. .. image:: _static/img/canny.png Args: input: input image tensor with shape :math:`(B,C,H,W)`. low_threshold: lower threshold for the hysteresis procedure. high_threshold: upper threshold for the hysteresis procedure. kernel_size: the size of... |
151,131 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
def constant_init(module, val, bias=0):
if hasattr(module, 'weight') and module.weight is not None:
nn.init.constant_(module.weight, val)
if hasattr(module, 'bia... | null |
151,132 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
initialized_logger = {}
The provided code snippet includes necessary dependencies for implementing the `get_root_logger` function. Write a Python function `def get_root_logger(l... | Get the root logger. The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If `log_file` is specified, a FileHandler will also be added. Args: logger_name (str): root logger name. Default: 'basicsr'. log_file (str | None): The log filename. If specified, a FileHandler ... |
151,133 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
IS_HIGH_VERSION = [int(m) for m in list(re.findall(r"^([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9][a-zA-Z0-9]*)?(\+git.*)?$",\
torch.__version__)[0][:3])] >= [1, 12, 0]
def gpu_is_av... | null |
151,134 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
IS_HIGH_VERSION = [int(m) for m in list(re.findall(r"^([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9][a-zA-Z0-9]*)?(\+git.*)?$",\
torch.__version__)[0][:3])] >= [1, 12, 0]
def get_devic... | null |
151,135 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
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 follo... | Set random seeds. |
151,136 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
def get_time_str():
return time.strftime('%Y%m%d_%H%M%S', time.localtime()) | null |
151,137 | import os
import re
import random
import time
import torch
import torch.nn as nn
import logging
import numpy as np
from os import path as osp
The provided code snippet includes necessary dependencies for implementing the `scandir` function. Write a Python function `def scandir(dir_path, suffix=None, recursive=False, f... | 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... |
151,138 | import os
import cv2
import numpy as np
import scipy.ndimage
from PIL import Image
import torch
import torchvision
from backend import config
from backend.inpaint.video.model.modules.flow_comp_raft import RAFT_bi
from backend.inpaint.video.model.recurrent_flow_completion import RecurrentFlowCompleteNet
from backend.inp... | null |
151,139 | import os
import cv2
import numpy as np
import scipy.ndimage
from PIL import Image
import torch
import torchvision
from backend import config
from backend.inpaint.video.model.modules.flow_comp_raft import RAFT_bi
from backend.inpaint.video.model.recurrent_flow_completion import RecurrentFlowCompleteNet
from backend.inp... | Prepares the data for video outpainting. |
151,140 | import os
import cv2
import numpy as np
import scipy.ndimage
from PIL import Image
import torch
import torchvision
from backend import config
from backend.inpaint.video.model.modules.flow_comp_raft import RAFT_bi
from backend.inpaint.video.model.recurrent_flow_completion import RecurrentFlowCompleteNet
from backend.inp... | null |
151,141 | import os
import cv2
import numpy as np
import scipy.ndimage
from PIL import Image
import torch
import torchvision
from backend import config
from backend.inpaint.video.model.modules.flow_comp_raft import RAFT_bi
from backend.inpaint.video.model.recurrent_flow_completion import RecurrentFlowCompleteNet
from backend.inp... | null |
151,142 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from backend.inpaint.utils.spectral_norm import spectral_norm as _spectral_norm
def spectral_norm(module, mode=True):
if mode:
return _spectral_norm(module)
return module | null |
151,144 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def load_img_to_array(img_p):
img = Image.open(img_p)
if img.mode == "RGBA":
img = img.convert("RGB")
return np.array(img) | null |
151,145 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def save_array_to_img(img_arr, img_p):
Image.fromarray(img_arr.astype(np.uint8)).save(img_p) | null |
151,146 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def dilate_mask(mask, dilate_factor=15):
mask = mask.astype(np.uint8)
mask = cv2.dilate(
mask,
np.ones((dilate_factor, dilate_factor), np.uint8),
iterations=1
)
return mask | null |
151,147 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def erode_mask(mask, dilate_factor=15):
mask = mask.astype(np.uint8)
mask = cv2.erode(
mask,
np.ones((dilate_factor, dilate_factor), np.uint8),
iterations=1
)
return mask | null |
151,148 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def show_mask(ax, mask: np.ndarray, random_color=False):
mask = mask.astype(np.uint8)
if np.max(mask) == 255:
mask = mask / 255
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6]... | null |
151,149 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def show_points(ax, coords: List[List[float]], labels: List[int], size=375):
coords = np.array(coords)
labels = np.array(labels)
color_table = {0: 'red', 1: 'green'}
for label_value, color in color_table.items():
... | null |
151,150 | import cv2
import numpy as np
from PIL import Image
from typing import Any, Dict, List
def get_clicked_point(img_path):
img = cv2.imread(img_path)
cv2.namedWindow("image")
cv2.imshow("image", img)
last_point = []
keep_looping = True
def mouse_callback(event, x, y, flags, param):
nonlo... | null |
151,151 | import os
import sys
import torch
import numpy as np
import cv2
from PIL import Image
from torch.hub import download_url_to_file, get_dir
from urllib.parse import urlparse
def get_image(image):
def scale_image(img, factor, interpolation=cv2.INTER_AREA):
def pad_img_to_modulo(img, mod):
def prepare_img_and_mask(image, ... | null |
151,152 | import torch
from torch.nn.functional import normalize
class SpectralNorm(object):
# Invariant before and after each forward call:
# u = normalize(W @ v)
# NB: At initialization, this invariant is not enforced
_version = 1
# At version 1:
# made `W` not a buffer,
# added `v` as a buff... | r"""Removes the spectral normalization reparameterization from a module. Args: module (Module): containing module name (str, optional): name of weight parameter Example: >>> m = spectral_norm(nn.Linear(40, 10)) >>> remove_spectral_norm(m) |
151,153 | import torch
from torch.nn.functional import normalize
def spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None):
def use_spectral_norm(module, use_sn=False):
if use_sn:
return spectral_norm(module)
return module | null |
151,154 | import matplotlib.patches as patches
from matplotlib.path import Path
import io
import cv2
import random
import zipfile
import numpy as np
from PIL import Image, ImageOps
import torch
import matplotlib
from matplotlib import pyplot as plt
def get_random_shape(edge_num=9, ratio=0.7, width=432, height=240):
'''
... | null |
151,155 | import importlib
import logging
import os
import os.path
import platform
import re
import string
import subprocess
import sys
from typing import AnyStr, Dict, List, Optional, Union
import cv2
def get_and_create_path(file_path: AnyStr, output_directory: Optional[AnyStr] = None) -> AnyStr:
""" Get & Create Path: Gets... | Initializes logging for PySceneDetect. The logger instance used is named 'pyscenedetect'. By default the logger has no handlers to suppress output. All existing log handlers are replaced every time this function is invoked. Arguments: log_level: Verbosity of log messages. Should be one of [logging.INFO, logging.DEBUG, ... |
151,156 | import importlib
import logging
import os
import os.path
import platform
import re
import string
import subprocess
import sys
from typing import AnyStr, Dict, List, Optional, Union
import cv2
def get_ffmpeg_version() -> Optional[str]:
"""Get ffmpeg version identifier, or None if ffmpeg is not found. Uses `get_ffmpe... | Get the system's operating system, Python, packages, and external tool versions. Useful for debugging or filing bug reports. Used for the `scenedetect version -a` command. |
151,157 | import logging
import os
from string import Template
import time
from typing import Dict, List, Tuple, Optional
from string import Template
from scenedetect.detectors import AdaptiveDetector
from scenedetect.frame_timecode import FrameTimecode
from scenedetect.platform import get_and_create_path, get_file_name
from sce... | Perform main CLI application control logic. Run once all command-line options and configuration file options have been validated. Arguments: context: Prevalidated command-line option context to use for processing. |
151,158 | from abc import ABC, abstractmethod
import logging
import os
import os.path
from configparser import ConfigParser, ParsingError
from typing import Any, AnyStr, Dict, List, Optional, Tuple, Union
from platformdirs import user_config_dir
from scenedetect.detectors import ContentDetector
from scenedetect.frame_timecode im... | Validates the layout of the section/option mapping. Returns: List of any parsing errors in human-readable form. |
151,159 | from abc import ABC, abstractmethod
import logging
import os
import os.path
from configparser import ConfigParser, ParsingError
from typing import Any, AnyStr, Dict, List, Optional, Tuple, Union
from platformdirs import user_config_dir
from scenedetect.detectors import ContentDetector
from scenedetect.frame_timecode im... | Process the given configuration into a key-value mapping. Returns: Configuration mapping and list of any processing errors in human readable form. |
151,160 | import logging
import os
from typing import Any, AnyStr, Dict, Optional, Tuple, Type
import click
import scenedetect
from scenedetect import open_video, AVAILABLE_BACKENDS
from scenedetect._scene_loader import SceneLoader
from scenedetect.scene_detector import SceneDetector
from scenedetect.platform import get_and_crea... | Parses a user input string into a FrameTimecode assuming the given framerate. If value is None, None will be returned instead of processing the value. Raises: click.BadParameter |
151,161 | import logging
import os
from typing import Any, AnyStr, Dict, Optional, Tuple, Type
import click
import scenedetect
from scenedetect import open_video, AVAILABLE_BACKENDS
from scenedetect._scene_loader import SceneLoader
from scenedetect.scene_detector import SceneDetector
from scenedetect.platform import get_and_crea... | Checks if the video path is a URL or image sequence. |
151,162 | import csv
from enum import Enum
from typing import Iterable, List, Tuple, Optional, Dict, Callable, Union, TextIO
import threading
import queue
import logging
import math
import sys
import cv2
import numpy as np
from backend.scenedetect._thirdparty.simpletable import (SimpleTableCell, SimpleTableImage, SimpleTableRow,... | Get the optimal default downscale factor based on a video's resolution (currently only the width in pixels is considered). The resulting effective width of the video will be between frame_width and 1.5 * frame_width pixels (e.g. if frame_width is 200, the range of effective widths will be between 200 and 300). Argument... |
151,163 | import csv
from enum import Enum
from typing import Iterable, List, Tuple, Optional, Dict, Callable, Union, TextIO
import threading
import queue
import logging
import math
import sys
import cv2
import numpy as np
from backend.scenedetect._thirdparty.simpletable import (SimpleTableCell, SimpleTableImage, SimpleTableRow,... | Returns a list of tuples of start/end FrameTimecodes for each scene based on a list of detected scene cuts/breaks. This function is called when using the :meth:`SceneManager.get_scene_list` method. The scene list is generated from a cutting list (:meth:`SceneManager.get_cut_list`), noting that each scene is contiguous,... |
151,164 | import codecs
def quote(string):
try:
from urllib.parse import quote
return quote(string)
except ModuleNotFoundError:
from urllib import pathname2url
return pathname2url(string) | null |
151,165 | import codecs
The provided code snippet includes necessary dependencies for implementing the `fit_data_to_columns` function. Write a Python function `def fit_data_to_columns(data, num_cols)` to solve the following problem:
Format data into the configured number of columns in a proper format to generate a SimpleTable. ... | Format data into the configured number of columns in a proper format to generate a SimpleTable. Example: test_data = [str(x) for x in range(20)] fitted_data = fit_data_to_columns(test_data, 5) table = SimpleTable(fitted_data) |
151,166 | import os
import math
from logging import getLogger
from typing import Iterable, List, Optional, Tuple, Union
from numpy import ndarray
import cv2
from scenedetect.platform import get_file_name
from scenedetect.frame_timecode import FrameTimecode, MAX_FPS_DELTA
from scenedetect.video_stream import VideoStream, VideoOpe... | Get Number of Frames: Returns total number of frames in the cap_list. Calls get(CAP_PROP_FRAME_COUNT) and returns the sum for all VideoCaptures. |
151,167 | import os
import math
from logging import getLogger
from typing import Iterable, List, Optional, Tuple, Union
from numpy import ndarray
import cv2
from scenedetect.platform import get_file_name
from scenedetect.frame_timecode import FrameTimecode, MAX_FPS_DELTA
from scenedetect.video_stream import VideoStream, VideoOpe... | Open Captures - helper function to open all capture objects, set the framerate, and ensure that all open captures have been opened and the framerates match on a list of video file paths, or a list containing a single device ID. Arguments: video_files: List of one or more paths (str), or a list of a single integer devic... |
151,168 | from enum import Enum
from logging import getLogger
from typing import List, Optional
import numpy
from backend.scenedetect.scene_detector import SceneDetector
The provided code snippet includes necessary dependencies for implementing the `_compute_frame_average` function. Write a Python function `def _compute_frame_a... | Computes the average pixel value/intensity for all pixels in a frame. The value is computed by adding up the 8-bit R, G, and B values for each pixel, and dividing by the number of pixels multiplied by 3. Arguments: frame: Frame representing the RGB pixels to average. Returns: Average pixel intensity across all 3 channe... |
151,169 | from dataclasses import dataclass
import math
from typing import List, NamedTuple, Optional
import numpy
import cv2
from backend.scenedetect.scene_detector import SceneDetector
The provided code snippet includes necessary dependencies for implementing the `_mean_pixel_distance` function. Write a Python function `def _... | Return the mean average distance in pixel values between `left` and `right`. Both `left and `right` should be 2 dimensional 8-bit images of the same shape. |
151,170 | from dataclasses import dataclass
import math
from typing import List, NamedTuple, Optional
import numpy
import cv2
from backend.scenedetect.scene_detector import SceneDetector
The provided code snippet includes necessary dependencies for implementing the `_estimated_kernel_size` function. Write a Python function `def... | Estimate kernel size based on video resolution. |
151,171 | from logging import getLogger
import math
from typing import AnyStr, Tuple, Union, Optional
import os.path
import cv2
from numpy import ndarray
from backend.scenedetect.frame_timecode import FrameTimecode, MAX_FPS_DELTA
from backend.scenedetect.platform import get_file_name
from backend.scenedetect.video_stream import ... | Display/pixel aspect ratio of the VideoCapture as a float (1.0 represents square pixels). |
151,173 | import paddle
import paddle.nn as nn
import numpy as np
import cv2
from .rec_ctc_loss import CTCLoss
from .rec_sar_loss import SARLoss
from .basic_loss import DMLLoss
from .basic_loss import DistanceLoss
from .det_db_loss import DBLoss
from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss
def _sum_loss(loss_di... | null |
151,174 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def resize_norm_img_sar(img, image_shape, width_downsample_ratio=0.25):
imgC, imgH, imgW_min, imgW_max = image_shape
h = img.shape[0]
w = img.shape... | null |
151,175 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def resize_norm_img(img, image_shape, padding=True):
imgC, imgH, imgW = image_shape
h = img.shape[0]
w = img.shape[1]
if not padding:
r... | null |
151,176 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def resize_norm_img_chinese(img, image_shape):
imgC, imgH, imgW = image_shape
# todo: change to 0 and modified image shape
max_wh_ratio = imgW * 1.... | null |
151,177 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def cvtColor(img):
"""
cvtColor
"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
delta = 0.001 * random.random() * flag()
hsv[:, :, 2] = h... | null |
151,178 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def srn_other_inputs(image_shape, num_heads, max_text_length):
imgC, imgH, imgW = image_shape
feature_dim = int((imgH / 8) * (imgW / 8))
encoder_... | null |
151,179 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def rad(x):
"""
rad
"""
return x * np.pi / 180
The provided code snippet includes necessary dependencies for implementing the `get_warpR` funct... | get_warpR |
151,180 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def rad(x):
"""
rad
"""
return x * np.pi / 180
The provided code snippet includes necessary dependencies for implementing the `get_warpAffine` ... | get_warpAffine |
151,181 | import math
import cv2
import numpy as np
import random
import copy
from PIL import Image
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
def cvtColor(img):
"""
cvtColor
"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
delta = 0.001 * random.random() * flag()
hsv[:, :, 2] = h... | warp |
151,183 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import cv2
import random
def is_poly_outside_rect(poly, x, y, w, h):
def split_regions(axis):
def random_select(axis, max_size):
def region_wise_random_... | null |
151,184 | import copy
import cv2
import random
import numpy as np
from PIL import Image
from shapely.geometry import Polygon
from ppocr.data.imaug.iaa_augment import IaaAugment
from ppocr.data.imaug.random_crop_data import is_poly_outside_rect
from tools.infer.utility import get_rotate_crop_image
def get_union(pD, pG):
def get_i... | null |
151,194 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
import numpy as np
def conv3x3(in_channel, out_channel, stride=1):
return nn.Conv2D(
in_channel,
... | null |
151,195 | from paddle import ParamAttr
from paddle.nn.initializer import KaimingNormal
import numpy as np
import paddle
import paddle.nn as nn
from paddle.nn.initializer import TruncatedNormal, Constant, Normal
The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python fu... | Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... |
151,197 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import paddle
from paddle import nn, ParamAttr
from paddle.nn import functional as F
import numpy as np
import itertools
def grid_sample(input, grid, canvas=None):
input.stop_gradient = False
... | null |
151,201 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import paddle
from paddle import nn
import paddle.nn.functional as F
from paddle import ParamAttr
def get_bias_attr(k):
stdv = 1.0 / math.sqrt(k * 1.0)
initializer = paddle.nn.initializer.Un... | null |
151,202 | import math
import paddle
import copy
from paddle import nn
import paddle.nn.functional as F
from paddle.nn import LayerList
from paddle.nn.initializer import XavierNormal as xavier_uniform_
from paddle.nn import Dropout, Linear, LayerNorm, Conv2D
import numpy as np
from ppocr.modeling.heads.multiheadAttention import M... | null |
151,204 | import cv2
import paddle
import numpy as np
from numpy.fft import ifft
from ppocr.utils.poly_nms import poly_nms, valid_boundary
def fill_hole(input_mask):
h, w = input_mask.shape
canvas = np.zeros((h + 2, w + 2), np.uint8)
canvas[1:h + 1, 1:w + 1] = input_mask.copy()
mask = np.zeros((h + 4, w + 4), n... | null |
151,211 | import paddle
def iou_single(a, b, mask, n_class):
valid = mask == 1
a = a.masked_select(valid)
b = b.masked_select(valid)
miou = []
for i in range(n_class):
if a.shape == [0] and a.shape == b.shape:
inter = paddle.to_tensor(0.0)
union = paddle.to_tensor(0.0)
... | null |
151,213 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
The provided code snippet includes necessary dependencies for implementing the `print_dict` function. Write a Python function `def print_dict(d, logger, delimiter=0)` to solve the following problem:
Recursively visualize a... | Recursively visualize a dict and indenting acrrording by the relationship of keys. |
151,214 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
def get_check_global_params(mode):
check_params = ['use_gpu', 'max_text_length', 'image_shape', \
'image_shape', 'character_type', 'loss_type']
if mode == "train_eval":
check_params = ch... | null |
151,215 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
def _check_image_file(path):
img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif'}
return any([path.lower().endswith(e) for e in img_end])
def get_image_file_list(img_file):
imgs_lists = []
i... | null |
151,216 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
import logging
def check_and_read_gif(img_path):
if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:
gif = cv2.VideoCapture(img_path)
ret, frame = gif.read()
if not ret:
logger = ... | null |
151,217 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
def load_vqa_bio_label_maps(label_map_path):
with open(label_map_path, "r", encoding='utf-8') as fin:
lines = fin.readlines()
lines = [line.strip() for line in lines]
if "O" not in lines:
lines.... | null |
151,218 | import logging
import os
import imghdr
import cv2
import random
import numpy as np
import paddle
def set_seed(seed=1024):
random.seed(seed)
np.random.seed(seed)
paddle.seed(seed) | null |
151,219 | import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def draw_box_txt(bbox, text, draw, font, font_size, color):
# draw ocr results outline
bbox = ((bbox[0], bbox[1]), (bbox[2], bbox[3]))
draw.rectangle(bbox, fill=color)
# draw ocr results
start_y = max(0, bbox[0][1] - font_size)... | null |
151,220 | import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def draw_box_txt(bbox, text, draw, font, font_size, color):
def draw_re_results(image,
result,
font_path="doc/fonts/simfang.ttf",
font_size=18):
np.random.seed(0)
if isinstance(i... | null |
151,221 | import os
import sys
import tarfile
import requests
from tqdm import tqdm
from ppocr.utils.logging import get_logger
def download_with_progressbar(url, save_path):
logger = get_logger()
response = requests.get(url, stream=True)
if response.status_code == 200:
total_size_in_bytes = int(response.heade... | null |
151,223 | import numpy as np
import scipy.io as io
from ppocr.utils.e2e_metric.polygon_fast import iod, area_of_intersection, area
def area(x, y):
def area_of_intersection(det_x, det_y, gt_x, gt_y):
def iod(det_x, det_y, gt_x, gt_y):
def get_socre_A(gt_dir, pred_dict):
allInputs = 1
def input_reading_mod(pre... | null |
151,224 | import numpy as np
import scipy.io as io
from ppocr.utils.e2e_metric.polygon_fast import iod, area_of_intersection, area
def area(x, y):
polygon = Polygon(np.stack([x, y], axis=1))
return float(polygon.area)
def area_of_intersection(det_x, det_y, gt_x, gt_y):
p1 = Polygon(np.stack([det_x, det_y], axis=... | null |
151,225 | import numpy as np
import scipy.io as io
from ppocr.utils.e2e_metric.polygon_fast import iod, area_of_intersection, area
def combine_results(all_data):
tr = 0.7
tp = 0.6
fsc_k = 0.8
k = 2
global_sigma = []
global_tau = []
global_pred_str = []
global_gt_str = []
for data in all_data:... | null |
151,240 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import math
import numpy as np
from itertools import groupby
from skimage.morphology._skeletonize import thin
def point_pair2poly(point_pair_list):
def expand_poly_along_width(poly, shrink_ratio_of_wi... | null |
151,241 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import math
import numpy as np
from itertools import groupby
from skimage.morphology._skeletonize import thin
def ctc_decoder_for_image(gather_info_list,
logits_map,
... | return center point and end point of TCL instance; filter with the char maps; |
151,255 | import sys
import paddle
_profiler_step_id = 0
_profiler_options = None
class ProfilerOptions(object):
'''
Use a string to initialize a ProfilerOptions.
The string should be in the format: "key1=value1;key2=value;key3=value3".
For example:
"profile_path=model.profile"
"batch_range=[50, 60]; ... | Enable the operator-level timing using PaddlePaddle's profiler. The profiler uses a independent variable to count the profiler steps. One call of this function is treated as a profiler step. Args: profiler_options - a string to initialize the ProfilerOptions. Default is None, and the profiler is disabled. |
151,256 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import errno
import os
import pickle
import six
import paddle
from ppocr.utils.logging import get_logger
def load_pretrained_params(model, path):
logger = get_logger()
if path.endswith('.pdparams'):
... | load model from checkpoint or pretrained_model |
151,257 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import errno
import os
import pickle
import six
import paddle
from ppocr.utils.logging import get_logger
def _mkdir_if_not_exist(path, logger):
"""
mkdir if not exists, ignore the exception when multipro... | save model to the target path |
151,259 | import argparse
import os
import sys
import platform
import cv2
import numpy as np
import paddle
from PIL import Image, ImageDraw, ImageFont
import math
from paddle import inference
import time
from ppocr.utils.logging import get_logger
def init_args():
parser = argparse.ArgumentParser()
# params for prediction... | null |
151,260 | import argparse
import os
import sys
import platform
import cv2
import numpy as np
import paddle
from PIL import Image, ImageDraw, ImageFont
import math
from paddle import inference
import time
from ppocr.utils.logging import get_logger
def get_output_tensors(args, mode, predictor):
output_names = predictor.get_out... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.