def test(): # get device device = get_device(0) # load net num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) mean = config.MEANS cfg = config.voc_ab if args.version == 'fcos_lite': from models.fcos_lite import FCOS_LITE net = FCOS_LITE(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False) print('Let us test FCOS-LITE on the VOC0712 dataset ......') net.load_state_dict(torch.load(args.trained_model, map_location='cuda')) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean), thresh=args.visual_threshold)
def main(trained_model): # load net num_classes = len(labelmap) + 1 # +1 for background net = build_ssd('test', 300, num_classes) # print(net) net = net.cuda() # initialize SSD net.load_state_dict(torch.load(trained_model)) # resume_ckpt(trained_model,net) net.eval() print('Finished loading model!') # load data dataset = VOCDetection(args.voc_root, [('2007', set_type)], BaseTransform(300, dataset_mean), VOCAnnotationTransform()) dataset = COCO if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, dataset, BaseTransform(net.size, dataset_mean), args.top_k, 300, thresh=args.confidence_threshold)
def test(): # get device if args.cuda: print('use cuda') cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) cfg = config.voc_cfg if args.version == 'centernet': from models.centernet import CenterNet net = CenterNet(device, input_size=cfg['min_dim'], num_classes=num_classes) net.load_state_dict(torch.load(args.trained_model, map_location=device)) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test(): # get device device = get_device(0) # load net num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) mean = config.MEANS cfg = config.voc_ab if args.version == 'yolo_v2': net = myYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=config.ANCHOR_SIZE) print('Let us test yolo-v2 on the VOC0712 dataset ......') elif args.version == 'yolo_v3': from models.yolo_v3 import myYOLOv3 net = myYOLOv3(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=config.MULTI_ANCHOR_SIZE) net.load_state_dict(torch.load(args.trained_model, map_location='cuda')) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean), thresh=args.visual_threshold)
def evaluate(model, save_folder, cuda, top_k, im_size=320, thresh=0.001, dataset_mean=((104, 117, 123))): model.phase = 'test' model.eval() dataset = VOCDetection(args.voc_root, BaseTransform(im_size, dataset_mean), VOCAnnotationTransform(), phase='valid') map = eval_net(save_folder, model, cuda, dataset, BaseTransform(im_size, dataset_mean), top_k, im_size, thresh=thresh) return map
def test(): # get device if args.cuda: cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net num_classes = 80 if args.dataset == 'COCO_val': cfg = config.coco_af input_size = cfg['min_dim'] testset = COCODataset(data_dir=args.dataset_root, json_file='instances_val2017.json', name='val2017', img_size=cfg['min_dim'][0], debug=args.debug) elif args.dataset == 'COCO_test-dev': cfg = config.coco_af input_size = cfg['min_dim'] testset = COCODataset(data_dir=args.dataset_root, json_file='image_info_test-dev2017.json', name='test2017', img_size=cfg['min_dim'][0], debug=args.debug) elif args.dataset == 'VOC': cfg = config.voc_af input_size = cfg['min_dim'] testset = VOCDetection(VOC_ROOT, [('2007', 'test')], None, VOCAnnotationTransform()) # build model if args.version == 'yolo': from models.yolo import myYOLO net = myYOLO(device, input_size=input_size, num_classes=num_classes, trainable=False) print('Let us test YOLO on the %s dataset ......' % (args.dataset)) else: print('Unknown Version !!!') exit() net.load_state_dict(torch.load(args.trained_model, map_location=device)) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test(): # get device if args.cuda: print('use cuda') cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) cfg = config.voc_ab if args.version == 'yolo_v2': from models.yolo_v2 import myYOLOv2 net = myYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.ANCHOR_SIZE) print('Let us test yolo-v2 on the VOC0712 dataset ......') elif args.version == 'yolo_v3': from models.yolo_v3 import myYOLOv3 net = myYOLOv3(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.MULTI_ANCHOR_SIZE) elif args.version == 'slim_yolo_v2': from models.slim_yolo_v2 import SlimYOLOv2 net = SlimYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.ANCHOR_SIZE) print('Let us test slim-yolo-v2 on the VOC0712 dataset ......') elif args.version == 'tiny_yolo_v3': from models.tiny_yolo_v3 import YOLOv3tiny net = YOLOv3tiny(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.TINY_MULTI_ANCHOR_SIZE) print('Let us test tiny-yolo-v3 on the VOC0712 dataset ......') net.load_state_dict(torch.load(args.trained_model, map_location=device)) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test_voc(): # load net num_classes = len(CUSTOM_CLASSES if args.use_custom else VOC_CLASSES ) + 1 # +1 background net = build_ssd('test', 300, num_classes) # initialize SSD if args.cuda: net.load_state_dict( torch.load(args.trained_model, map_location=torch.device('cuda'))) else: net.load_state_dict( torch.load(args.trained_model, map_location=torch.device('cpu'))) net.eval() print('Finished loading model!') # load data if args.use_custom: custom_class_to_ind = dict( zip(CUSTOM_CLASSES, range(len(CUSTOM_CLASSES)))) testset = VOCDetection(root=args.voc_root, image_sets=[('2019', 'test')], dataset_name='VOC2019', transform=BaseTransform(300, MEANS), target_transform=VOCAnnotationTransform( class_to_ind=custom_class_to_ind)) else: testset = VOCDetection(root=args.voc_root, image_sets=[('2007', 'test')], dataset_name='VOC0712', transform=BaseTransform(300, MEANS), target_transform=VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_random_img(net, args.cuda, testset, BaseTransform(300, MEANS), thresh=args.visual_threshold)
def draw_anchor(ImgPath, AnnoPath, save_path): # load data testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) imagelist = os.listdir(ImgPath) cnt = 5 #for image in imagelist: for i in range(cnt): image, annotation = testset.pull_anno(i) #image_pre, ext = os.path.splitext(image) imgfile = ImgPath + image + '.png' xmlfile = AnnoPath + 'test' + image + '.xml' #xmlfile = AnnoPath + image + '.xml' #xmlfile = AnnoPath +image + '.xml' # print(image) # 打开xml文档 DOMTree = xml.dom.minidom.parse(xmlfile) # 得到文档元素对象 collection = DOMTree.documentElement # 读取图片 img = cv.imread(imgfile) filenamelist = collection.getElementsByTagName("filename") filename = filenamelist[0].childNodes[0].data print(filename) # 得到标签名为object的信息 objectlist = collection.getElementsByTagName("object") for objects in objectlist: # 每个object中得到子标签名为name的信息 namelist = objects.getElementsByTagName('name') name_idx = 0 bndbox = objects.getElementsByTagName('bndbox') # print(bndbox) for box in bndbox: x1_list = box.getElementsByTagName('xmin') x1 = int(x1_list[0].childNodes[0].data) y1_list = box.getElementsByTagName('ymin') y1 = int(y1_list[0].childNodes[0].data) x2_list = box.getElementsByTagName('xmax') #注意坐标,看是否需要转换 x2 = int(x2_list[0].childNodes[0].data) y2_list = box.getElementsByTagName('ymax') y2 = int(y2_list[0].childNodes[0].data) cv.rectangle(img, (x1, y1), (x2, y2), (0, 165, 255), thickness=2) # 通过此语句得到具体的某个name的值 objectname = namelist[name_idx].childNodes[0].data cv.putText(img, objectname, (x1, y1), cv.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 255), thickness=1) name_idx += 1 #cv.imshow(filename, img)#这个要安装Xmanager才可以看 cv.imwrite(save_path + '/' + filename, img) #save picture
def test_voc(): # load net num_classes = len(VOC_CLASSES) + 1 net = build_ssd('test', 300, num_classes) net.load_state_dict(torch.load(args.trained_model)) net.eval() print('Finished loading model!') # load data testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def test(): # get device if args.cuda: print('use cuda') cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net num_classes = 80 if args.dataset == 'COCO': cfg = config.coco_ab testset = COCODataset( data_dir=args.dataset_root, json_file='instances_val2017.json', name='val2017', img_size=cfg['min_dim'][0], debug=args.debug) elif args.dataset == 'VOC': cfg = config.voc_ab testset = VOCDetection(VOC_ROOT, [('2007', 'test')], None, VOCAnnotationTransform()) if args.version == 'yolo_v2': from models.yolo_v2 import myYOLOv2 net = myYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.ANCHOR_SIZE_COCO) print('Let us test yolo-v2 on the MSCOCO dataset ......') elif args.version == 'yolo_v3': from models.yolo_v3 import myYOLOv3 net = myYOLOv3(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.MULTI_ANCHOR_SIZE_COCO) elif args.version == 'slim_yolo_v2': from models.slim_yolo_v2 import SlimYOLOv2 net = SlimYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.ANCHOR_SIZE_COCO) elif args.version == 'tiny_yolo_v3': from models.tiny_yolo_v3 import YOLOv3tiny net = YOLOv3tiny(device, input_size=cfg['min_dim'], num_classes=num_classes, anchor_size=config.TINY_MULTI_ANCHOR_SIZE_COCO) net.load_state_dict(torch.load(args.trained_model, map_location='cuda')) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test(): # get device device = get_device(0) # load net num_classes = 80 anchor_size = config.ANCHOR_SIZE_COCO if args.dataset == 'COCO': cfg = config.coco_ab testset = COCODataset( data_dir=args.dataset_root, json_file='instances_val2017.json', name='val2017', img_size=cfg['min_dim'][0], debug=args.debug) mean = config.MEANS elif args.dataset == 'VOC': cfg = config.voc_ab testset = VOCDetection(VOC_ROOT, [('2007', 'test')], None, VOCAnnotationTransform()) mean = config.MEANS if args.version == 'yolo_v2': from models.yolo_v2 import myYOLOv2 net = myYOLOv2(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=anchor_size) print('Let us test yolo-v2 on the MSCOCO dataset ......') elif args.version == 'yolo_v3': from models.yolo_v3 import myYOLOv3 net = myYOLOv3(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=anchor_size) elif args.version == 'tiny_yolo_v2': from models.tiny_yolo_v2 import YOLOv2tiny net = YOLOv2tiny(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=config.ANCHOR_SIZE) elif args.version == 'tiny_yolo_v3': from models.tiny_yolo_v3 import YOLOv3tiny net = YOLOv3tiny(device, input_size=cfg['min_dim'], num_classes=num_classes, trainable=False, anchor_size=config.MULTI_ANCHOR_SIZE) net.load_state_dict(torch.load(args.trained_model, map_location='cuda')) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean), thresh=args.visual_threshold)
def test_voc(): num_classes = len(VOC_CLASSES) + 1 net = build_ssd('test', 300, num_classes) net.eval() print('Finished loading model!') testset = VOCDetection(opt.DATASETS.ROOT, ['test'], BaseTransform(300, opt.DATASETS.MEANS), VOCAnnotationTransform()) if opt.DEVICE: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def read_gt(voc_dir): set_type = 'test' dataset_mean = (104, 117, 123) dataset = VOCDetection(voc_dir, [('2007', set_type)], BaseTransform(300, dataset_mean), VOCAnnotationTransform()) num_images = len(dataset) gt_bbox = [[[] for _ in range(num_images)] for _ in range(len(labelmap)+1)] for i in range(len(dataset)): im_name, gt = dataset.pull_anno(i) for box_conf in gt: gt_bbox[box_conf[4]+1][i].append(box_conf[:4]) return gt_bbox, num_images
def test(): # load net num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) mean = config.MEANS if args.version == 'yolo_v1': cfg = config.voc_af net = myYOLOv1(device, input_size=cfg['min_dim'], num_classes=num_classes, conf_thresh=0.01, trainable=False, backbone=args.backbone).to(device) elif args.version == 'yolo_v1_ms': cfg = config.voc_af net = myYOLOv1(device, input_size=cfg['min_dim'], num_classes=num_classes, conf_thresh=0.01, trainable=False, backbone=args.backbone) elif args.version == 'yolo_anchor': cfg = config.voc_ab net = myYOLOv1(device, input_size=cfg['min_dim'], num_classes=num_classes, conf_thresh=0.01, trainable=False, anchor_size=config.ANCHOR_SIZE, backbone=args.backbone).to(device) net.load_state_dict(torch.load(args.trained_model)) net.eval() print('Finished loading model!') net = net.to(device) # evaluation test_net(net, args.cuda, testset, BaseTransform(net.input_size, mean), thresh=args.visual_threshold)
def main(): target_domain = 'watercolor' set_type = 'train' json_path = 'outputs/VGG-voc-watercolor-styles-pseudolabel-nopreservecolour/pslabels.json' root = '../Datasets/Clipart-Watercolor-Comic/{}'.format(target_domain) _imgpath = osp.join('%s', 'JPEGImages', '%s.jpg') _annopath = osp.join('%s', 'Annotations', '%s.xml') with open(json_path) as json_file: data = json.load(json_file) output_path = osp.join(osp.dirname(json_path), 'ps_images') if not osp.exists(output_path): os.makedirs(output_path) target_transform = VOCAnnotationTransform() for img_id in data: image = Image.open(_imgpath % (root, img_id)) width, height = image.size # psuedolabel ps_anno = data[img_id] # groundtruth anno gt_annos = ET.parse(_annopath % (root, img_id)).getroot() gt_annos = target_transform(gt_annos, width, height) int_annos = [] for gt_anno in gt_annos: new_anno = [ gt_anno[0] * width, gt_anno[1] * height, gt_anno[2] * width, gt_anno[3] * height, gt_anno[4] ] new_anno = [int(round(i)) for i in new_anno] int_annos.append(new_anno) gt_anno = int_annos ps_image = draw_annos(image.copy(), ps_anno, colour=(0, 0, 255)) gt_image = draw_annos(image.copy(), gt_anno, colour=(0, 255, 0)) export_image([ps_image, gt_image], output_path=osp.join(output_path, img_id + '.png')) # raise NotImplementedError pass
def pseudolabel_trainer(model, args, output_dir, stylized_root, num_classes): # check output directory print('Generating Pseudolabels...') dataset_mean = (104, 117, 123) pseudo_dataset = datasets.ArtDetection(root=args.style_root, transform=BaseTransform(300, dataset_mean), target_domain=args.target_domain, set_type='train', target_transform=VOCAnnotationTransform()) pslabels = pseudolabel.pseudolabel(model, pseudo_dataset, args.pthresh, overlap_thresh=args.overlap_thresh) print("Saving pseudolabels JSON file to {}...".format(os.path.join(output_dir, 'pslabels.json'))) with open(os.path.join(output_dir, 'pslabels.json'), 'w') as fp: json.dump(pslabels, fp) # Source, pseudolablled and validation datasets sc_loader, ps_loader, val_data = get_dataloaders(args, stylized_root, pslabels) # training criterion for source data ssd_criterion = MultiBoxLoss(num_classes, 0.5, True, 0, True, 3, 0.5, False, cfg, torch.cuda.is_available(), neg_thresh=0.) style_criterion = FeatureConsistency() optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) # training criterion for pseudolabelled example -- negative threshold adusted neg_thresh = args.nthresh ps_criterion = MultiBoxLoss(num_classes, 0.5, True, 0, True, 3, 0.5, False, cfg, torch.cuda.is_available(), neg_thresh=neg_thresh) ps_pair = (ps_loader, ps_criterion) # dataloader and ssd criterion for pseudolabelled image pairs sc_pair = (sc_loader, ssd_criterion) # dataloader and ssd criterion for source image pairs if not os.path.exists(output_dir): os.makedirs(output_dir) # Ensure datasets are fully preprocessed # preprocess.check_preprocess(args, sc_loader, stylized_root, pseudolabel=False) preprocess.check_preprocess(args, ps_loader, stylized_root, args.stage2_its, pseudolabel=True) # print("Setting max iterations to 5000 for pseudolabel training.") model, best_model, best_map, accuracy_history = train(model, ps_pair, sc_pair, optimizer, val_data, args.stage2_its, output_dir, log_freq=args.log_freq, test_freq=args.test_freq, aux_criterion=style_criterion) report_and_save(model, best_model, best_map, accuracy_history, output_dir, args.stage2_its, pseudolabel=True) return model
def test(): if args.cuda: print('use cuda') cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net cfg = config.voc_af input_size = cfg['min_dim'] num_classes = len(VOC_CLASSES) testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) # build model if args.version == 'yolo': from models.yolo import myYOLO net = myYOLO(device, input_size=input_size, num_classes=num_classes, trainable=False) print('Let us test yolo on the VOC0712 dataset ......') else: print('Unknown Version !!!') exit() net.load_state_dict(torch.load(args.trained_model, map_location=device)) net.eval() print('Finished loading model!') net = net.to(device) # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test_voc(): # Initialise the class net = SDDOpenVINO() # Set Probability threshold for detections prob_threshold = args.visual_threshold #Load the model through `net` device = "GPU" if args.gpu else "CPU" net.load_model(args.model, device=device) print('Finished loading model!') # load data testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) # evaluation test_net(args.save_folder, net, args.gpu, testset, thresh=args.visual_threshold)
def test_voc(cfg): # load net num_classes = len(VOC_CLASSES) + 1 # +1 background net = build_ssd('test', cfg['min_dim'], cfg) # initialize SSD net.load_state_dict(torch.load(args.trained_model)) net.eval() print('Finished loading model!') # load data testset = VOCDetection(data_root, [('2012', 'person_val')], None, VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(save_path, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def eval(): # load net num_classes = len(labelmap) + 1 # +1 for background root_dir = os.path.dirname(args.trained_model) model_name = os.path.basename(args.trained_model) # load data if args.dataset == 'VOC': dataset = VOCDetection(args.root_dir, [('2007', set_type)], BaseTransform(args.input_size, dataset_mean), VOCAnnotationTransform(), only_test=True) else: dataset = COCODetection(args.root_dir, 'test-dev2017', BaseTransform(args.input_size, dataset_mean), COCOAnnotationTransform()) net = build_net('test', args.input_size, num_classes) state_dict = torch.load(args.trained_model) # create new OrderedDict that does not contain `module.` new_state_dict = OrderedDict() for k, v in state_dict.items(): head = k[:7] if head == 'module.': name = k[7:] # remove `module.` else: name = k if 'base' in name: name = name.replace('base', 'vgg') new_state_dict[name] = v net.load_state_dict(new_state_dict) net.eval() print('Finished loading model:{}'.format(args.trained_model)) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(root_dir, net, dataset, model_name, retest=False)
def test_voc(): # load net num_classes = len(VOC_CLASSES) + 1 # +1 background net = build_ssd('test', 300, num_classes) # initialize SSD net.load_state_dict( torch.load(args.trained_model, map_location=torch.device('cpu'))) net.eval() print('Finished loading model!') # load data testset = VOCDetection(args.voc_root, [('selfie', 'val')], None, VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def test_voc(): # load net num_classes = len(VOC_CLASSES) + 1 # +1 background net = build_ssd('test', 300, num_classes) # initialize SSD net.load_state_dict(torch.load(args.trained_model)) net.eval() print('Finished loading model!') # load data testset = VOCDetection(args.dataset_root, [('2007', 'test')], None, VOCAnnotationTransform()) # GPU support if available net = net.to(device) if args.cuda: cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def test_voc(): # load net num_classes = len(VOC_CLASSES) + 1 # +1 background net = build_ssd('test', 300, num_classes) # initialize SSD net.load_state_dict(torch.load('weights/ssd_300_VOC0712.pth')) # s_model = torch.jit.trace(net, torch.randn(1, 3, 300, 300)) # torch.jit.save(s_model, 'ssd.pt') net.eval() print('Finished loading model!') # load data testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, testset, BaseTransform(net.size, (104, 117, 123)), thresh=args.visual_threshold)
def test_voc(): # load net num_classes = len(VOC_CLASSES) + 1 # +1 background【这里我觉得也不应该加1】 net = build_ssd('test', 300, num_classes) # initialize SSD net.load_state_dict(torch.load(args.trained_model)) # 在创建的网络中添加前面训练过的权重系数 net.eval() # 开始机进行eval()模式 print('Finished loading model!') # load data testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) # 将 第二个参数的默认值改变成【要选用的数据集】 if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation # #输入参数:【VOC数据集root,网络,cuda,输入的测试数据,预处理函数, 阈值】 test_net( args.save_folder, # VOC数据集root net, # 网络 args.cuda, # cuda testset, # 输入的测试数据 BaseTransform(net.size, (104, 117, 123)), # 预处理函数 thresh=args.visual_threshold # 阈值 )
def test(): # get device if args.cuda: print('use cuda') cudnn.benchmark = True device = torch.device("cuda") else: device = torch.device("cpu") # load net num_classes = 80 if args.dataset == 'COCO': cfg = config.coco_cfg testset = COCODataset( data_dir=args.dataset_root, json_file='instances_val2017.json', name='val2017', img_size=cfg['min_dim'][0], debug=args.debug) elif args.dataset == 'VOC': cfg = config.voc_cfg testset = VOCDetection(VOC_ROOT, [('2007', 'test')], None, VOCAnnotationTransform()) if args.version == 'centernet': from models.centernet import CenterNet net = CenterNet(device, input_size=cfg['min_dim'], num_classes=num_classes) net.load_state_dict(torch.load(args.trained_model, map_location='cuda')) net.to(device).eval() print('Finished loading model!') # evaluation test_net(net, device, testset, BaseTransform(net.input_size, mean=(0.406, 0.456, 0.485), std=(0.225, 0.224, 0.229)), thresh=args.visual_threshold)
def test_voc(): # load net num_classes = 1 + 1 # +1 background print(num_classes) net = build_ssd('test', 300, num_classes) # initialize SSD model = '/home/zrj/Object_detection/hgo3.0/weights/ssd3001020_COCO_5000.pth' net.load_state_dict(torch.load(model)) net.eval() print('Finished loading model!') testset = VOCDetection(args.voc_root, [('2007', 'test')], None, VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True test_net(args.save_folder, net, args.cuda, testset, BaseTransform(500, (0, 0, 0)), thresh=args.visual_threshold)
import numpy as np import cv2 if torch.cuda.is_available(): torch.set_default_tensor_type('torch.cuda.FloatTensor') from ssd import build_ssd # SSDネットワークの定義と重みファイルのロード net = build_ssd('test', 300, 21) net.load_weights('./weights/BCCD.pth') from matplotlib import pyplot as plt from data import VOCDetection, VOC_ROOT, VOCAnnotationTransform # BCCD_test 読み込み testset = VOCDetection(VOC_ROOT, [('BCCD', 'test')], None, VOCAnnotationTransform()) img_id = 25 image = testset.pull_image(img_id) # テスト画像の表示 rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.figure(figsize=(10,10)) plt.imshow(rgb_image) plt.show() x = cv2.resize(image, (300, 300)).astype(np.float32) # 300*300にリサイズ x -= (104.0, 117.0, 123.0) x = x.astype(np.float32) x = x[:, :, ::-1].copy() x = torch.from_numpy(x).permute(2, 0, 1) # [300,300,3] → [3,300,300] xx = Variable(x.unsqueeze(0)) # [3,300,300] → [1,3,300,300]
def evaluate_detections(box_list, output_dir, dataset): write_voc_results_file(box_list, dataset) do_python_eval(output_dir) if __name__ == '__main__': # load net num_classes = len(labelmap) + 1 # +1 for background net = build_ssd('test', 300, num_classes) # initialize SSD net.load_state_dict(torch.load(args.trained_model, map_location='cpu')) net.eval() print('Finished loading model!') # load data dataset = VOCDetection(args.voc_root, [('2007', set_type)], BaseTransform(300, dataset_mean), VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, args.cuda, dataset, BaseTransform(net.size, dataset_mean), args.top_k, 300, thresh=args.confidence_threshold)
net = torch.load( 'model/KDGAN_1F1D/T_var/prune_10/10epoch/lr_0508/20200329/ssd300_VOC_C64_0_Epoch20.pkl' ) # net = net.module # state = torch.load('./weights/ssd300_COCO_85000.pth') # net.load_state_dict(state) net.phase = 'test' net.softmax = nn.Softmax(dim=-1) net.detect = Detect(num_classes, 0, 200, 0.01, 0.45) # net.load_state_dict(torch.load(args.trained_model)) net.eval() print('Finished loading model!') # load data dataset = VOCDetection(args.voc_root, [('2007', set_type)], transform=BaseTransform(300, dataset_mean), target_transform=VOCAnnotationTransform()) if args.cuda: net = net.cuda() cudnn.benchmark = True # evaluation test_net(args.save_folder, net, 'cuda:0', dataset, BaseTransform(net.size, dataset_mean), args.top_k, 300, thresh=args.confidence_threshold) """