code stringlengths 17 6.64M |
|---|
def get_dataset(data_cfg):
if isinstance(data_cfg['ann_file'], (list, tuple)):
ann_files = data_cfg['ann_file']
num_dset = len(ann_files)
else:
ann_files = [data_cfg['ann_file']]
num_dset = 1
if ('proposal_file' in data_cfg.keys()):
if isinstance(data_cfg['proposal_... |
class VOCDataset(XMLDataset):
CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')
def __init__(self, **kwargs):
super(VOCDataset, self).__init__(**... |
class XMLDataset(CustomDataset):
def __init__(self, **kwargs):
super(XMLDataset, self).__init__(**kwargs)
self.cat2label = {cat: (i + 1) for (i, cat) in enumerate(self.CLASSES)}
def load_annotations(self, ann_file):
img_infos = []
img_ids = mmcv.list_from_file(ann_file)
... |
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, dilation)
self.bn1 = nn.BatchNorm2d(planes)
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
'Bottleneck block.\n If style is "pytorch", the stride-two layer is the 3x3 conv layer,\n if it is "caffe", the stride-two layer is the... |
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False):
downsample = None
if ((stride != 1) or (inplanes != (planes * block.expansion))):
downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=Fal... |
class ResNet(nn.Module):
'ResNet backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n num_stages (int): Resnet stages, normally 4.\n strides (Sequence[int]): Strides of the first block of each stage.\n dilations (Sequence[int]): Dilation of each stage.\... |
class ConvFCBBoxHead(BBoxHead):
'More general bbox head, with shared conv and fc layers and two optional\n separated branches.\n\n /-> cls convs -> cls fcs -> cls\n shared convs -> shared fcs\n \\-> reg convs -> reg fcs -> reg\n '
def __i... |
class SharedFCBBoxHead(BBoxHead):
def __init__(self, in_channels=256, fc_out_channels=1024, roi_feat_size=(7, 7), num_classes=1, reg_dim=7, reg_class_agnostic=True):
super(SharedFCBBoxHead, self).__init__()
self.num_classes = num_classes
self.reg_class_agnostic = reg_class_agnostic
... |
def _build_module(cfg, parrent=None, default_args=None):
return (cfg if isinstance(cfg, nn.Module) else obj_from_dict(cfg, parrent, default_args))
|
def build(cfg, parrent=None, default_args=None):
if isinstance(cfg, list):
modules = [_build_module(cfg_, parrent, default_args) for cfg_ in cfg]
return nn.Sequential(*modules)
else:
return _build_module(cfg, parrent, default_args)
|
def build_backbone(cfg):
return build(cfg, backbones)
|
def build_neck(cfg):
return build(cfg, necks)
|
def build_rpn_head(cfg):
return build(cfg, rpn_heads)
|
def build_roi_extractor(cfg):
return build(cfg, roi_extractors)
|
def build_bbox_head(cfg):
return build(cfg, bbox_heads)
|
def build_mask_head(cfg):
return build(cfg, mask_heads)
|
def build_single_stage_head(cfg):
return build(cfg, single_stage_heads)
|
def build_detector(cfg, train_cfg=None, test_cfg=None):
from . import detectors
return build(cfg, detectors, dict(train_cfg=train_cfg, test_cfg=test_cfg))
|
class PointPillars(BaseDetector):
def __init__(self, backbone, neck, rpn_head=None, bbox_head=None, rcnn_head=None, train_cfg=None, test_cfg=None, pretrained=None):
super(PointPillars, self).__init__()
self.backbone = builder.build_backbone(backbone)
self.neck = builder.build_neck(neck)
... |
def cfg_from_file(filename):
'Load a config file and merge it into the default options.'
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
|
def _merge_a_into_b(a, b):
'Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n '
if (type(a) is not edict):
return
for (k, v) in a.items():
if (k not in b):
raise KeyError('{} is not a valid config ke... |
def cfg_from_list(cfg_list):
'Set config keys via list (e.g., from command line).'
from ast import literal_eval
assert ((len(cfg_list) % 2) == 0)
for (k, v) in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = k.split('.')
d = __C
for subkey in key_list[:(- 1)]:
asser... |
def save_config_to_file(cfg, pre='cfg', logger=None):
for (key, val) in cfg.items():
if isinstance(cfg[key], edict):
if (logger is not None):
logger.info(('\n%s.%s = edict()' % (pre, key)))
else:
print(('\n%s.%s = edict()' % (pre, key)))
... |
class FPN(nn.Module):
def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=(- 1), add_extra_convs=False, normalize=None, activation=None):
super(FPN, self).__init__()
assert isinstance(in_channels, list)
self.in_channels = in_channels
self.out_channels ... |
class RPNBase(nn.Module):
def __init__(self, use_norm=True, layer_nums=(3, 5, 5), layer_strides=(2, 2, 2), num_filters=(128, 128, 256), upsample_strides=(1, 2, 4), num_upsample_filters=(256, 256, 256), num_input_features=128):
'upsample_strides support float: [0.25, 0.5, 1]\n if upsample_strides <... |
class RPN(RPNBase):
def _make_layer(self, inplanes, planes, num_blocks, stride=1):
if self._use_norm:
BatchNorm2d = change_default_args(eps=0.001, momentum=0.01)(nn.BatchNorm2d)
Conv2d = change_default_args(bias=False)(nn.Conv2d)
ConvTranspose2d = change_default_args(b... |
def get_paddings_indicator(actual_num, max_num, axis=0):
'Create boolean mask by actually number of a padded tensor.\n Args:\n actual_num ([type]): [description]\n max_num ([type]): [description]\n Returns:\n [type]: [description]\n '
actual_num = torch.unsqueeze(actual_num, (axi... |
def get_pos_to_kw_map(func):
pos_to_kw = {}
fsig = inspect.signature(func)
pos = 0
for (name, info) in fsig.parameters.items():
if (info.kind is info.POSITIONAL_OR_KEYWORD):
pos_to_kw[pos] = name
pos += 1
return pos_to_kw
|
def change_default_args(**kwargs):
def layer_wrapper(layer_class):
class DefaultArgLayer(layer_class):
def __init__(self, *args, **kw):
pos_to_kw = get_pos_to_kw_map(layer_class.__init__)
kw_to_pos = {kw: pos for (pos, kw) in pos_to_kw.items()}
... |
def one_hot(tensor, depth, dim=(- 1), on_value=1.0, dtype=torch.float32):
tensor_onehot = torch.zeros(*list(tensor.shape), depth, dtype=dtype, device=tensor.device)
tensor_onehot.scatter_(dim, tensor.unsqueeze(dim).long(), on_value)
return tensor_onehot
|
class ConvModule(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, normalize=None, activation='relu', inplace=True, activate_last=True):
super(ConvModule, self).__init__()
self.with_norm = (normalize is not None)
s... |
class Empty(torch.nn.Module):
def __init__(self, *args, **kwargs):
super(Empty, self).__init__()
def forward(self, *args, **kwargs):
if (len(args) == 1):
return args[0]
elif (len(args) == 0):
return None
return args
|
def build_norm_layer(cfg, num_features):
assert (isinstance(cfg, dict) and ('type' in cfg))
cfg_ = cfg.copy()
cfg_.setdefault('eps', 1e-05)
layer_type = cfg_.pop('type')
if (layer_type not in norm_cfg):
raise KeyError('Unrecognized norm type {}'.format(layer_type))
elif (norm_cfg[layer... |
class Sequential(torch.nn.Module):
"A sequential container.\n Modules will be added to it in the order they are passed in the constructor.\n Alternatively, an ordered dict of modules can also be passed in.\n\n To make it easier to understand, given is a small example::\n\n # Example of using Seque... |
def xavier_init(module, gain=1, bias=0, distribution='normal'):
assert (distribution in ['uniform', 'normal'])
if (distribution == 'uniform'):
nn.init.xavier_uniform_(module.weight, gain=gain)
else:
nn.init.xavier_normal_(module.weight, gain=gain)
if hasattr(module, 'bias'):
nn... |
def normal_init(module, mean=0, std=1, bias=0):
nn.init.normal_(module.weight, mean, std)
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias)
|
def uniform_init(module, a=0, b=1, bias=0):
nn.init.uniform_(module.weight, a, b)
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias)
|
def kaiming_init(module, mode='fan_out', nonlinearity='relu', bias=0, distribution='normal'):
assert (distribution in ['uniform', 'normal'])
if (distribution == 'uniform'):
nn.init.kaiming_uniform_(module.weight, mode=mode, nonlinearity=nonlinearity)
else:
nn.init.kaiming_normal_(module.we... |
def bias_init_with_prob(prior_prob):
' initialize conv/fc bias value according to giving probablity'
bias_init = float((- np.log(((1 - prior_prob) / prior_prob))))
return bias_init
|
class ThreeNN(Function):
@staticmethod
def forward(ctx, unknown: torch.Tensor, known: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]:
'\n Find the three nearest neighbors of unknown in known\n :param ctx:\n :param unknown: (N, 3)\n :param known: (M, 3)\n :retu... |
class ThreeInterpolate(Function):
@staticmethod
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
'\n Performs weight linear interpolation on 3 features\n :param ctx:\n :param features: (M, C) Features descriptors to be interpolate... |
def pts_in_boxes3d(pts, boxes3d):
N = len(pts)
M = len(boxes3d)
pts_in_flag = torch.IntTensor(M, N).fill_(0)
reg_target = torch.FloatTensor(N, 3).fill_(0)
points_op_cpu.pts_in_boxes3d(pts.contiguous(), boxes3d.contiguous(), pts_in_flag, reg_target)
return (pts_in_flag, reg_target)
|
@numba.jit(nopython=True)
def _points_to_voxel_reverse_kernel(points, voxel_size, coors_range, num_points_per_voxel, coor_to_voxelidx, voxels, coors, max_points=35, max_voxels=20000):
N = points.shape[0]
ndim = 3
ndim_minus_1 = (ndim - 1)
grid_size = ((coors_range[3:] - coors_range[:3]) / voxel_size)
... |
@numba.jit(nopython=True)
def _points_to_voxel_kernel(points, voxel_size, coors_range, num_points_per_voxel, coor_to_voxelidx, voxels, coors, max_points=35, max_voxels=20000):
N = points.shape[0]
ndim = 3
grid_size = ((coors_range[3:] - coors_range[:3]) / voxel_size)
grid_size = np.round(grid_size, 0,... |
def points_to_voxel(points, voxel_size, coors_range, max_points=35, reverse_index=True, max_voxels=20000):
"convert kitti points(N, >=3) to voxels. This version calculate\n everything in one loop. now it takes only 4.2ms(complete point cloud)\n with jit and 3.2ghz cpu.(don't calculate other features)\n N... |
@numba.jit(nopython=True)
def bound_points_jit(points, upper_bound, lower_bound):
N = points.shape[0]
ndim = points.shape[1]
keep_indices = np.zeros((N,), dtype=np.int32)
success = 0
for i in range(N):
success = 1
for j in range((ndim - 1)):
if ((points[(i, j)] < lower_... |
class get_pybind_include(object):
'Helper class to determine the pybind11 include path\n The purpose of this class is to postpone importing pybind11\n until it is actually installed, so that the ``get_include()``\n method can be invoked. '
def __init__(self, user=False):
self.user = user
... |
class RoIAwarePool3d(nn.Module):
def __init__(self, out_size, max_pts_each_voxel=128):
super().__init__()
self.out_size = out_size
self.max_pts_each_voxel = max_pts_each_voxel
def forward(self, rois, pts, pts_feature, pool_method='max'):
assert (pool_method in ['max', 'avg'])... |
class RoIAwarePool3dFunction(Function):
@staticmethod
def forward(ctx, rois, pts, pts_feature, out_size, max_pts_each_voxel, pool_method):
"\n :param rois: (N, 7) [x, y, z, w, l, h, ry] in LiDAR coordinate, (x, y, z) is the bottom center of rois\n :param pts: (npoints, 3)\n :para... |
def points_in_boxes_gpu(points, boxes):
'\n :param points: (B, M, 3)\n :param boxes: (B, T, 8), num_valid_boxes <= T\n :return box_idxs_of_pts: (B, M), default background = -1\n '
assert (boxes.shape[0] == points.shape[0])
assert (boxes.shape[2] == 7)
(batch_size, num_points, _) = points.s... |
def points_in_boxes_cpu(points, boxes):
'\n :param points: (npoints, 3)\n :param boxes: (N, 7) [x, y, z, w, l, h, rz] in LiDAR coordinate, z is the bottom center, each box DO NOT overlaps\n :return point_indices: (N, npoints)\n '
assert (boxes.shape[1] == 7)
assert (points.shape[1] == 3)
p... |
class _PointnetSAModuleBase(nn.Module):
def __init__(self):
super().__init__()
self.npoint = None
self.groupers = None
self.mlps = None
self.pool_method = 'max_pool'
def forward(self, xyz: torch.Tensor, features: torch.Tensor=None, new_xyz=None) -> (torch.Tensor, torc... |
class PointnetSAModuleMSG(_PointnetSAModuleBase):
'Pointnet set abstraction layer with multiscale grouping'
def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], bn: bool=True, use_xyz: bool=True, pool_method='max_pool', instance_norm=False):
'\n :p... |
class PointnetSAModule(PointnetSAModuleMSG):
'Pointnet set abstraction layer'
def __init__(self, *, mlp: List[int], npoint: int=None, radius: float=None, nsample: int=None, bn: bool=True, use_xyz: bool=True, pool_method='max_pool', instance_norm=False):
'\n :param mlp: list of int, spec of the... |
class PointnetFPModule(nn.Module):
'Propigates the features of one set to another'
def __init__(self, *, mlp: List[int], bn: bool=True):
'\n :param mlp: list of int\n :param bn: whether to use batchnorm\n '
super().__init__()
self.mlp = pt_utils.SharedMLP(mlp, bn=... |
class FurthestPointSampling(Function):
@staticmethod
def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:
'\n Uses iterative furthest point sampling to select a set of npoint features that have the largest\n minimum distance\n :param ctx:\n :param xyz: (B, N, ... |
class GatherOperation(Function):
@staticmethod
def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
'\n :param ctx:\n :param features: (B, C, N)\n :param idx: (B, npoint) index tensor of the features to gather\n :return:\n output: (B, C, ... |
class ThreeNN(Function):
@staticmethod
def forward(ctx, unknown: torch.Tensor, known: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]:
'\n Find the three nearest neighbors of unknown in known\n :param ctx:\n :param unknown: (B, N, 3)\n :param known: (B, M, 3)\n ... |
class ThreeInterpolate(Function):
@staticmethod
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
'\n Performs weight linear interpolation on 3 features\n :param ctx:\n :param features: (B, C, M) Features descriptors to be interpol... |
class GroupingOperation(Function):
@staticmethod
def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
'\n :param ctx:\n :param features: (B, C, N) tensor of features to group\n :param idx: (B, npoint, nsample) tensor containing the indicies of features to ... |
class BallQuery(Function):
@staticmethod
def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, new_xyz: torch.Tensor) -> torch.Tensor:
'\n :param ctx:\n :param radius: float, radius of the balls\n :param nsample: int, maximum number of features in the balls\n :p... |
class QueryAndGroup(nn.Module):
def __init__(self, radius: float, nsample: int, use_xyz: bool=True):
'\n :param radius: float, radius of ball\n :param nsample: int, maximum number of features to gather in the ball\n :param use_xyz:\n '
super().__init__()
(self.... |
class GroupAll(nn.Module):
def __init__(self, use_xyz: bool=True):
super().__init__()
self.use_xyz = use_xyz
def forward(self, xyz: torch.Tensor, new_xyz: torch.Tensor, features: torch.Tensor=None):
'\n :param xyz: (B, N, 3) xyz coordinates of the features\n :param new_... |
class SharedMLP(nn.Sequential):
def __init__(self, args: List[int], *, bn: bool=False, activation=nn.ReLU(inplace=True), preact: bool=False, first: bool=False, name: str='', instance_norm: bool=False):
super().__init__()
for i in range((len(args) - 1)):
self.add_module((name + 'layer{... |
class _ConvBase(nn.Sequential):
def __init__(self, in_size, out_size, kernel_size, stride, padding, activation, bn, init, conv=None, batch_norm=None, bias=True, preact=False, name='', instance_norm=False, instance_norm_func=None):
super().__init__()
bias = (bias and (not bn))
conv_unit = ... |
class _BNBase(nn.Sequential):
def __init__(self, in_size, batch_norm=None, name=''):
super().__init__()
self.add_module((name + 'bn'), batch_norm(in_size))
nn.init.constant_(self[0].weight, 1.0)
nn.init.constant_(self[0].bias, 0)
|
class BatchNorm1d(_BNBase):
def __init__(self, in_size: int, *, name: str=''):
super().__init__(in_size, batch_norm=nn.BatchNorm1d, name=name)
|
class BatchNorm2d(_BNBase):
def __init__(self, in_size: int, name: str=''):
super().__init__(in_size, batch_norm=nn.BatchNorm2d, name=name)
|
class Conv1d(_ConvBase):
def __init__(self, in_size: int, out_size: int, *, kernel_size: int=1, stride: int=1, padding: int=0, activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str='', instance_norm=False):
super().__init__(in_size,... |
class Conv2d(_ConvBase):
def __init__(self, in_size: int, out_size: int, *, kernel_size: Tuple[(int, int)]=(1, 1), stride: Tuple[(int, int)]=(1, 1), padding: Tuple[(int, int)]=(0, 0), activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str=''... |
class FC(nn.Sequential):
def __init__(self, in_size: int, out_size: int, *, activation=nn.ReLU(inplace=True), bn: bool=False, init=None, preact: bool=False, name: str=''):
super().__init__()
fc = nn.Linear(in_size, out_size, bias=(not bn))
if (init is not None):
init(fc.weight... |
def log_print(info, log_f=None):
print(info)
if (log_f is not None):
print(info, file=log_f)
|
class DiceLoss(nn.Module):
def __init__(self, ignore_target=(- 1)):
super().__init__()
self.ignore_target = ignore_target
def forward(self, input, target):
'\n :param input: (N), logit\n :param target: (N), {0, 1}\n :return:\n '
input = torch.sigmo... |
def train_one_epoch(model, train_loader, optimizer, epoch, lr_scheduler, total_it, tb_log, log_f):
model.train()
log_print(('===============TRAIN EPOCH %d================' % epoch), log_f=log_f)
loss_func = DiceLoss(ignore_target=(- 1))
for (it, batch) in enumerate(train_loader):
optimizer.zer... |
def eval_one_epoch(model, eval_loader, epoch, tb_log, log_f=None):
model.train()
log_print(('===============EVAL EPOCH %d================' % epoch), log_f=log_f)
iou_list = []
for (it, batch) in enumerate(eval_loader):
(pts_input, cls_labels) = (batch['pts_input'], batch['cls_labels'])
... |
def save_checkpoint(model, epoch, ckpt_name):
if isinstance(model, torch.nn.DataParallel):
model_state = model.module.state_dict()
else:
model_state = model.state_dict()
state = {'epoch': epoch, 'model_state': model_state}
ckpt_name = '{}.pth'.format(ckpt_name)
torch.save(state, ck... |
def load_checkpoint(model, filename):
if os.path.isfile(filename):
log_print(('==> Loading from checkpoint %s' % filename))
checkpoint = torch.load(filename)
epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['model_state'])
log_print('==> Done')
else:
... |
def train_and_eval(model, train_loader, eval_loader, tb_log, ckpt_dir, log_f):
model.cuda()
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
def lr_lbmd(cur_epoch):
cur_decay = 1
for decay_step in args.decay_step_list:
if (cur_epoch >= dec... |
def main():
parser = ArgumentParser(description='COCO Evaluation')
parser.add_argument('result', help='result file path')
parser.add_argument('--ann', help='annotation file path')
parser.add_argument('--types', type=str, nargs='+', choices=['proposal_fast', 'proposal', 'bbox', 'segm', 'keypoint'], def... |
def parse_xml(args):
(xml_path, img_path) = args
tree = ET.parse(xml_path)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
bboxes = []
labels = []
bboxes_ignore = []
labels_ignore = []
for obj in root.findall... |
def cvt_annotations(devkit_path, years, split, out_file):
if (not isinstance(years, list)):
years = [years]
annotations = []
for year in years:
filelist = osp.join(devkit_path, 'VOC{}/ImageSets/Main/{}.txt'.format(year, split))
if (not osp.isfile(filelist)):
print('file... |
def parse_args():
parser = argparse.ArgumentParser(description='Convert PASCAL VOC annotations to mmdetection format')
parser.add_argument('devkit_path', help='pascal voc devkit path')
parser.add_argument('-o', '--out-dir', help='output path')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
devkit_path = args.devkit_path
out_dir = (args.out_dir if args.out_dir else devkit_path)
mmcv.mkdir_or_exist(out_dir)
years = []
if osp.isdir(osp.join(devkit_path, 'VOC2007')):
years.append('2007')
if osp.isdir(osp.join(devkit_path, 'VOC2012')):
... |
def add_path(path):
if (path not in sys.path):
sys.path.insert(0, path)
|
def single_test(model, data_loader, saveto=None, class_names=['Car'], show=False):
template = (('{} ' + ' '.join(['{:.4f}' for _ in range(15)])) + '\n')
if (saveto is not None):
mmcv.mkdir_or_exist(saveto)
model.eval()
annos = []
prog_bar = mmcv.ProgressBar(len(data_loader.dataset))
fo... |
def _data_func(data, device_id):
data = scatter(collate([data], samples_per_gpu=1), [device_id])[0]
return dict(return_loss=False, rescale=True, **data)
|
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test detector')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--gpus', default=1, type=int, help='GPU number used for testing')
parser.... |
def main():
args = parse_args()
cfg = mmcv.Config.fromfile(args.config)
cfg.model.pretrained = None
dataset = utils.get_dataset(cfg.data.val)
class_names = cfg.data.val.class_names
if (args.gpus == 1):
model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
loa... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work_dir', help='the dir to save logs and models')
parser.add_argument('--validate', action='store_true', help='whether to evaluate the... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
cfg.gpus = args.gpus
if (cfg.checkpoint_config is not None):
cfg.checkpoint_config.meta = dict(mmdet_version=__version__, config=cfg.text)
if (args.la... |
def draw_tension(time, values):
fig = plt.figure(figsize=(20, 10))
plt.rcParams['xtick.labelsize'] = 14
plt.plot(time, values, marker='o')
plt.tight_layout()
plt.show()
|
@hydra.main(config_path='configs/', config_name='convert.yaml')
def convert(config: DictConfig):
assert (config.get('convert_to') in ['pytorch', 'torchscript', 'onnx', 'tensorrt']), 'Please Choose one of [pytorch, torchscript, onnx, tensorrt]'
log.info(f'Instantiating model <{config.model._target_}>')
mod... |
def generate(imgs_path, vid_path, fps=30, frame_size=(1242, 375), resize=True):
'Generate frames to vid'
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
vid_writer = cv2.VideoWriter(vid_path, fourcc, fps, frame_size)
imgs_glob = sorted(glob(os.path.join(imgs_path, '*.png')))
if resize:
for img_pa... |
def generate_sets(images_path: str, dump_dir: str, postfix: str='', train_size: float=0.8, is_yolo: bool=False):
images = glob(os.path.join(images_path, '*.png'))
ids = [id_.split('/')[(- 1)].split('.')[0] for id_ in images]
train_sets = sorted(ids[:int((len(ids) * train_size))])
val_sets = sorted(ids... |
def get_assets(tag):
'Get release assets by tag name'
url = ('https://api.github.com/repos/ruhyadi/yolo3d-lightning/releases/tags/' + tag)
response = requests.get(url)
return response.json()['assets']
|
def download_assets(assets, dir):
'Download assets to dir'
for asset in assets:
url = asset['browser_download_url']
filename = asset['name']
print('[INFO] Downloading {}'.format(filename))
response = requests.get(url, stream=True)
with open(os.path.join(dir, filename), ... |
class KITTI2YOLO():
def __init__(self, dataset_path: str='../data/KITTI', classes: Tuple=['car', 'van', 'truck', 'pedestrian', 'cyclist'], img_width: int=1224, img_height: int=370):
self.dataset_path = dataset_path
self.img_width = img_width
self.img_height = img_height
self.class... |
def create_release(tag, name, description, target='main'):
'Create release'
token = os.environ.get('GITHUB_TOKEN')
headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}', 'Content-Type': 'application/zip'}
url = 'https://api.github.com/repos/ruhyadi/yolo3d-lightning/r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.