id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
143,789 | import numpy as np
import cv2
def normalize(data):
return np.float32(data/255.) | null |
143,790 | import numpy as np
import cv2
The provided code snippet includes necessary dependencies for implementing the `remove_dataparallel_wrapper` function. Write a Python function `def remove_dataparallel_wrapper(state_dict)` to solve the following problem:
r"""Converts a DataParallel model to a normal one by removing the "m... | r"""Converts a DataParallel model to a normal one by removing the "module." wrapper in the module dictionary Args: state_dict: a torch.nn.DataParallel state dictionary |
143,791 | import numpy as np
import cv2
The provided code snippet includes necessary dependencies for implementing the `is_rgb` function. Write a Python function `def is_rgb(im_path)` to solve the following problem:
r""" Returns True if the image in im_path is an RGB image
Here is the function:
def is_rgb(im_path):
r""" R... | r""" Returns True if the image in im_path is an RGB image |
143,792 | import torch
from torch.autograd import Function, Variable
The provided code snippet includes necessary dependencies for implementing the `concatenate_input_noise_map` function. Write a Python function `def concatenate_input_noise_map(input, noise_sigma)` to solve the following problem:
r"""Implements the first layer ... | r"""Implements the first layer of FFDNet. This function returns a torch.autograd.Variable composed of the concatenation of the downsampled input image and the noise map. Each image of the batch of size CxHxW gets converted to an array of size 4*CxH/2xW/2. Each of the pixels of the non-overlapped 2x2 patches of the inpu... |
143,793 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as M
import math
from torch import Tensor
from torch.nn import Parameter
from .extractor import SEResNeXt_Origin, BottleneckX_Origin
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps) | null |
143,794 | import numpy as np
import cv2
def resize_pad(img, size = 256):
if len(img.shape) == 2:
img = np.expand_dims(img, 2)
if img.shape[2] == 1:
img = np.repeat(img, 3, 2)
if img.shape[2] == 4:
img = img[:, :, :3]
pad = None
if (... | null |
143,795 | import torch
import numpy as np
import cv2
import os
import einops
import safetensors
import safetensors.torch
from PIL import Image
from omegaconf import OmegaConf
from .common import OfflineInpainter
from ..utils import resize_keep_aspect
from .booru_tagger import Tagger
from .sd_hack import hack_everything
from .ldm... | null |
143,796 | import torch
import numpy as np
import cv2
import os
import einops
import safetensors
import safetensors.torch
from PIL import Image
from omegaconf import OmegaConf
from .common import OfflineInpainter
from ..utils import resize_keep_aspect
from .booru_tagger import Tagger
from .sd_hack import hack_everything
from .ldm... | null |
143,797 | from typing import List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def relu_nf(x):
return F.relu(x) * 1.7139588594436646 | null |
143,798 | from typing import List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def gelu_nf(x):
return F.gelu(x) * 1.7015043497085571 | null |
143,799 | from typing import List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def silu_nf(x):
return F.silu(x) * 1.7881293296813965 | null |
143,800 | import torch
import einops
from transformers import logging
from . import ldm
from .ldm.modules.attention import default
def _hacked_sliced_attentin_forward(self, x, context=None, mask=None):
h = self.heads
q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
... | null |
143,801 | import torch
import einops
from transformers import logging
from . import ldm
from .ldm.modules.attention import default
def disable_verbosity():
logging.set_verbosity_error()
return
def _hacked_clip_forward(self, text):
PAD = self.tokenizer.pad_token_id
EOS = self.tokenizer.eos_token_id
BOS = self.... | null |
143,802 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import cv2
import os
import shutil
from torch import Tensor
from .common import OfflineInpainter
from ..utils import resize_keep_aspect
def set_requires_grad(module, value):
for param in module.parameters():
param.require... | null |
143,803 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import cv2
import os
import shutil
from torch import Tensor
from .common import OfflineInpainter
from ..utils import resize_keep_aspect
def get_activation(kind='tanh'):
if kind == 'tanh':
return nn.Tanh()
if kind == '... | null |
143,804 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import cv2
import os
import shutil
from torch import Tensor
from .common import OfflineInpainter
from ..utils import resize_keep_aspect
class LamaFourier:
def __init__(self, build_discriminator=True, use_mpe=False, large_arch: boo... | null |
143,805 | import os
import gc
import pandas as pd
import numpy as np
from onnxruntime import InferenceSession
from typing import Tuple, List, Dict
from io import BytesIO
from PIL import Image
import cv2
from pathlib import Path
from tqdm import tqdm
def make_square(img, target_size):
old_size = img.shape[:2]
desired_siz... | null |
143,806 | import os
import gc
import pandas as pd
import numpy as np
from onnxruntime import InferenceSession
from typing import Tuple, List, Dict
from io import BytesIO
from PIL import Image
import cv2
from pathlib import Path
from tqdm import tqdm
def smart_resize(img, size):
# Assumes the image has already gone through m... | null |
143,807 | from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import abc
import random
from kornia.geometry.transform import rotate
from .inpainting_lama_mpe import LamaMPEInpainter
class DepthWiseSeparableConv(nn.Module):
def __init__(self, in_dim, out_dim, *a... | null |
143,808 | from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import abc
import random
from kornia.geometry.transform import rotate
from .inpainting_lama_mpe import LamaMPEInpainter
from torchsummary import summary
def get_norm_layer(kind='bn'):
if not isinsta... | null |
143,809 | from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import abc
import random
from kornia.geometry.transform import rotate
from .inpainting_lama_mpe import LamaMPEInpainter
from torchsummary import summary
def get_activation(kind='tanh'):
if kind == '... | null |
143,810 | from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import abc
import random
from kornia.geometry.transform import rotate
from .inpainting_lama_mpe import LamaMPEInpainter
class FFCNLayerDiscriminator(BaseDiscriminator):
def __init__(self, input_nc, n... | null |
143,811 | from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import abc
import random
from kornia.geometry.transform import rotate
from .inpainting_lama_mpe import LamaMPEInpainter
def get_generator(n_blocks: int = 9):
init_conv_kwargs = {
'ratio_gin':... | null |
143,812 | from typing import List, Optional
import numpy as np
import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
from .inpainting_lama_mpe import LamaMPEInpainter
from torch.nn.utils import spectral_norm
def relu_nf(x):
return F.relu(x) * 1.7139588594436646 | null |
143,813 | from typing import List, Optional
import numpy as np
import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
from .inpainting_lama_mpe import LamaMPEInpainter
from torch.nn.utils import spectral_norm
def gelu_nf(x):
return F.gelu(x) * 1.7015043497085571 | null |
143,814 | from typing import List, Optional
import numpy as np
import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
from .inpainting_lama_mpe import LamaMPEInpainter
from torch.nn.utils import spectral_norm
def silu_nf(x):
return F.silu(x) * 1.7881293296813965 | null |
143,815 | from typing import List, Optional
import numpy as np
import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
from .inpainting_lama_mpe import LamaMPEInpainter
from torch.nn.utils import spectral_norm
def my_layer_norm(feat):
mean = feat.mean((2, 3), keepdim=True)
std = feat.s... | null |
143,821 | import os
import math
import torch
import torch.nn as nn
import numpy as np
from einops import repeat
from ...util import instantiate_from_config
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list... | Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly... |
143,834 | import math
import torch
import torch.nn as nn
import numpy as np
from einops import rearrange
from typing import Optional, Any
from ldm.modules.attention import MemoryEfficientCrossAttention
class AttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.in_channels = in_channe... | null |
143,835 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from ..attention import SpatialTransformer
fr... | null |
143,836 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from ..attention import SpatialTransformer
fr... | null |
143,837 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from ..attention import SpatialTransformer
fr... | A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) |
143,838 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from .diffusionmodules.util import checkpoint
import os
def uniq(arr):
return{el: True for el in arr}.keys() | null |
143,839 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from .diffusionmodules.util import checkpoint
import os
def max_neg_value(t):
return -torch.finfo(t.dtype).max | null |
143,840 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from .diffusionmodules.util import checkpoint
import os
def init_(tensor):
dim = tensor.shape[-1]
std = 1 / math.sqrt(dim)
... | null |
143,841 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from .diffusionmodules.util import checkpoint
import os
The provided code snippet includes necessary dependencies for implementing t... | Zero out the parameters of a module and return it. |
143,842 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from .diffusionmodules.util import checkpoint
import os
def Normalize(in_channels):
return torch.nn.GroupNorm(num_groups=32, num... | null |
143,845 | import numpy as np
import cv2
import torch
from functools import partial
import random
from scipy import ndimage
import scipy
import scipy.stats as ss
from scipy.interpolate import interp2d
from scipy.linalg import orth
import albumentations
import ldm.modules.image_degradation.utils_image as util
The provided code sn... | # modified version of https://github.com/assafshocher/BlindSR_dataset_generator # Kai Zhang # min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var # max_var = 2.5 * sf |
143,857 | import os
import math
import random
import numpy as np
import torch
import cv2
from torchvision.utils import make_grid
from datetime import datetime
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def get_image_paths(dataroot):
paths = None # return None if dataroot is None
if dataroot is not None:
paths = s... | split the large images from original_dataroot into small overlapped images with size (p_size)x(p_size), and save them into target_dataroot; only the images with larger size than (p_max)x(p_max) will be split. Args: original_dataroot: target_dataroot: p_size: size of small images p_overlap: patch size in training is a g... |
143,897 | import cv2
import torch
import torch.nn as nn
from torchvision.transforms import Compose
from ldm.modules.midas.midas.dpt_depth import DPTDepthModel
from ldm.modules.midas.midas.midas_net import MidasNet
from ldm.modules.midas.midas.midas_net_custom import MidasNet_small
from ldm.modules.midas.midas.transforms import R... | null |
143,913 | import importlib
import torch
from torch import optim
import numpy as np
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
# xc a list of captions to plot
b = len(xc)
txts = list()
for bi in range(b):
... | null |
143,923 | import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager, nullcontext
from functools import partial
import itertools
from tqdm import tqdm
from torchvision.utils import ma... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
143,924 | import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager, nullcontext
from functools import partial
import itertools
from tqdm import tqdm
from torchvision.utils import ma... | null |
143,925 | import einops
import torch
import torch as th
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import cv2
from .ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from .ldm.modules.diffusionmodules.util import noise_like
from einops import rearra... | null |
143,926 | import einops
import torch
import torch as th
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import cv2
from .ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from .ldm.modules.diffusionmodules.util import noise_like
from einops import rearra... | null |
143,927 | import einops
import torch
import torch as th
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import cv2
from .ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from .ldm.modules.diffusionmodules.util import noise_like
from einops import rearra... | fills masked regions with colors from image using blur. Not extremely effective. |
143,928 | import einops
import torch
import torch as th
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import cv2
from .ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from .ldm.modules.diffusionmodules.util import noise_like
from einops import rearra... | null |
143,929 | import einops
import torch
import torch as th
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import cv2
from .ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from .ldm.modules.diffusionmodules.util import noise_like
from einops import rearra... | null |
143,930 | import os
import re
import cv2
import numpy as np
import freetype
import functools
from pathlib import Path
from typing import Tuple, Optional, List
from hyphen import Hyphenator
from hyphen.dictools import LANGUAGES as HYPHENATOR_LANGUAGES
from langcodes import standardize_tag
from ..utils import BASE_PATH, is_punctua... | null |
143,931 | import os
import re
import cv2
import numpy as np
import freetype
import functools
from pathlib import Path
from typing import Tuple, Optional, List
from hyphen import Hyphenator
from hyphen.dictools import LANGUAGES as HYPHENATOR_LANGUAGES
from langcodes import standardize_tag
from ..utils import BASE_PATH, is_punctua... | null |
143,932 | import os
import re
import cv2
import numpy as np
import freetype
import functools
from pathlib import Path
from typing import Tuple, Optional, List
from hyphen import Hyphenator
from hyphen.dictools import LANGUAGES as HYPHENATOR_LANGUAGES
from langcodes import standardize_tag
from ..utils import BASE_PATH, is_punctua... | null |
143,933 | import os
import re
import cv2
import numpy as np
import freetype
import functools
from pathlib import Path
from typing import Tuple, Optional, List
from hyphen import Hyphenator
from hyphen.dictools import LANGUAGES as HYPHENATOR_LANGUAGES
from langcodes import standardize_tag
from ..utils import BASE_PATH, is_punctua... | null |
143,934 | import tempfile
import subprocess
import math
import cv2
import platform
import glob
import os
from ..utils import Context
alignment_to_justification = {
"left": "TEXT-JUSTIFY-LEFT",
"right": "TEXT-JUSTIFY-RIGHT",
"center": "TEXT-JUSTIFY-CENTER",
}
direction_to_base_direction = {
"h": "TEXT-DIRECTION-LT... | null |
143,935 | import cv2
import numpy as np
from PIL import Image
from typing import List, Tuple
from .text_render import get_char_glyph, put_char_horizontal, add_color
from .ballon_extractor import extract_ballon_region
from ..utils import TextBlock, rect_distance
def render_lines(
textlines: List[Textline],
canvas_h: int,
... | r""" Args: downscale_constraint (float, optional): minimum scaling down ratio, prevent rendered text from being too small ref_textballon (bool, optional): take text balloons as reference for text layout. original_img (np.ndarray, optional): original image used to extract text balloons. |
143,936 | import numpy as np
from skimage import io
import cv2
def loadImage(img_file):
img = io.imread(img_file) # RGB order
if img.shape[0] == 2: img = img[0]
if len(img.shape) == 2 : img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
if img.shape[2] == 4: img = img[:,:,:3]
img = np.array(img)
re... | null |
143,937 | import numpy as np
from skimage import io
import cv2
def normalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)):
# should be RGB order
img = in_img.copy().astype(np.float32)
img -= np.array([mean[0] * 255.0, mean[1] * 255.0, mean[2] * 255.0], dtype=np.float32)
img /=... | null |
143,939 | import numpy as np
from skimage import io
import cv2
def resize_aspect_ratio(img, square_size, interpolation, mag_ratio=1):
height, width, channel = img.shape
# magnify image size
target_size = mag_ratio * square_size#max(height, width)
# set original image size
# if target_size > square_size:
... | null |
143,941 | import numpy as np
import cv2
import math
def getDetBoxes_core(textmap, linkmap, text_threshold, link_threshold, low_text):
# prepare data
linkmap = linkmap.copy()
textmap = textmap.copy()
img_h, img_w = textmap.shape
""" labeling method """
ret, text_score = cv2.threshold(textmap, low_text, 1, ... | null |
143,942 | import numpy as np
import cv2
import math
def adjustResultCoordinates(polys, ratio_w, ratio_h, ratio_net = 2):
if len(polys) > 0:
polys = np.array(polys)
for k in range(len(polys)):
if polys[k] is not None:
polys[k] *= (ratio_w * ratio_net, ratio_h * ratio_net)
retur... | null |
143,943 | import os
import shutil
import numpy as np
import einops
from typing import Union, Tuple
import cv2
import torch
from .ctd_utils.basemodel import TextDetBase, TextDetBaseDNN
from .ctd_utils.utils.yolov5_utils import non_max_suppression
from .ctd_utils.utils.db_utils import SegDetectorRepresenter
from .ctd_utils.utils.i... | null |
143,944 | import os
import shutil
import numpy as np
import einops
from typing import Union, Tuple
import cv2
import torch
from .ctd_utils.basemodel import TextDetBase, TextDetBaseDNN
from .ctd_utils.utils.yolov5_utils import non_max_suppression
from .ctd_utils.utils.db_utils import SegDetectorRepresenter
from .ctd_utils.utils.i... | null |
143,945 | import os
import shutil
import numpy as np
import einops
from typing import Union, Tuple
import cv2
import torch
from .ctd_utils.basemodel import TextDetBase, TextDetBaseDNN
from .ctd_utils.utils.yolov5_utils import non_max_suppression
from .ctd_utils.utils.db_utils import SegDetectorRepresenter
from .ctd_utils.utils.i... | null |
143,946 | from typing import List
import cv2
import numpy as np
from .utils.imgproc_utils import union_area, enlarge_window
from ...utils import TextBlock, Quadrilateral
REFINEMASK_INPAINT = 0
def refine_mask(img: np.ndarray, pred_mask: np.ndarray, blk_list: List[Quadrilateral], refine_mode: int = REFINEMASK_INPAINT) -> np.ndarr... | null |
143,947 | from operator import mod
from cv2 import imshow
from copy import deepcopy
from .common import *
class Detect(nn.Module):
def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
def forward(self, x):
def _make_grid(self, nx=20, ny=20, i=0):
class Conv(nn.Module):
def __init__(self, c1, c2, k=1, ... | null |
143,948 | from operator import mod
from cv2 import imshow
from copy import deepcopy
from .common import *
class Detect(nn.Module):
stride = None # strides computed during build
onnx_dynamic = False # ONNX export parameter
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super()... | null |
143,949 | import json
import math
import platform
import warnings
from collections import OrderedDict, namedtuple
from copy import copy
from pathlib import Path
import cv2
import numpy as np
import requests
import torch
import torch.nn as nn
from PIL import Image
from torch.cuda import amp
from ..utils.yolov5_utils import make_d... | null |
143,950 | import cv2
import copy
import torch
import torch.nn as nn
from .utils.yolov5_utils import fuse_conv_and_bn
from .utils.weight_init import init_weights
from .yolov5.yolo import load_yolov5_ckpt
from .yolov5.common import C3, Conv
class UnetHead(nn.Module):
def __init__(self, act=True) -> None:
super(UnetHead... | null |
143,951 | import os
import os.path as osp
import glob
from pathlib import Path
import cv2
import numpy as np
import json
IMG_EXT = ['.bmp', '.jpg', '.png', '.jpeg']
def find_all_imgs(img_dir, abs_path=False):
imglist = list()
for filep in glob.glob(osp.join(img_dir, "*")):
filename = osp.basename(filep)
... | null |
143,952 | import os
import os.path as osp
import glob
from pathlib import Path
import cv2
import numpy as np
import json
def imread(imgpath, read_type=cv2.IMREAD_COLOR):
# img = cv2.imread(imgpath, read_type)
# if img is None:
img = cv2.imdecode(np.fromfile(imgpath, dtype=np.uint8), read_type)
return img | null |
143,953 | import os
import os.path as osp
import glob
from pathlib import Path
import cv2
import numpy as np
import json
def imwrite(img_path, img, ext='.png'):
suffix = Path(img_path).suffix
if suffix != '':
img_path = img_path.replace(suffix, ext)
else:
img_path += ext
cv2.imencode(ext, img)[1]... | null |
143,954 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
# scales img(bs,3,y,x) by ratio constrained to gs-multiple
if ratio == 1.0:
return img... | null |
143,955 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def fuse_conv_and_bn(conv, bn):
# Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
fusedconv = nn.Conv2d(conv.in_channels,
... | null |
143,956 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def check_anchor_order(m):
# Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
a = m.anchors.prod(-1).view(-1) # anchor area
... | null |
143,957 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def initialize_weights(model):
for m in model.modules():
t = type(m)
if t is nn.Conv2d:
pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', n... | null |
143,958 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def make_divisible(x, divisor):
# Returns nearest x divisible by divisor
if isinstance(divisor, torch.Tensor):
divisor = int(divisor.max()) # to int
return ma... | null |
143,959 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def intersect_dicts(da, db, exclude=()):
# Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
return {k: v for k, v in da.items(... | null |
143,960 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False):
# Check version vs. required version
from packaging import version
curr... | null |
143,961 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import time
import torchvision
class Colors:
# Ultralytics color palette https://ultralytics.com/
def __init__(self):
# hex = matplotlib.colors.TABLEAU_COLORS.values()
hex = ('FF3838', 'F... | null |
143,962 | import numpy as np
import cv2
import random
from typing import List
def hex2bgr(hex):
gmask = 254 << 8
rmask = 254
b = hex >> 16
g = (hex & gmask) >> 8
r = hex & rmask
return np.stack([b, g, r]).transpose() | null |
143,963 | import numpy as np
import cv2
import random
from typing import List
def get_yololabel_strings(clslist, labellist):
content = ''
for cls, xywh in zip(clslist, labellist):
content += str(int(cls)) + ' ' + ' '.join([str(e) for e in xywh]) + '\n'
if len(content) != 0:
content = content[:-1]
... | null |
143,964 | import numpy as np
import cv2
import random
from typing import List
def xywh2xyxypoly(xywh, to_int=True):
xyxypoly = np.tile(xywh[:, [0, 1]], 4)
xyxypoly[:, [2, 4]] += xywh[:, [2]]
xyxypoly[:, [5, 7]] += xywh[:, [3]]
if to_int:
xyxypoly = xyxypoly.astype(np.int64)
return xyxypoly | null |
143,965 | import numpy as np
import cv2
import random
from typing import List
def xyxy2yolo(xyxy, w: int, h: int):
if xyxy == [] or xyxy == np.array([]) or len(xyxy) == 0:
return None
if isinstance(xyxy, list):
xyxy = np.array(xyxy)
if len(xyxy.shape) == 1:
xyxy = np.array([xyxy])
yolo = ... | null |
143,966 | import numpy as np
import cv2
import random
from typing import List
def yolo_xywh2xyxy(xywh: np.array, w: int, h: int, to_int=True):
if xywh is None:
return None
if len(xywh) == 0:
return None
if len(xywh.shape) == 1:
xywh = np.array([xywh])
xywh[:, [0, 2]] *= w
xywh[:, [1,... | null |
143,967 | import numpy as np
import cv2
import random
from typing import List
def resize_keepasp(im, new_shape=640, scaleup=True, interpolation=cv2.INTER_LINEAR, stride=None):
shape = im.shape[:2] # current shape [height, width]
if new_shape is not None:
if not isinstance(new_shape, tuple):
new_sha... | null |
143,968 | import numpy as np
import cv2
import random
from typing import List
def draw_connected_labels(num_labels, labels, stats, centroids, names="draw_connected_labels", skip_background=True):
labdraw = np.zeros((labels.shape[0], labels.shape[1], 3), dtype=np.uint8)
max_ind = 0
if isinstance(num_labels, int):
... | null |
143,969 | import cv2
import numpy as np
import pyclipper
from shapely.geometry import Polygon
from collections import namedtuple
import warnings
import torch
def iou_rotate(box_a, box_b, method='union'):
rect_a = cv2.minAreaRect(box_a)
rect_b = cv2.minAreaRect(box_b)
r1 = cv2.rotatedRectangleIntersection(rect_a, rec... | null |
143,970 | import cv2
import numpy as np
import pyclipper
from shapely.geometry import Polygon
from collections import namedtuple
import warnings
import torch
The provided code snippet includes necessary dependencies for implementing the `shrink_polygon_py` function. Write a Python function `def shrink_polygon_py(polygon, shrink... | 对框进行缩放,返回去的比例为1/shrink_ratio 即可 |
143,971 | import cv2
import numpy as np
import pyclipper
from shapely.geometry import Polygon
from collections import namedtuple
import warnings
import torch
def shrink_polygon_pyclipper(polygon, shrink_ratio):
from shapely.geometry import Polygon
import pyclipper
polygon_shape = Polygon(polygon)
distance = poly... | null |
143,972 | import torch.nn as nn
import torch
def normal_init(module, mean=0, std=1, bias=0):
nn.init.normal_(module.weight, mean, std)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias) | null |
143,973 | import torch.nn as nn
import torch
def uniform_init(module, a=0, b=1, bias=0):
nn.init.uniform_(module.weight, a, b)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias) | null |
143,974 | import torch.nn as nn
import torch
def bilinear_kernel(in_channels, out_channels, kernel_size):
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = (torch.arange(kernel_size).reshape(-1, 1),
torch.arange(kernel_size).re... | null |
143,975 | import torch.nn as nn
import torch
def constant_init(module, val, bias=0):
nn.init.constant_(module.weight, val)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias)
def xavier_init(module, gain=1, bias=0, distribution='normal'):
assert distribution in ['unifo... | null |
143,976 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import shutil
import numpy as np
import torch
import cv2
import einops
from typing import List, Tuple
from .default_utils.DBNet_resnet34 import TextDetection as TextDetectionDefault
from .default_utils import imgproc, dbnet_... | null |
143,977 | from functools import partial
import shutil
from typing import Callable, Optional, Tuple, Union
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torchvision.models import resnet34
import einops
import math
from timm.layers import trunc_no... | null |
143,978 | from functools import partial
import shutil
from typing import Callable, Optional, Tuple, Union
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torchvision.models import resnet34
import einops
import math
from timm.layers import trunc_no... | null |
143,979 | import os
import shutil
import numpy as np
import torch
import cv2
import einops
from typing import List, Tuple
from .default_utils.DBNet_resnet34 import TextDetection as TextDetectionDefault
from .default_utils import imgproc, dbnet_utils, craft_utils
from .common import OfflineDetector
from ..utils import TextBlock, ... | null |
143,980 | from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.init as init
from torchvision import models
def init_weights(modules):
for m in modules:
if isinstance(m, nn.Conv2d):
init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bi... | null |
143,981 | import os
import re
import subprocess
import tempfile
import shutil
import einops
import tqdm
from sys import platform
from typing import List
from PIL import Image
from collections import OrderedDict
import math
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from... | null |
143,982 | import os
import re
import subprocess
import tempfile
import shutil
import einops
import tqdm
from sys import platform
from typing import List
from PIL import Image
from collections import OrderedDict
import math
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from... | Pixel unshuffle. Args: x (Tensor): Input feature with shape (b, c, hh, hw). scale (int): Downsample ratio. Returns: Tensor: the pixel unshuffled feature. |
143,983 | import os
import re
import subprocess
import tempfile
import shutil
import einops
import tqdm
from sys import platform
from typing import List
from PIL import Image
from collections import OrderedDict
import math
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from... | Pixel shuffle layer (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network, CVPR17) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.