def demo(): img = './demo/000492_1.jpg' result = inference_detector(model, img) print(result[1], type(result[1]), len(result[1])) print(result[1] == []) #print(len(result)) show_result_pyplot(model, img, result, score_thr=0.3)
def main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image model_result = inference_detector(model, args.img) for i, anchor_set in enumerate(model_result): anchor_set = anchor_set[anchor_set[:, 4] >= 0.5] model_result[i] = anchor_set # show the results show_result_pyplot(model, args.img, model_result, score_thr=args.score_thr, title='pytorch_result') url = 'http://' + args.inference_addr + '/predictions/' + args.model_name with open(args.img, 'rb') as image: response = requests.post(url, image) server_result = parse_result(response.json(), model.CLASSES) show_result_pyplot(model, args.img, server_result, score_thr=args.score_thr, title='server_result') for i in range(len(model.CLASSES)): assert np.allclose(model_result[i], server_result[i])
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) save_pth = os.path.join(args.img, args.config.split('/')[-1].split('.')[0]) os.mkdir(save_pth) img_list = os.listdir(args.img) for im_str in img_list: if im_str.endswith('.jpg'): _im = os.path.join(args.img, im_str) img = cv2.imread(_im, cv2.IMREAD_UNCHANGED) # test a single image try: result = inference_detector(model, img) show_result_pyplot(model, _im, result, im_str, save_pth, score_thr=args.score_thr) except Exception as e: print('[error]', _im) pass
def testinference(config, checkpoint): #Basemmdetection='/Developer/3DObject/mmdetection/' #config = Basemmdetection+'configs/faster_rcnn/faster_rcnn_r101_fpn_2x_coco.py' # Setup a checkpoint file to load #checkpoint = Basemmdetection+'checkpoints/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth' # initialize the detector # model1 = init_detector(config, checkpoint, device='cuda:0') model1 = mymm2d_init_detector(config, checkpoint, device='cuda:0') img = '/DATA5T/Dataset/WaymoKitti/4c_train5678/training/image_0/000000.png' result = inference_detector( model1, img ) #result (tuple[list] or list): The detection result, can be either (bbox, segm) or just bbox. show_result_pyplot(model1, img, result, score_thr=0.3) bbox_result = result bboxes = np.vstack(bbox_result) labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) print(bboxes) print(type(bboxes)) print(type(labels))
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.5, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image img_list = os.listdir(args.img) for i, img in enumerate(img_list): # if i < 6: # continue if i == 109: break if i not in [34, 36, 64, 108]: continue img = os.path.join(args.img, img) result = inference_detector(model, img) # show the results show_result_pyplot(model, img, result, score_thr=args.score_thr, name=i + 1)
def main(): parser = ArgumentParser() parser.add_argument('--img', default='/data/datasets/PANDA/split1/IMG_01_01.jpg', help='Image file') parser.add_argument( '--config', default= 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py', help='Config file') parser.add_argument( '--checkpoint', default= '/data/models/mmdetection/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
def box_check(img, device='cpu'): flip = False det_config = '/home/filipkr/Documents/xjob/mmpose/mmdetection/' +\ 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' det_model = '/home/filipkr/Documents/xjob/mmpose/mmdetection/' +\ 'checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' det_model = init_detector(det_config, det_model, device=device) print('loaded detection model') det_results = inference_detector(det_model, img) # bbox = det_results[0] bbox = np.expand_dims(np.array(det_results[0])[0, :], axis=0) bbox[0, 2:4] = bbox[0, 2:4] + 100 # print(bbox) if abs(bbox[0, 0] - bbox[0, 2]) > abs(bbox[0, 1] - bbox[0, 3]): flip = True bbox[0, 1] -= 100 bbox = [[bbox[0, 1], bbox[0, 0], bbox[0, 3], bbox[0, 2], bbox[0, 4]]] print('frames will be flipped') else: bbox[0, 0] -= 100 print('bounding box found: {0}'.format(bbox)) show_result_pyplot(det_model, img, det_results) return bbox, flip
def main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.5, help='bbox score threshold') parser.add_argument('--output-img', type=str, default='output.jpg', help='output image') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score - thr, output_img=args.output - img)
def main(): args = parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device='cuda:0') # test a single image result = inference_detector(model, args.img_file) # show the results show_result_pyplot(model, args.img_file, result, out_file=args.out)
async def async_main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image tasks = asyncio.create_task(async_inference_detector(model, args.img)) result = await asyncio.gather(tasks) # show the results show_result_pyplot(model, args.img, result[0], score_thr=args.score_thr)
def main(): config = '/home/zhoufeipeng/code/vertex/configs/polygon/polyrnn_r50_fpn_1x_building.py' checkpoint = '/home/zhoufeipeng/code/vertex/work_dirs/polyrnn_r50_fpn_1x_building/latest.pth' device = 'cuda:0' score_thr = 0.6 img = '/home/zhoufeipeng/code/vertex/data/building/yunnan_small/val/JPEGImages/yunnan_small_32_0_512_4096.png' # build the model from a config file and a checkpoint file model = init_detector(config, checkpoint, device=device) # test a single image result = inference_detector(model, img) # show the results show_result_pyplot(model, img, result, score_thr=score_thr)
def main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr) # добавлено сохранение в файл model.show_result(args.img, result, score_thr=args.score_thr, font_size=5, out_file='result_.jpg')
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() hooks = {} # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) for name, module in model.named_modules(): print(name) print(module) if '1fpn_convs' in name and '.conv' in name: # if 'backbone.layer1.2.conv3' in name: # print(name) # print(module) hooks[name] = module.register_forward_hook(hook) # test a single image result = inference_detector(model, args.img) for name, module in model.named_modules(): if '2fpn_convs' in name and '.conv' in name: # if 'backbone.layer1.2.conv3' in name: out = module._value_hook[0].detach().cpu() # print(out) for i in range(128): plt.box(False) fig, axarr = plt.subplots() axarr.axis('off') axarr.imshow(out[i, :, :], cmap='gray', vmin=0, vmax=1) # plt.show() fig.patch.set_visible(False) fig.savefig('demo/nest94/' + name + str(i) + '.png') plt.close(fig) # show the results # res=filter(result) show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
def main(): config = './configs/faster_rcnn_r50_fpn_1x_coco.py' # download the checkpoint from model zoo and put it in `checkpoints/` # url: http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth checkpoint = './checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' device = 'cuda:0' image = '../Dataset/demo.jpg' score_thr = 0.3 # build the model from a config file and a checkpoint file model = init_detector(config, checkpoint=checkpoint, device=device) # test a single image result = inference_detector(model, image) # show the results show_result_pyplot(model, image, result, score_thr=score_thr)
def main(): parser = ArgumentParser() parser.add_argument('img_dir', help='Image dir') parser.add_argument('config_dir', help='Config dir') parser.add_argument('checkpoint_dir', help='Checkpoint dir') parser.add_argument('result_dir', help='result dir') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--score-thr', type=float, default=0.9, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config_dir, args.checkpoint_dir, device=args.device) # test some img select_result = [] for img_file in os.listdir(args.img_dir): print(img_file) img = args.img_dir + img_file result = inference_detector(model, img) # show the results result_pic = show_result_pyplot(model, img, result, score_thr=args.score_thr) plt.figure(figsize=(15, 10)) plt.imshow(mmcv.bgr2rgb(result_pic)) plt.title('result') plt.tight_layout() plt.savefig(args.result_dir + img_file)
def main(): parser = ArgumentParser() parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image root = "/data-tmp/coco2017/val2017/*.jpg" if os.path.exists("./res"): shutil.rmtree("./res") os.makedirs("./res", exist_ok=True) imgs = glob.glob(root) for img_path in tqdm(imgs[::10]): result = inference_detector(model, img_path) # show the results img = show_result_pyplot(model, img_path, result, score_thr=args.score_thr) cv2.imwrite("./res/{}".format(os.path.basename(img_path)), img)
def main(): parser = ArgumentParser() parser.add_argument('--img', help='Image file', default='images/woman_tee_half_jeans.jpg') parser.add_argument('--config', default='configs/fashion/mask_rcnn.py', help='Config file') parser.add_argument('--checkpoint', default='checkpoints/fashion_product_detector.pth', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.5, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results img, coordinates_list, label_txts = show_result_pyplot( model, args.img, result, score_thr=args.score_thr) print('products detected ', label_txts) #extract color scheme color_scheme = ColorScheme(args.img, coordinates_list).color_scheme print('color scheme is', color_scheme)
def main(): parser = ArgumentParser() parser.add_argument('--img', default='./000000008690.jpg',help='Image file') parser.add_argument('--config',default='../configs/fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py', help='Config file') parser.add_argument('--checkpoint',default='../checkpoint/fcos_r50_caffe_fpn_gn_1x_4gpu_20200218-7831950c.pth', help='Checkpoint file') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
def testinferencedetector(config, checkpoint): #Basemmdetection='/Developer/3DObject/mmdetection/' #config = Basemmdetection+'configs/faster_rcnn/faster_rcnn_r101_fpn_2x_coco.py' # Setup a checkpoint file to load #checkpoint = Basemmdetection+'checkpoints/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth' # initialize the detector # model1 = init_detector(config, checkpoint, device='cuda:0') model1 = mymm2d_init_detector(config, checkpoint, device='cuda:0') img = '/DATA5T/Dataset/WaymoKitti/4c_train5678/training/image_0/000010.png' #result = inference_detector(model1, img) #result (tuple[list] or list): The detection result, can be either (bbox, segm) or just bbox. result = myinferencedetector(model1, img) show_result_pyplot(model1, img, result, score_thr=0.3) bbox_result = result bboxes = np.vstack(bbox_result) labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) print(bboxes) #5,1, last column is the confidence score #xmin, ymin, xmax, ymax in pixels print(type(bboxes)) print(type(labels)) num_box = len(bboxes) newboxes = np.zeros((num_box, 4), dtype=float) newboxes[:, 0] = (bboxes[:, 0] + bboxes[:, 2]) / 2.0 #center_x newboxes[:, 1] = (bboxes[:, 1] + bboxes[:, 3]) / 2.0 #center_y newboxes[:, 2] = (bboxes[:, 2] - bboxes[:, 0]) #width newboxes[:, 3] = (bboxes[:, 3] - bboxes[:, 1]) # height # boxes[:, 0] = (pred_boxes[:, 3] + pred_boxes[:, 1]) * im_width / 2.0 # boxes[:, 1] = (pred_boxes[:, 2] + pred_boxes[:, 0]) * im_height / 2.0 # boxes[:, 2] = (pred_boxes[:, 3] - pred_boxes[:, 1]) * im_width # boxes[:, 3] = (pred_boxes[:, 2] - pred_boxes[:, 0]) * im_height pred_score = np.zeros((num_box, ), dtype=float) pred_score = bboxes[:, 4] return { 'boxes': newboxes, 'scores': pred_score, 'classes': labels, }
def mainTableDetector(imageName): # Load model config_file = '/home/keshav/workspace/wisflux/table-detect/table-detection-server/CascadeTabNet/Config/cascade_mask_rcnn_hrnetv2p_w32_20e.py' checkpoint_file = '/home/keshav/workspace/wisflux/table-detect/table-detection-server/CascadeTabNet/epoch_24.pth' model = init_detector(config_file, checkpoint_file, device='cuda:0') # Test a single image img = "/home/keshav/workspace/wisflux/table-detect/table-detection-server/pdfs/newfile/{}".format( imageName) # Run Inference result = inference_detector(model, img) print(result[0]) # Visualization results show_result_pyplot(img, result, ('Bordered', 'cell', 'Borderless'), score_thr=0.85) return result[0][0]
def main(): parser = ArgumentParser() # parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.000000001, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image # import pdb; # pdb.set_trace() # test_img_dir = "/home/dell/桌面/tile_round1_testA_20201231/tile_round1_testA_20201231/cam3/crop/" imgs_dir = os.listdir(test_img_dir) json_result = [] for img in imgs_dir: img_name = img img = test_img_dir + img result = inference_detector(model, img) # show the results show_result_pyplot(model, result, img, img_name, json_result=json_result, score_thr=args.score_thr) with open("/home/dell/桌面/guangdong/result_cam3.json", "w") as f: json.dump(json_result, f, cls=MyEncoder, indent=6) print("加载入文件完成...")
def inference_model(config_name, checkpoint, args, logger=None): cfg = Config.fromfile(config_name) if args.aug: if 'flip' in cfg.data.test.pipeline[1]: cfg.data.test.pipeline[1].flip = True else: if logger is not None: logger.error(f'{config_name}: unable to start aug test') else: print(f'{config_name}: unable to start aug test', flush=True) model = init_detector(cfg, checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results if args.show: show_result_pyplot(model, args.img, result, score_thr=args.score_thr, wait_time=args.wait_time) return result
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument( 'split', help='split configs in BboxToolkit/tools/split_configs') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image nms_cfg = dict(type='BT_nms', iou_thr=0.5) result = inference_detector_huge_image(model, args.img, args.split, nms_cfg) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
def main(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--out_file', default='result.jpg', help='Test image') parser.add_argument( '--score-thr', type=float, default=0.25, help='bbox score threshold') args = parser.parse_args() model = init_detector(args.config, args.checkpoint, device=args.device) load(model) ImageList = os.listdir(args.img) for ImageName in ImageList: ImagePath = os.path.join(args.img, ImageName) Image = cv2.imread(ImagePath) # build the model from a config file and a checkpoint file # test a single image result = inference_detector(model, Image) # show the results show_result_pyplot(model, Image, result, score_thr=args.score_thr, out_file=os.path.join(args.out_file,ImageName))
def main(args): config = Config.fromfile(args.config) logger = get_root_logger(log_file='benchmark_test_image.log', log_level=logging.ERROR) for model_key in config: model_infos = config[model_key] if not isinstance(model_infos, list): model_infos = [model_infos] for model_info in model_infos: print('processing: ', model_info['config'], flush=True) config_name = model_info['config'].strip() checkpoint = osp.join(args.checkpoint_root, model_info['checkpoint'].strip()) try: # build the model from a config file and a checkpoint file cfg = Config.fromfile(config_name) if args.aug: if 'flip' in cfg.data.test.pipeline[1]: cfg.data.test.pipeline[1].flip = True else: logger.error( f'{config_name} " : Unable to start aug test') model = init_detector(cfg, checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results if args.show: show_result_pyplot(model, args.img, result, score_thr=args.score_thr, wait_time=1) except Exception as e: logger.error(f'{config_name} " : {repr(e)}')
cfg.evaluation.interval = 12 # We can set the checkpoint saving interval to reduce the storage cost cfg.checkpoint_config.interval = 12 # Set seed thus the results are more reproducible cfg.seed = 0 set_random_seed(0, deterministic=False) cfg.gpu_ids = range(1) # We can initialize the logger for training and have a look # at the final config used for training print(f'Config:\n{cfg.pretty_text}') # Build dataset datasets = [build_dataset(cfg.data.train)] # Build the detector model = init_detector( cfg, '/home/palm/PycharmProjects/mmdetection/tutorial_exps/epoch_24.pth', device='cpu') # test a single image result = inference_detector( model, '/media/palm/data/MicroAlgae/22_11_2020/images/00001.jpg') # show the results show_result_pyplot( model, '/media/palm/data/MicroAlgae/22_11_2020/images/00001.jpg', result, score_thr=0.3)
def show_result(img_path): # Run Inference result = inference_detector(model, img_path) # Visualization results show_result_pyplot(img_path, result,('Bordered', 'cell', 'Borderless'), score_thr=0.85)
# Build the detector model = build_detector( cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg) # Add an attribute for visualization convenience model.CLASSES = datasets[0].CLASSES # Create work_dir mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) train_detector(model, datasets, cfg, distributed=False, validate=True) """# testing: quên chỉnh tên class về logo""" img = mmcv.imread('/content/drive/My Drive/mmdetection/flick/training/image_2/2534155497.jpg') model.cfg = cfg result = inference_detector(model, img) show_result_pyplot(model, img, result) """## pickle""" import pickle pkl_filename = "/content/drive/My Drive/flick_dataset_preprocessing/model/model_1.pkl" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) """## torch.save""" PATH = '/content/drive/My Drive/flick_dataset_preprocessing/model/model_1.pth' torch.save(model, PATH)
] labels = np.concatenate(labels) indexes_to_delete = []; for j in range(len(bboxes)): score = float(bboxes[j][4]); class_name = obj_list[labels[j]] if(score < thresh or class_name not in classes): indexes_to_delete.append(j); bboxes_new = np.delete(bboxes, indexes_to_delete, 0) labels_new = np.delete(labels, indexes_to_delete) if(savefig): show_result_pyplot(img_name, bboxes_new, labels_new, model.CLASSES, output_name, thresh) if(write_monk_format): print("Saving Annotations to monk format"); df = preds_to_monk_format(img_name, bboxes, labels, classes, class_names=obj_list, thresh=thresh); out_file_name = output_name.split(".")[0] + ".csv"; df.to_csv(out_file_name, index=False); if(write_coco_format): print("Saving Annotations to coco format (individual files)"); coco_json = preds_to_coco_format(img_name, bboxes, labels, classes, class_names=obj_list, thresh=thresh); out_file_name = output_name.split(".")[0] + ".json"; outfile = open(out_file_name, 'w'); json_str = json.dumps(coco_json, indent=4); outfile.write(json_str);