code stringlengths 17 6.64M |
|---|
def make_cuda_ext(name, module, sources):
define_macros = []
if (torch.cuda.is_available() or (os.getenv('FORCE_CUDA', '0') == '1')):
define_macros += [('WITH_CUDA', None)]
else:
raise EnvironmentError('CUDA is required to compile MMDetection!')
return CUDAExtension(name='{}.{}'.format... |
def parse_requirements(fname='requirements.txt', with_version=True):
'Parse the package dependencies listed in a requirements file but strips\n specific versioning information.\n\n Args:\n fname (str): path to requirements file\n with_version (bool, default=False): if True include version spec... |
def test_max_iou_assigner():
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
gt_labels = torch.LongTensor([2, 3])
assign_result =... |
def test_max_iou_assigner_with_ignore():
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])... |
def test_max_iou_assigner_with_empty_gt():
'Test corner case where an image might have no true detections.'
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([])
ass... |
def test_max_iou_assigner_with_empty_boxes():
'Test corner case where an network might predict no boxes.'
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
gt_labels = torch.LongTensor([2, 3])
as... |
def test_max_iou_assigner_with_empty_boxes_and_ignore():
'Test corner case where an network might predict no boxes and\n ignore_iof_thr is on.'
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, ... |
def test_max_iou_assigner_with_empty_boxes_and_gt():
'Test corner case where an network might predict no boxes and no gt.'
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.empty((0, 4))
assign_result = self.assign(bboxes, gt_bboxes)
assert ... |
def test_point_assigner():
self = PointAssigner()
points = torch.FloatTensor([[0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
assign_result = self.assign(points, gt_bboxes)
expected_gt_inds = torch.LongTensor([1, 2, 1, 0])
assert... |
def test_point_assigner_with_empty_gt():
'Test corner case where an image might have no true detections.'
self = PointAssigner()
points = torch.FloatTensor([[0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1]])
gt_bboxes = torch.FloatTensor([])
assign_result = self.assign(points, gt_bboxes)
expecte... |
def test_point_assigner_with_empty_boxes_and_gt():
'Test corner case where an image might predict no points and no gt.'
self = PointAssigner()
points = torch.FloatTensor([])
gt_bboxes = torch.FloatTensor([])
assign_result = self.assign(points, gt_bboxes)
assert (len(assign_result.gt_inds) == 0... |
def test_approx_iou_assigner():
self = ApproxMaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
approxs_per_octave = 1
approxs = bboxes
... |
def test_approx_iou_assigner_with_empty_gt():
'Test corner case where an image might have no true detections.'
self = ApproxMaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([]... |
def test_approx_iou_assigner_with_empty_boxes():
'Test corner case where an network might predict no boxes.'
self = ApproxMaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
approxs_per_octave = 1
approxs... |
def test_approx_iou_assigner_with_empty_boxes_and_gt():
'Test corner case where an network might predict no boxes and no gt.'
self = ApproxMaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.empty((0, 4))
approxs_per_octave = 1
approxs = bboxes
s... |
def test_random_assign_result():
'Test random instantiation of assign result to catch corner cases.'
from mmdet.core.bbox.assigners.assign_result import AssignResult
AssignResult.random()
AssignResult.random(num_gts=0, num_preds=0)
AssignResult.random(num_gts=0, num_preds=3)
AssignResult.rando... |
class AsyncTestCase(asynctest.TestCase):
use_default_loop = False
forbid_get_event_loop = True
TEST_TIMEOUT = int(os.getenv('ASYNCIO_TEST_TIMEOUT', '30'))
def _run_test_method(self, method):
result = method()
if asyncio.iscoroutine(result):
self.loop.run_until_complete(asy... |
class MaskRCNNDetector():
def __init__(self, model_config, checkpoint=None, streamqueue_size=3, device='cuda:0'):
self.streamqueue_size = streamqueue_size
self.device = device
self.model = init_detector(model_config, checkpoint=None, device=self.device)
self.streamqueue = None
... |
class AsyncInferenceTestCase(AsyncTestCase):
if (sys.version_info >= (3, 7)):
async def test_simple_inference(self):
if (not torch.cuda.is_available()):
import pytest
pytest.skip('test requires GPU and torch+cuda')
root_dir = os.path.dirname(os.path... |
def _get_config_directory():
'Find the predefined detector config directory.'
try:
repo_dpath = dirname(dirname(__file__))
except NameError:
import mmdet
repo_dpath = dirname(dirname(mmdet.__file__))
config_dpath = join(repo_dpath, 'configs')
if (not exists(config_dpath)):
... |
def test_config_build_detector():
'Test that all detection models defined in the configs can be\n initialized.'
from xdoctest.utils import import_module_from_path
from mmdet.models import build_detector
config_dpath = _get_config_directory()
print('Found config_dpath = {!r}'.format(config_dpath... |
def test_config_data_pipeline():
'Test whether the data pipeline is valid and can process corner cases.\n\n CommandLine:\n xdoctest -m tests/test_config.py test_config_build_data_pipeline\n '
from xdoctest.utils import import_module_from_path
from mmdet.datasets.pipelines import Compose
i... |
def test_nms_device_and_dtypes_cpu():
'\n CommandLine:\n xdoctest -m tests/test_nms.py test_nms_device_and_dtypes_cpu\n '
iou_thr = 0.7
base_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.9], [49.3, 32.9, 51.0, 35.3, 0.9], [35.3, 11.5, 39.9, 14.5, 0.4], [35.2, 11.7, 39.7, 15.7, 0.3]])
dets =... |
def test_nms_device_and_dtypes_gpu():
'\n CommandLine:\n xdoctest -m tests/test_nms.py test_nms_device_and_dtypes_gpu\n '
if (not torch.cuda.is_available()):
import pytest
pytest.skip('test requires GPU and torch+cuda')
iou_thr = 0.7
base_dets = np.array([[49.1, 32.4, 51.0... |
def test_random_sampler():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
gt_la... |
def test_random_sampler_empty_gt():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.empty(0, 4)
gt_labels = torch.empty(0).lon... |
def test_random_sampler_empty_pred():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.empty(0, 4)
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
gt_labels = torch.LongTensor([1, 2])
assign_result = assigne... |
def _context_for_ohem():
try:
from test_forward import _get_detector_cfg
except ImportError:
import sys
from os.path import dirname
sys.path.insert(0, dirname(__file__))
from test_forward import _get_detector_cfg
(model, train_cfg, test_cfg) = _get_detector_cfg('fas... |
def test_ohem_sampler():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]])
gt_labe... |
def test_ohem_sampler_empty_gt():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.empty(0, 4)
gt_labels = torch.LongTensor([])... |
def test_ohem_sampler_empty_pred():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
bboxes = torch.empty(0, 4)
gt_bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_labels = torch.LongTensor([... |
def test_random_sample_result():
from mmdet.core.bbox.samplers.sampling_result import SamplingResult
SamplingResult.random(num_gts=0, num_preds=0)
SamplingResult.random(num_gts=0, num_preds=3)
SamplingResult.random(num_gts=3, num_preds=3)
SamplingResult.random(num_gts=0, num_preds=3)
SamplingR... |
def test_soft_nms_device_and_dtypes_cpu():
'\n CommandLine:\n xdoctest -m tests/test_soft_nms.py test_soft_nms_device_and_dtypes_cpu\n '
iou_thr = 0.7
base_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.9], [49.3, 32.9, 51.0, 35.3, 0.9], [35.3, 11.5, 39.9, 14.5, 0.4], [35.2, 11.7, 39.7, 15.7, 0.... |
def test_params_to_string():
npt.assert_equal(params_to_string(1000000000.0), '1000.0 M')
npt.assert_equal(params_to_string(200000.0), '200.0 k')
npt.assert_equal(params_to_string(3e-09), '3e-09')
|
def cal_train_time(log_dicts, args):
for (i, log_dict) in enumerate(log_dicts):
print('{}Analyze train time of {}{}'.format(('-' * 5), args.json_logs[i], ('-' * 5)))
all_times = []
for epoch in log_dict.keys():
if args.include_outliers:
all_times.append(log_dict... |
def plot_curve(log_dicts, args):
if (args.backend is not None):
plt.switch_backend(args.backend)
sns.set_style(args.style)
legend = args.legend
if (legend is None):
legend = []
for json_log in args.json_logs:
for metric in args.keys:
legend.append('{... |
def add_plot_parser(subparsers):
parser_plt = subparsers.add_parser('plot_curve', help='parser for plotting curves')
parser_plt.add_argument('json_logs', type=str, nargs='+', help='path of train log in json format')
parser_plt.add_argument('--keys', type=str, nargs='+', default=['bbox_mAP'], help='the met... |
def add_time_parser(subparsers):
parser_time = subparsers.add_parser('cal_train_time', help='parser for computing the average time per training iteration')
parser_time.add_argument('json_logs', type=str, nargs='+', help='path of train log in json format')
parser_time.add_argument('--include-outliers', act... |
def parse_args():
parser = argparse.ArgumentParser(description='Analyze Json Log')
subparsers = parser.add_subparsers(dest='task', help='task parser')
add_plot_parser(subparsers)
add_time_parser(subparsers)
args = parser.parse_args()
return args
|
def load_json_logs(json_logs):
log_dicts = [dict() for _ in json_logs]
for (json_log, log_dict) in zip(json_logs, log_dicts):
with open(json_log, 'r') as log_file:
for line in log_file:
log = json.loads(line.strip())
if ('epoch' not in log):
... |
def main():
args = parse_args()
json_logs = args.json_logs
for json_log in json_logs:
assert json_log.endswith('.json')
log_dicts = load_json_logs(json_logs)
eval(args.task)(log_dicts, args)
|
def parse_args():
parser = argparse.ArgumentParser(description='Browse a dataset')
parser.add_argument('config', help='train config file path')
parser.add_argument('--skip-type', type=str, nargs='+', default=['DefaultFormatBundle', 'Normalize', 'Collect'], help='skip some useless pipeline')
parser.add... |
def retrieve_data_cfg(config_path, skip_type):
cfg = Config.fromfile(config_path)
train_data_cfg = cfg.data.train
train_data_cfg['pipeline'] = [x for x in train_data_cfg.pipeline if (x['type'] not in skip_type)]
return cfg
|
def main():
args = parse_args()
cfg = retrieve_data_cfg(args.config, args.skip_type)
dataset = build_dataset(cfg.data.train)
progress_bar = mmcv.ProgressBar(len(dataset))
for item in dataset:
filename = (os.path.join(args.output_dir, Path(item['filename']).name) if (args.output_dir is not ... |
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 convert_bn(blobs, state_dict, caffe_name, torch_name, converted_names):
state_dict[(torch_name + '.bias')] = torch.from_numpy(blobs[(caffe_name + '_b')])
state_dict[(torch_name + '.weight')] = torch.from_numpy(blobs[(caffe_name + '_s')])
bn_size = state_dict[(torch_name + '.weight')].size()
state_... |
def convert_conv_fc(blobs, state_dict, caffe_name, torch_name, converted_names):
state_dict[(torch_name + '.weight')] = torch.from_numpy(blobs[(caffe_name + '_w')])
converted_names.add((caffe_name + '_w'))
if ((caffe_name + '_b') in blobs):
state_dict[(torch_name + '.bias')] = torch.from_numpy(blo... |
def convert(src, dst, depth):
'Convert keys in detectron pretrained ResNet models to pytorch style.'
if (depth not in arch_settings):
raise ValueError('Only support ResNet-50 and ResNet-101 currently')
block_nums = arch_settings[depth]
caffe_model = mmcv.load(src, encoding='latin1')
blobs ... |
def main():
parser = argparse.ArgumentParser(description='Convert model keys')
parser.add_argument('src', help='src detectron model path')
parser.add_argument('dst', help='save path')
parser.add_argument('depth', type=int, help='ResNet model depth')
args = parser.parse_args()
convert(args.src,... |
def fuse_conv_bn(conv, bn):
'During inference, the functionary of batch norm layers is turned off but\n only the mean and var alone channels are used, which exposes the chance to\n fuse it with the preceding conv layers to save computations and simplify\n network structures.'
conv_w = conv.weight
... |
def fuse_module(m):
last_conv = None
last_conv_name = None
for (name, child) in m.named_children():
if isinstance(child, (nn.BatchNorm2d, nn.SyncBatchNorm)):
if (last_conv is None):
continue
fused_conv = fuse_conv_bn(last_conv, child)
m._modules[... |
def parse_args():
parser = argparse.ArgumentParser(description='fuse Conv and BN layers in a model')
parser.add_argument('config', help='config file path')
parser.add_argument('checkpoint', help='checkpoint file path')
parser.add_argument('out', help='output path of the converted model')
args = pa... |
def main():
args = parse_args()
model = init_detector(args.config, args.checkpoint)
fused_model = fuse_module(model)
save_checkpoint(fused_model, args.out)
|
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--shape', type=int, nargs='+', default=[1280, 800], help='input image size')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
if (len(args.shape) == 1):
input_shape = (3, args.shape[0], args.shape[0])
elif (len(args.shape) == 2):
input_shape = ((3,) + tuple(args.shape))
else:
raise ValueError('invalid input shape')
cfg = Config.fromfile(args.config)
model = buil... |
def parse_args():
parser = argparse.ArgumentParser(description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = parser.parse_args()
return args
|
def process_checkpoint(in_file, out_file):
checkpoint = torch.load(in_file, map_location='cpu')
if ('optimizer' in checkpoint):
del checkpoint['optimizer']
torch.save(checkpoint, out_file)
sha = subprocess.check_output(['sha256sum', out_file]).decode()
final_file = (out_file.rstrip('.pth')... |
def main():
args = parse_args()
process_checkpoint(args.in_file, args.out_file)
|
def export_onnx_model(model, inputs, passes):
'Trace and export a model to onnx format. Modified from\n https://github.com/facebookresearch/detectron2/\n\n Args:\n model (nn.Module):\n inputs (tuple[args]): the model will be called by `model(*inputs)`\n passes (None or list[str]): the o... |
def parse_args():
parser = argparse.ArgumentParser(description='MMDet pytorch model conversion to ONNX')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--out', type=str, required=True, help='output ONNX filenam... |
def main():
args = parse_args()
if (not args.out.endswith('.onnx')):
raise ValueError('The output file must be a onnx file.')
if (len(args.shape) == 1):
input_shape = (3, args.shape[0], args.shape[0])
elif (len(args.shape) == 2):
input_shape = ((3,) + tuple(args.shape))
els... |
class MultipleKVAction(argparse.Action):
'\n argparse action to split an argument into KEY=VALUE form\n on the first = and append to a dictionary. List options should\n be passed as comma separated values, i.e KEY=V1,V2,V3\n '
def _parse_int_float_bool(self, val):
try:
return ... |
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--out', help='output result file in pickle format')
parser.add_... |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show), 'Please specify at least one operation (save/eval/format/show the results) with the argument "--out", "--eval", "--format_only" or "--show"'
if (args.eval and args.format_only):
raise ValueError('--eva... |
def coco_eval_with_return(result_files, result_types, coco, max_dets=(100, 300, 1000)):
for res_type in result_types:
assert (res_type in ['proposal', 'bbox', 'segm', 'keypoints'])
if mmcv.is_str(coco):
coco = COCO(coco)
assert isinstance(coco, COCO)
eval_results = {}
for res_type ... |
def voc_eval_with_return(result_file, dataset, iou_thr=0.5, logger='print', only_ap=True):
det_results = mmcv.load(result_file)
annotations = [dataset.get_ann_info(i) for i in range(len(dataset))]
if (hasattr(dataset, 'year') and (dataset.year == 2007)):
dataset_name = 'voc07'
else:
da... |
def single_gpu_test(model, data_loader, show=False):
model.eval()
results = []
dataset = data_loader.dataset
prog_bar = mmcv.ProgressBar(len(dataset))
for (i, data) in enumerate(data_loader):
with torch.no_grad():
result = model(return_loss=False, rescale=(not show), **data)
... |
def multi_gpu_test(model, data_loader, tmpdir=None):
model.eval()
results = []
dataset = data_loader.dataset
(rank, world_size) = get_dist_info()
if (rank == 0):
prog_bar = mmcv.ProgressBar(len(dataset))
for (i, data) in enumerate(data_loader):
with torch.no_grad():
... |
def collect_results(result_part, size, tmpdir=None):
(rank, world_size) = get_dist_info()
if (tmpdir is None):
MAX_LEN = 512
dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda')
if (rank == 0):
tmpdir = tempfile.mkdtemp()
tmpdir = torch.tens... |
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('--out', help='output result file')
parser.add_argument('--corruptions', t... |
def main():
args = parse_args()
assert (args.out or args.show), 'Please specify at least one operation (save or show the results) with the argument "--out" or "--show"'
if ((args.out is not None) and (not args.out.endswith(('.pkl', '.pickle')))):
raise ValueError('The output file must be a pkl fil... |
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('--resume_from', help='the checkpoint file to resume from')
... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
if (args.resume_from is not None):
cfg.resume_from = args.resume_from
... |
def convert(in_file, out_file):
'Convert keys in checkpoints.\n\n There can be some breaking changes during the development of mmdetection,\n and this tool is used for upgrading checkpoints trained with old versions\n to the latest one.\n '
checkpoint = torch.load(in_file)
in_state_dict = chec... |
def main():
parser = argparse.ArgumentParser(description='Upgrade model version')
parser.add_argument('in_file', help='input checkpoint file')
parser.add_argument('out_file', help='output checkpoint file')
args = parser.parse_args()
convert(args.in_file, args.out_file)
|
@HEADS.register_module
class SepcFreeAnchorRetinaHead(FreeAnchorRetinaHead):
def forward_single(self, x):
if (not isinstance(x, list)):
x = [x, x]
cls_feat = x[0]
reg_feat = x[1]
for cls_conv in self.cls_convs:
cls_feat = cls_conv(cls_feat)
for reg_... |
@HEADS.register_module
class SepcRetinaHead(RetinaHead):
def forward_single(self, x):
if (not isinstance(x, list)):
x = [x, x]
cls_feat = x[0]
reg_feat = x[1]
for cls_conv in self.cls_convs:
cls_feat = cls_conv(cls_feat)
for reg_conv in self.reg_con... |
@NECKS.register_module
class SEPC(nn.Module):
def __init__(self, in_channels=([256] * 5), out_channels=256, num_outs=5, pconv_deform=False, lcconv_deform=False, iBN=False, Pconv_num=4):
super(SEPC, self).__init__()
assert isinstance(in_channels, list)
self.in_channels = in_channels
... |
class PConvModule(nn.Module):
def __init__(self, in_channels=256, out_channels=256, kernel_size=[3, 3, 3], dilation=[1, 1, 1], groups=[1, 1, 1], iBN=False, part_deform=False):
super(PConvModule, self).__init__()
self.iBN = iBN
self.Pconv = nn.ModuleList()
self.Pconv.append(sepc_co... |
def iBN(fms, bn):
sizes = [p.shape[2:] for p in fms]
(n, c) = (fms[0].shape[0], fms[0].shape[1])
fm = torch.cat([p.view(n, c, 1, (- 1)) for p in fms], dim=(- 1))
fm = bn(fm)
fm = torch.split(fm, [(s[0] * s[1]) for s in sizes], dim=(- 1))
return [p.view(n, c, s[0], s[1]) for (p, s) in zip(fm, s... |
class sepc_conv(DeformConv):
def __init__(self, *args, part_deform=False, **kwargs):
super(sepc_conv, self).__init__(*args, **kwargs)
self.part_deform = part_deform
if self.part_deform:
self.conv_offset = nn.Conv2d(self.in_channels, (((self.deformable_groups * 2) * self.kernel... |
class MultipleKVAction(argparse.Action):
'\n argparse action to split an argument into KEY=VALUE form\n on the first = and append to a dictionary. List options should\n be passed as comma separated values, i.e KEY=V1,V2,V3\n '
def _parse_int_float_bool(self, val):
try:
return ... |
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--out', help='output result file in pickle format')
parser.add_... |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show), 'Please specify at least one operation (save/eval/format/show the results) with the argument "--out", "--eval", "--format_only" or "--show"'
if (args.eval and args.format_only):
raise ValueError('--eva... |
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('--resume_from', help='the checkpoint file to resume from')
... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
if (args.resume_from is not None):
cfg.resume_from = args.resume_from
... |
def generate_previews():
gcoll = avt_preview_collections['thumbnail_previews']
image_location = gcoll.images_location
enum_items = []
gallery = ['dress01.jpg', 'dress02.jpg', 'dress03.jpg', 'dress04.jpg', 'dress05.jpg', 'dress06.jpg', 'glasses01.jpg', 'glasses02.jpg', 'hat01.jpg', 'hat02.jpg', 'hat03.... |
def update_weights(self, context):
global mAvt
if (mAvt.body is not None):
obj = mAvt.body
else:
reload_avatar()
mAvt.val_breast = self.val_breast
mAvt.val_torso = self.val_torso
mAvt.val_hips = (- self.val_hips)
mAvt.val_armslegs = self.val_limbs
mAvt.val_weight = (- s... |
def load_model_from_blend_file(filename):
with bpy.data.libraries.load(filename) as (data_from, data_to):
data_to.objects = [name for name in data_from.objects]
for obj in data_to.objects:
bpy.context.scene.collection.objects.link(obj)
|
def reload_avatar():
global mAvt
mAvt.load_shape_model()
mAvt.eyes = bpy.data.objects['Avatar:High-poly']
mAvt.body = bpy.data.objects['Avatar:Body']
mAvt.skel = bpy.data.objects['Avatar']
mAvt.armature = bpy.data.armatures['Avatar']
mAvt.skel_ref = motion_utils.get_rest_pose(mAvt.skel, mA... |
class AVATAR_OT_LoadModel(bpy.types.Operator):
bl_idname = 'avt.load_model'
bl_label = 'Load human model'
bl_description = 'Loads a parametric naked human model'
def execute(self, context):
global mAvt
global avt_path
scn = context.scene
obj = context.active_object
... |
class AVATAR_OT_SetBodyShape(bpy.types.Operator):
bl_idname = 'avt.set_body_shape'
bl_label = 'Set Body Shape'
bl_description = 'Set Body Shape'
def execute(self, context):
global mAvt
obj = mAvt.body
cp_vals = obj.data.copy()
mAvt.np_mesh_prev = mAvt.read_verts(cp_val... |
class AVATAR_OT_ResetParams(bpy.types.Operator):
bl_idname = 'avt.reset_params'
bl_label = 'Reset Parameters'
bl_description = 'Reset original parameters of body shape'
def execute(self, context):
global mAvt
obj = bpy.data.objects['Avatar:Body']
cp_vals = obj.data.copy()
... |
class AVATAR_PT_LoadPanel(bpy.types.Panel):
bl_idname = 'AVATAR_PT_LoadPanel'
bl_label = 'Load model'
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Avatar'
bpy.types.Object.val_breast = FloatProperty(name='Breast Size', description='Breasts Size', default=0, min=0.0, max=1.0, ... |
class AVATAR_OT_CreateStudio(bpy.types.Operator):
bl_idname = 'avt.create_studio'
bl_label = 'Create Studio'
bl_description = 'Set up a lighting studio for high quality renderings'
def execute(self, context):
global avt_path
dressing.load_studio(avt_path)
return {'FINISHED'}
|
class AVATAR_OT_WearCloth(bpy.types.Operator):
bl_idname = 'avt.wear_cloth'
bl_label = 'Wear Cloth'
bl_description = 'Dress human with selected cloth'
def execute(self, context):
global avt_path
scn = context.scene
obj = context.active_object
iconname = bpy.context.sce... |
class AVATAR_PT_DressingPanel(bpy.types.Panel):
bl_idname = 'AVATAR_PT_DressingPanel'
bl_label = 'Dress Human'
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Avatar'
def draw(self, context):
layout = self.layout
obj = context.object
scn = context.scene
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.