id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
31,337
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _enhance_level_to_arg(level, _hparams): # range [0.1, 1.9] return (level / _MAX_LEVEL) * 1.8 + 0.1,
null
31,338
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _enhance_increasing_level_to_arg(level, _hparams): # the ...
null
31,339
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _shear_level_to_arg(level, _hparams): # range [-0.3, 0.3]...
null
31,340
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _translate_abs_level_to_arg(level, hparams): translate_co...
null
31,341
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _translate_rel_level_to_arg(level, hparams): # default ra...
null
31,342
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _posterize_level_to_arg(level, _hparams): # As per Tensorflow TPU EfficientNet impl # range [0, 4], 'keep 0 up to 4 MSB of original image' # intensity/severity of augmentation decr...
null
31,343
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _posterize_original_level_to_arg(level, _hparams): # As per original AutoAugment paper description # range [4, 8], 'keep 4 up to 8 MSB of image' # intensity/sever...
null
31,344
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _solarize_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 256), def _solarize_increasin...
null
31,345
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _solarize_add_level_to_arg(level, _hparams): # range [0, 110] return int((level / _MAX_LEVEL) * 110),
null
31,346
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def auto_augment_policy(name='v0', hparams=None): hparams = hparams or _HPARAMS_DEFAULT if name == 'original': return auto_augment_policy_original(hparams) elif name == 'origin...
Create a AutoAugment transform :param config_str: String defining configuration of auto augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the AutoAugment policy (one of 'v0', 'v0r', 'original', 'originalr'). The remaining sections, not order sepecific determine 'mstd' - fl...
31,347
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. _RAND_TRANSFORMS = [ 'AutoContrast', 'Equalize', 'Invert', 'Rotate', 'Posterize', 'Solarize', 'SolarizeAdd', 'Color', 'Contrast', 'Brightne...
Create a RandAugment transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining sections, not order sepecific determine 'm' - integer mag...
31,348
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def augmix_ops(magnitude=10, hparams=None, transforms=None): hparams = hparams or _HPARAMS_DEFAULT transforms = transforms or _AUGMIX_TRANSFORMS return [AugmentOp( name, prob=1...
Create AugMix PyTorch transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining sections, not order sepecific determine 'm' - integer ma...
31,349
import os import contextlib import copy import numpy as np import paddle from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def convert_to_xywh(boxes): xmin, ymin, xmax, ymax = boxes.unbind(1) return paddle.stack((xmin, ...
null
31,350
import os import contextlib import copy import numpy as np import paddle from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def merge(img_ids, eval_imgs): def create_common_coco_eval(coco_eval, img_ids, eval_imgs): img_ids, ...
null
31,351
import os import contextlib import copy import numpy as np import paddle from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather The provided code snippet includes necessary dependencies for implementing the `evaluate` function. Writ...
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
31,352
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy The provided code snippet includes necessary d...
crop image and target with region Args: image: np.array target: label dict contains labels, boxes, or masks fields, see coco.py for details regtion: list, crop region [top, left, height, width] Returns: cropped_image: cropped image target: corresponding targets
31,353
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy The provided code snippet includes necessary d...
horizontal flip image and corresponding labels
31,354
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def resize(image, target, size, max_size=None)...
null
31,355
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def pad(image, target, padding): padded_im...
null
31,356
import copy import pickle import numpy as np import paddle import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler The provided code snippet includes necessary dependencies for implementing the `reduce_dict` function. Write a Python function `def reduce_dict(input_dict, average=True)` to solve th...
Impl all_reduce for dict of tensors in DDP
31,357
import copy import pickle import numpy as np import paddle import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def accuracy(output, target, topk=(1,)): if target.numel() == 0: return [paddle.zeros([])] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk...
null
31,358
import copy import pickle import numpy as np import paddle import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler The provided code snippet includes necessary dependencies for implementing the `all_gather` function. Write a Python function `def all_gather(data)` to solve the following problem: r...
run all_gather on any picklable data (do not requires tensors) Args: data: picklable object Returns: data_list: list of data gathered from each rank
31,359
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils def print_model_named_params(model): for name, param in model.named_par...
null
31,360
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils def print_model_named_buffers(model): for name, buff in model.named_buf...
null
31,361
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils def torch_to_paddle_mapping(): map1 = torch_to_paddle_mapping_backbone()...
null
31,362
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils class NestedTensor(): """Each NestedTensor has .tensor and .mask attrib...
null
31,363
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils class NestedTensor(): """Each NestedTensor has .tensor and .mask attrib...
null
31,366
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils def torch_to_paddle_mapping(): def convert(torch_model, paddle_model): ...
null
31,367
import sys from misc import NestedTensor as ThNestedTensor import os import argparse import numpy as np import paddle import torch from detr import build_detr from utils import NestedTensor from config import get_config import misc as th_utils class NestedTensor(): def __init__(self, tensors, mask): def deco...
null
31,369
from scipy.optimize import linear_sum_assignment from scipy.spatial import distance import paddle import paddle.nn as nn import paddle.nn.functional as F from box_ops import box_cxcywh_to_xyxy from box_ops import generalized_box_iou def cdist_p1(x, y): # x: [batch * num_queries, 4] # y: [batch * num_boxes, 4] ...
null
31,370
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddle.distributed as dist from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from utils import Avera...
return arguments, this will overwrite the config after loading yaml file
31,371
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddle.distributed as dist from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from utils import Avera...
null
31,372
import os import numpy as np from PIL import Image import paddle from pycocotools.coco import COCO from pycocotools import mask as coco_mask import transforms as T from utils import collate_fn The provided code snippet includes necessary dependencies for implementing the `convert_coco_poly_to_mask` function. Write a P...
Convert coco anno from polygons to image masks
31,373
import os import numpy as np from PIL import Image import paddle from pycocotools.coco import COCO from pycocotools import mask as coco_mask import transforms as T from utils import collate_fn class CocoDetection(paddle.io.Dataset): """ COCO Detection dataset This class gets images and annotations for paddle tr...
Return CocoDetection dataset according to image_set: ['train', 'val']
31,374
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `box_xyxy_to_cxcywh_numpy` function. Write a Python function `def box_xyxy_to_cxcywh_numpy(box)` to solve the following problem: convert box from top-left/bottom-right format: [x0, y0, x1, y1] to center-size...
convert box from top-left/bottom-right format: [x0, y0, x1, y1] to center-size format: [center_x, center_y, width, height] Args: box: numpy array, last_dim=4, stop-left/bottom-right format boxes Return: numpy array, last_dim=4, center-size format boxes
31,375
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `box_cxcywh_to_xyxy` function. Write a Python function `def box_cxcywh_to_xyxy(box)` to solve the following problem: convert box from center-size format: [center_x, center_y, width, height] to top-left/botto...
convert box from center-size format: [center_x, center_y, width, height] to top-left/bottom-right format: [x0, y0, x1, y1] Args: box: paddle.Tensor, last_dim=4, stores center-size format boxes Return: paddle.Tensor, last_dim=4, top-left/bottom-right format boxes
31,376
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `box_xyxy_to_cxcywh` function. Write a Python function `def box_xyxy_to_cxcywh(box)` to solve the following problem: convert box from top-left/bottom-right format: [x0, y0, x1, y1] to center-size format: [ce...
convert box from top-left/bottom-right format: [x0, y0, x1, y1] to center-size format: [center_x, center_y, width, height] Args: box: paddle.Tensor, last_dim=4, stop-left/bottom-right format boxes Return: paddle.Tensor, last_dim=4, center-size format boxes
31,377
import numpy as np import paddle def box_iou(boxes1, boxes2): """compute iou of 2 sets of boxes in (x1, y1, x2, y2) format This method returns the iou between every pair of boxes in two sets of boxes. Args: boxes1: paddle.Tensor, shape=N x 4, boxes are stored in (x1, y1, x2, y2) format ...
Compute GIoU of each pais in boxes1 and boxes2 GIoU = IoU - |A_c - U| / |A_c| where A_c is the smallest convex hull that encloses both boxes, U is the union of boxes Details illustrations can be found in https://giou.stanford.edu/ Args: boxes1: paddle.Tensor, shape=N x 4, boxes are stored in (x1, y1, x2, y2) format box...
31,378
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `masks_to_boxes` function. Write a Python function `def masks_to_boxes(masks)` to solve the following problem: convert masks to bboxes Args: masks: paddle.Tensor, NxHxW Return: boxes: paddle.Tensor, Nx4 Her...
convert masks to bboxes Args: masks: paddle.Tensor, NxHxW Return: boxes: paddle.Tensor, Nx4
31,379
import os import paddle from paddle.io import Dataset, DataLoader from paddle.vision import transforms, datasets, image_load, set_image_backend import numpy as np import argparse from PIL import Image import cv2 from config import * class ImageNet1MDataset(Dataset): def __init__(self, file_folder, mode="train", tra...
null
31,380
import os import paddle from paddle.io import Dataset, DataLoader from paddle.vision import transforms, datasets, image_load, set_image_backend import numpy as np import argparse from PIL import Image import cv2 from config import * def get_loader(config, dataset_train, dataset_test=None, multi=False): # multigpu ...
null
31,381
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as infile: yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_conf...
Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config
31,382
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 256 _C.DATA.BATCH_SIZE_EVAL = 8 _C.DATA.DATA_PATH = '/dataset/coco/' _C.DATA.DATASET = 'coco' _C.DATA.NUM_WORKERS = 2 _C.DATA.IMAGENET_MEAN = [0.485, 0.456, 0.406] _C.DATA.IMAGENET_STD = [0.229, 0.22...
Return a clone of config or load from yaml file
31,383
import paddle import paddle.nn as nn import paddle.nn.functional as F def dice_loss(inputs, targets, num_boxes): inputs = F.sigmoid(inputs) inputs = inputs.flatten(1) numerator = 2 * (inputs * targets).sum(1) denominaror = inputs.sum(-1) + target.sum(-1) loss = 1 - (numerator + 1) / (denominator +1...
null
31,384
import paddle import paddle.nn as nn import paddle.nn.functional as F def sigmoid_focal_loss(inputs, targets, num_boxes, alpha=.25, gamma=2.): prob = F.sigmoid(inputs) ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") p_t = prob * targets + (1 - prob) * (1 - targets) loss ...
null
31,385
import numpy as np import paddle import paddle.nn.Functional as F def one_hot(x, num_classes, on_value=1., off_value=0.): one_hot = F.one_hot(x, num_classes) return paddle.scatter_(paddle.full((x.shape[0], num_classes), off_value), x, on_value) def mixup_target(target, num_classes, lam=1., smoothing=0.0, devic...
null
31,386
import numpy as np import paddle import paddle.nn.Functional as F def rand_bbox(img_shape, lam, margin=0., count=None): """ Standard CutMix bounding-box Generates a random square bbox based on lambda value. This impl includes support for enforcing a border margin as percent of bbox dimensions. Args: ...
Generate bbox and apply lambda correction.
31,387
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from config import get_config from config import update_c...
return arguments, this will overwrite the config after loading yaml file
31,388
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from config import get_config from config import update_c...
set logging file and format Args: filename: str, full path of the logger file to write logger_name: str, the logger name, e.g., 'master_logger', 'local_logger' Return: logger: python logger
31,389
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from config import get_config from config import update_c...
Training for one epoch Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, DETR model criterion: criterion defined in DETR postprocessors: PostProcess, converts output to the coco format base_ds: coco api instance for generate CocoEvaluator, pycocotools.coco.COCO(anno_file) optimizer: nn.optimi...
31,390
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from config import get_config from config import update_c...
Validate for whole dataset Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, DETR model criterion: criterion defined in DETR postprocessors: PostProcess, converts output to the coco format base_ds: coco api instance for generate CocoEvaluator, pycocotools.coco.COCO(anno_file) total_batch: int...
31,391
import random import math import paddle def _get_pixels(per_pixel, rand_color, patch_size, dtype="float32"): if per_pixel: return paddle.normal(shape=patch_size).astype(dtype) elif rand_color: return paddle.normal(shape=(patch_size[0], 1, 1)).astype(dtype) else: return paddle.zeros(...
null
31,392
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url def init_weights(lr): weight_attr = paddle.ParamAttr(learning_rate=lr) bias_attr = paddle.ParamAttr(learning_rate=lr) return weight_attr, bias_attr
null
31,393
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url class BasicBlock(nn.Layer): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, ...
null
31,394
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url class BasicBlock(nn.Layer): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, ...
null
31,395
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url class BottleneckBlock(nn.Layer): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, ...
null
31,396
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url class BottleneckBlock(nn.Layer): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, ...
null
31,397
from functools import partial import paddle import paddle.nn as nn from paddle.utils.download import get_weights_path_from_url class BottleneckBlock(nn.Layer): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, ...
null
31,398
import os import contextlib import copy import numpy as np import paddle from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def convert_to_xywh(boxes): #xmin, ymin, xmax, ymax = boxes.unbind(1) #return paddle.stack((xmin...
null
31,399
import os import contextlib import copy import numpy as np import paddle from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def merge(img_ids, eval_imgs): #all_img_ids = [img_ids] #all_eval_imgs = [eval_imgs] all_img_...
null
31,401
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def crop(image, target, region): cropped_i...
null
31,402
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def hflip(image, target): flipped_image = ...
null
31,403
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def resize(image, target, size, max_size=None)...
null
31,404
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def pad(image, target, padding=None, size_divi...
null
31,405
import copy import pickle import numpy as np import paddle import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def _max_by_axis(the_list): maxes = the_list[0] for sublist in the_list[1:]: for idx, item in enumerate(sublist): maxes[idx] = max(maxes[idx], item) re...
make the batch handle different image sizes This method take a list of tensors with different sizes, then max size is selected as the final batch size, smaller samples are padded with zeros(bottom-right), and corresponding masks are generated.
31,409
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddle.distributed as dist from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from pvtv2_det import b...
null
31,410
import os import copy import numpy as np from PIL import Image import paddle from pycocotools.coco import COCO from pycocotools import mask as coco_mask import transforms as T from utils import nested_tensor_from_tensor_list The provided code snippet includes necessary dependencies for implementing the `convert_coco_p...
Convert coco anno from polygons to image masks
31,411
import os import copy import numpy as np from PIL import Image import paddle from pycocotools.coco import COCO from pycocotools import mask as coco_mask import transforms as T from utils import nested_tensor_from_tensor_list class CocoDetection(paddle.io.Dataset): """ COCO Detection dataset This class gets imag...
Return CocoDetection dataset according to image_set: ['train', 'val']
31,412
import os import copy import numpy as np from PIL import Image import paddle from pycocotools.coco import COCO from pycocotools import mask as coco_mask import transforms as T from utils import nested_tensor_from_tensor_list def collate_fn(batch): """Collate function for batching samples Samples varies in sizes...
return dataloader on train/val set for single/multi gpu Arguments: dataset: paddle.io.Dataset, coco dataset batch_size: int, num of samples in one batch mode: str, ['train', 'val'], dataset to use multi_gpu: bool, if True, DistributedBatchSampler is used for DDP
31,417
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `masks_to_boxes` function. Write a Python function `def masks_to_boxes(masks)` to solve the following problem: convert masks to bboxes Args: masks: paddle.Tensor, NxHxW Return: boxes: paddle.Tensor, Nx4 Her...
convert masks to bboxes Args: masks: paddle.Tensor, NxHxW Return: boxes: paddle.Tensor, Nx4
31,418
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as infile: yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_conf...
Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config
31,419
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 8 _C.DATA.BATCH_SIZE_EVAL = 1 _C.DATA.WEIGHT_PATH = './weights/pvtv2_b0_maskrcnn.pdparams' _C.DATA.VAL_DATA_PATH = "/dataset/coco/" _C.DATA.DATASET = 'coco' _C.DATA.IMAGE_SIZE = 640 _C.DATA.CROP_PCT ...
Return a clone config or load from yaml file
31,420
import math import paddle import paddle.nn as nn from paddle.nn.initializer import Normal, Constant from retinanet_loss import RetinaNetLoss from post_process import RetinaNetPostProcess from det_utils.generator_utils import AnchorGenerator def transpose_to_bs_hwa_k(tensor, k): assert tensor.dim() == 4 bs, _, ...
null
31,421
import paddle from .box_utils import boxes_iou, bbox2delta def anchor_target_matcher(match_quality_matrix, positive_thresh, negative_thresh, allow_low_quality_matches, low_thresh = -float("inf")): ''' This c...
Args: anchors (tensor): shape [-1, 4] the sum of muti-level anchors. gt_boxes (list): gt_boxes[i] is the i-th img's gt_boxes. positive_thresh (float): the positive class threshold of iou between anchors and gt. negative_thresh (float): the negative class threshold of iou between anchors and gt. batch_size_per_image (in...
31,422
import paddle from .box_utils import boxes_iou, bbox2delta def anchor_target_matcher(match_quality_matrix, positive_thresh, negative_thresh, allow_low_quality_matches, low_thresh = -float("inf")): ''' This c...
It performs box matching between "roi" and "target",and assigns training labels to the proposals. Args: proposals (list[tensor]): the batch RoIs from rpn_head. gt_boxes (list[tensor]): gt_boxes[i] is the i'th img's gt_boxes. gt_classes (list[tensor]): gt_classes[i] is the i'th img's gt_classes. num_classes (int): the n...
31,423
import math import paddle import paddle.nn as nn from paddle.fluid.framework import Variable, in_dygraph_mode from paddle.fluid import core The provided code snippet includes necessary dependencies for implementing the `generate_proposals` function. Write a Python function `def generate_proposals(scores, ...
**Generate proposal Faster-RCNN** This operation proposes RoIs according to each box with their probability to be a foreground object and the box can be calculated by anchors. Bbox_deltais and scores to be an object are the output of RPN. Final proposals could be used to train detection net. For generating proposals, t...
31,424
import math import paddle import paddle.nn as nn from paddle.fluid.framework import Variable, in_dygraph_mode from paddle.fluid import core The provided code snippet includes necessary dependencies for implementing the `roi_align` function. Write a Python function `def roi_align(input, rois, ...
Region of interest align (also known as RoI align) is to perform bilinear interpolation on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). Args: input (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The...
31,425
import math import paddle import paddle.nn as nn from paddle.fluid.framework import Variable, in_dygraph_mode from paddle.fluid import core The provided code snippet includes necessary dependencies for implementing the `distribute_fpn_proposals` function. Write a Python function `def distribute_fpn_proposals(fpn_rois,...
**This op only takes LoDTensor as input.** In Feature Pyramid Networks (FPN) models, it is needed to distribute all proposals into different FPN level, with respect to scale of the proposals, the referring scale and the referring level. Besides, to restore the order of proposals, we return an array which indicates the ...
31,426
import math import paddle from paddle.fluid.framework import in_dygraph_mode from paddle.fluid import core from paddle.fluid.layer_helper import LayerHelper The provided code snippet includes necessary dependencies for implementing the `delta2bbox` function. Write a Python function `def delta2bbox(deltas, boxes, weigh...
The inverse process of bbox2delta.
31,427
import math import paddle from paddle.fluid.framework import in_dygraph_mode from paddle.fluid import core from paddle.fluid.layer_helper import LayerHelper def boxes_area(boxes): ''' Compute boxes area. Args: boxes (tensor): shape [M, 4] | [N, M, 4]. Returns: areas (tensor): shape [M] ...
Compute the ious of two boxes tensor and the coordinate format of boxes is xyxy. Args: boxes1 (tensor): when mode == 'a': shape [N, M, 4]; when mode == 'b': shape [N, M, 4] boxes2 (tensor): when mode == 'a': shape [N, R, 4]; when mode == 'b': shape [N, M, 4] mode (string | 'a' or 'b'): when mode == 'a': compute one to ...
31,428
import math import paddle from paddle.fluid.framework import in_dygraph_mode from paddle.fluid import core from paddle.fluid.layer_helper import LayerHelper def nonempty_bbox(boxes, min_size=0, return_mask=False): w = boxes[:, 2] - boxes[:, 0] h = boxes[:, 3] - boxes[:, 1] mask = paddle.logical_and(h > min...
null
31,429
import math import paddle from paddle.fluid.framework import in_dygraph_mode from paddle.fluid import core from paddle.fluid.layer_helper import LayerHelper The provided code snippet includes necessary dependencies for implementing the `multiclass_nms` function. Write a Python function `def multiclass_nms(bboxes, ...
This operator is to do multi-class non maximum suppression (NMS) on boxes and scores. In the NMS step, this operator greedily selects a subset of detection bounding boxes that have high scores larger than score_threshold, if providing this threshold, then selects the largest nms_top_k confidences scores if nms_top_k is...
31,430
from itertools import repeat import collections.abc import numpy as np import paddle import paddle.nn as nn def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable): return x return tuple(repeat(x, n)) return parse
null
31,431
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddle.distributed as dist from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from pvtv2_det import b...
Training for one epoch Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, DETR model criterion: nn.Layer postprocessors: nn.Layer base_ds: coco api instance train_loss_rpn_cls_meter.avg epoch: int, current epoch total_epoch: int, total num of epoch, for logging debug_steps: int, num of iters t...
31,432
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import paddle.distributed as dist from coco import build_coco from coco import get_dataloader from coco_eval import CocoEvaluator from pvtv2_det import b...
Validation for whole dataset Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a ViT model criterion: criterion postprocessors: postprocessor for generating bboxes base_ds: COCO instance total_epoch: int, total num of epoch, for logging debug_steps: int, num of iters to log info Returns: val_...
31,434
import copy import paddle import paddle.nn as nn from model_utils import DropPath class PyramidVisionTransformerV2(nn.Layer): """PyramidVisionTransformerV2 class Attributes: patch_size: int, size of patch image_size: int, size of image num_classes: int, num of image classes in_ch...
null
31,435
import paddle import paddle.nn as nn from config import get_config from pvtv2_backbone import build_pvtv2 from det_necks.fpn import FPN, LastLevelMaxPool from det_heads.maskrcnn_head.rpn_head import RPNHead from det_heads.maskrcnn_head.roi_head import RoIHead class PVTv2Det(nn.Layer): def __init__(self, config): ...
null
31,436
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils def print_model_named_params(mod...
null
31,437
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils def print_model_named_buffers(mo...
null
31,438
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils def torch_to_paddle_mapping(): ...
null
31,439
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils class NestedTensor(): """Eac...
null
31,440
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils class NestedTensor(): """Eac...
null
31,465
import sys import os import argparse import numpy as np import paddle import torch from config import get_config from pvtv2_det import build_pvtv2_det from model_utils import DropPath from utils import NestedTensor from misc import NestedTensor as ThNestedTensor import misc as th_utils class NestedTensor(): def _...
null
31,472
import paddle from .box_utils import boxes_iou, bbox2delta def anchor_target_matcher(match_quality_matrix, positive_thresh, negative_thresh, allow_low_quality_matches, low_thresh = -float("inf")): ''' This c...
It performs box matching between "roi" and "target",and assigns training labels to the proposals. Args: proposals (list[tensor]): the batch RoIs from rpn_head. gt_boxes (list[tensor]): gt_boxes[i] is the i'th img's gt_boxes. gt_classes (list[tensor]): gt_classes[i] is the i'th img's gt_classes. num_classes (int): the n...
31,481
import os import contextlib import copy import numpy as np from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def convert_to_xywh(boxes): #xmin, ymin, xmax, ymax = boxes.unbind(1) #return paddle.stack((xmin, ymin, xmax -...
null
31,482
import os import contextlib import copy import numpy as np from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather def merge(img_ids, eval_imgs): #all_img_ids = [img_ids] #all_eval_imgs = [eval_imgs] all_img_ids = all_gath...
null
31,483
import os import contextlib import copy import numpy as np from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from utils import all_gather The provided code snippet includes necessary dependencies for implementing the `evaluate` function. Write a Python fun...
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
31,486
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def resize(image, target, size, max_size=None)...
null
31,487
import random import numpy as np import PIL import paddle import paddle.vision.transforms as T from paddle.vision.transforms import functional as F from random_erasing import RandomErasing from box_ops import box_xyxy_to_cxcywh from box_ops import box_xyxy_to_cxcywh_numpy def pad(image, target, padding): padded_im...
null
31,492
import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from model_utils import DropPath, _ntuple The provided code snippet includes necessary dependencies for implementing the `windows_partition` function. Write a Python function `def windows_partition(x, window_size)` to solve the fo...
partite windows into window_size x window_size Args: x: Tensor, shape=[b, h, w, c] window_size: int, window size Returns: x: Tensor, shape=[num_windows*b, window_size, window_size, c]