Ejemplo n.º 1
0
def eval_all_models(cfg_file=cfg_file, begin_at=4000, add_eval_flag=True):
    cfg.merge_from_file(cfg_file)
    cfg.freeze()

    root = cfg.OUTPUT_DIR
    last_ckpt_file = os.path.join(root, 'last_checkpoint')

    step = cfg.SOLVER.CHECKPOINT_PERIOD
    max_iter = cfg.SOLVER.MAX_ITER
    with open(last_ckpt_file, 'r') as f:
        last_ckpt = f.read()
    last_ckpt_dirname = os.path.dirname(last_ckpt)

    def evaluation(main):
        def evaluation_all_models(add_eval_flag=add_eval_flag):
            for i in range(begin_at, max_iter + step, step):
                last_ckpt = os.path.join(last_ckpt_dirname,
                                         'model_{:07}.pth'.format(i))
                with open(last_ckpt_file, 'w') as f:
                    f.write(last_ckpt)
                main(add_eval_flag)
                torch.cuda.empty_cache()
            print('All models testing finished...')

        return evaluation_all_models

    return evaluation
def main():
    parser = argparse.ArgumentParser(
        description="PyTorch Object Detection Training")
    parser.add_argument(
        "--config-file",
        default=
        "/home/lxl/jittor/detectron.jittor/configs/maskrcnn_benchmark/e2e_faster_rcnn_R_50_C4_1x.yaml",
        metavar="FILE",
        help="path to config file",
        type=str,
    )
    parser.add_argument("--local_rank", type=int, default=0)
    parser.add_argument(
        "--skip-test",
        dest="skip_test",
        help="Do not test the final model",
        action="store_true",
    )
    parser.add_argument(
        "opts",
        help="Modify config options using the command-line",
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()

    num_gpus = int(
        os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1

    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()

    output_dir = cfg.OUTPUT_DIR
    if output_dir:
        mkdir(output_dir)

    logger = setup_logger("detectron", output_dir)
    logger.info("Using {} GPUs".format(num_gpus))

    logger.info("Collecting env info (might take some time)")
    logger.info("\n" + collect_env_info())

    logger.info("Loaded configuration file {}".format(args.config_file))

    model = train(cfg, args.local_rank, False)

    if not args.skip_test:
        run_test(cfg, model, False)
Ejemplo n.º 3
0
def run_inference(config_file):
    import jittor as jt
    from jittor_utils import auto_diff

    from detectron.config import cfg
    from detectron.modeling.detector import build_detection_model
    from detectron.utils.checkpoint import DetectronCheckpointer
    from detectron.data import make_data_loader
    from detectron.engine.inference import inference
    from detectron.utils.logger import setup_logger

    jt.flags.use_cuda = 1
    jt.cudnn.set_algorithm_cache_size(0)

    cfg.merge_from_file(config_file)
    cfg.freeze()

    save_dir = ""
    logger = setup_logger("maskrcnn_benchmark", save_dir)
    model = build_detection_model(cfg)
    # hook = auto_diff.Hook('fasterrcnn')
    # hook.hook_module(model)

    output_dir = cfg.OUTPUT_DIR
    checkpointer = DetectronCheckpointer(cfg, model, save_dir=output_dir)
    _ = checkpointer.load(cfg.MODEL.WEIGHT)

    iou_types = ("bbox", )
    if cfg.MODEL.MASK_ON:
        iou_types = iou_types + ("segm", )
    if cfg.MODEL.KEYPOINT_ON:
        iou_types = iou_types + ("keypoints", )
    dataset_names = cfg.DATASETS.TEST
    data_loaders_val = make_data_loader(cfg, is_train=False)
    for dataset_name, data_loader_val in zip(dataset_names, data_loaders_val):
        inference(
            model,
            data_loader_val,
            dataset_name=dataset_name,
            iou_types=iou_types,
            box_only=False if cfg.MODEL.FCOS_ON or cfg.MODEL.EMBED_MASK_ON
            or cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,
            bbox_aug=cfg.TEST.BBOX_AUG.ENABLED,
            expected_results=cfg.TEST.EXPECTED_RESULTS,
            expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
            cfg=cfg)
Ejemplo n.º 4
0
def run_torch_inference(config_file):
    import jittor as jt
    from jittor_utils import auto_diff

    from maskrcnn_benchmark.config import cfg
    from maskrcnn_benchmark.modeling.detector import build_detection_model
    from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
    from maskrcnn_benchmark.data import make_data_loader
    from maskrcnn_benchmark.engine.inference import inference
    from maskrcnn_benchmark.utils.logger import setup_logger

    cfg.merge_from_file(config_file)
    cfg.freeze()

    save_dir = ""
    model = build_detection_model(cfg)
    model = model.cuda()
    # hook = auto_diff.Hook('fasterrcnn')
    # hook.hook_module(model)

    output_dir = cfg.OUTPUT_DIR
    checkpointer = DetectronCheckpointer(cfg, model, save_dir=output_dir)
    _ = checkpointer.load(cfg.MODEL.WEIGHT)

    iou_types = ("bbox", )
    if cfg.MODEL.MASK_ON:
        iou_types = iou_types + ("segm", )
    dataset_names = cfg.DATASETS.TEST
    data_loaders_val = make_data_loader(cfg, is_train=False)
    for dataset_name, data_loader_val in zip(dataset_names, data_loaders_val):
        inference(
            model,
            data_loader_val,
            'coco_2014_minival',
            iou_types=iou_types,
            box_only=cfg.MODEL.RPN_ONLY,
            expected_results=cfg.TEST.EXPECTED_RESULTS,
            expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
        )
Ejemplo n.º 5
0
#     Given an url of an image, downloads the image and
#     returns a PIL image
#     """
#     response = requests.get(url)
#     pil_image = Image.open(BytesIO(response.content)).convert("RGB")
#     # convert to BGR format
#     image = np.array(pil_image)[:, :, [2, 1, 0]]
#     return image

# turn on cuda
jt.flags.use_cuda = 1

# set config
config_file = '../configs/maskrcnn_benchmark/e2e_mask_rcnn_R_50_FPN_1x.yaml'
# update the config options with the config file
cfg.merge_from_file(config_file)
#cfg.MODEL.WEIGHT = "weight/maskrcnn_r50.pth"

#set predictor
coco_demo = COCODemo(
    cfg,
    min_image_size=800,
    confidence_threshold=0.5,
)

#load image
pil_image = Image.open('test.jpg').convert("RGB")
image = np.array(pil_image)[:, :, [2, 1, 0]]

# compute predictions
predictions = coco_demo.run_on_opencv_image(image)
Ejemplo n.º 6
0
def main(cfg_file):
    parser = argparse.ArgumentParser(
        description="PyTorch Object Detection Training")
    parser.add_argument(
        "--config-file",
        default=cfg_file,
        metavar="FILE",
        help="path to config file",
        type=str,
    )
    parser.add_argument("--local_rank",
                        type=int,
                        default=int(
                            os.environ['CUDA_VISIBLE_DIVICES']))  # default=0
    parser.add_argument(
        "--skip-test",
        dest="skip_test",
        help="Do not test the final model",
        action="store_true",
        default=False,  # True False
    )
    parser.add_argument(
        "opts",
        help="Modify config options using the command-line",
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()

    num_gpus = int(
        os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
    args.distributed = num_gpus > 1

    # if args.distributed:
    #     torch.cuda.set_device(args.local_rank)
    #     torch.distributed.init_process_group(
    #         backend="nccl", init_method="env://"
    #     )
    #     synchronize()

    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()

    output_dir = cfg.OUTPUT_DIR
    if output_dir:
        mkdir(output_dir)

    logger = setup_logger("detectron", output_dir, get_rank())
    logger.info("Using {} GPUs".format(num_gpus))
    logger.info(args)

    logger.info("Loaded configuration file {}".format(args.config_file))
    with open(args.config_file, "r") as cf:
        config_str = "\n" + cf.read()
        logger.info(config_str)
    logger.info("Running with config:\n{}".format(cfg))

    model = train(cfg, args.distributed)
    if not args.skip_test:
        run_test(cfg, model, args.distributed)
Ejemplo n.º 7
0
def run_model(config_file, img_f=None):
    original_image = load(img_f)
    from detectron.config import cfg
    from detectron.modeling.detector import build_detection_model
    from detectron.utils.checkpoint import DetectronCheckpointer
    from detectron.structures.image_list import to_image_list
    from detectron.modeling.roi_heads.mask_head.inference import Masker

    from jittor import transform as T
    from jittor import nn
    import jittor as jt
    from jittor_utils import auto_diff

    jt.flags.use_cuda = 1
    confidence_threshold = 0.0

    cfg.merge_from_file(config_file)
    model = build_detection_model(cfg)

    checkpointer = DetectronCheckpointer(cfg, model, save_dir=cfg.OUTPUT_DIR)
    _ = checkpointer.load(cfg.MODEL.WEIGHT)

    name = config_file.split('/')[-1].split('.')[0]
    # hook = auto_diff.Hook(name)
    # hook.hook_module(model)
    model.eval()

    class Resize(object):
        def __init__(self, min_size, max_size):
            self.min_size = min_size
            self.max_size = max_size

        # modified from torchvision to add support for max size
        def get_size(self, image_size):
            w, h = image_size
            size = self.min_size
            max_size = self.max_size
            if max_size is not None:
                min_original_size = float(min((w, h)))
                max_original_size = float(max((w, h)))
                if max_original_size / min_original_size * size > max_size:
                    size = int(
                        round(max_size * min_original_size /
                              max_original_size))

            if (w <= h and w == size) or (h <= w and h == size):
                return (h, w)

            if w < h:
                ow = size
                oh = int(size * h / w)
            else:
                oh = size
                ow = int(size * w / h)

            return (oh, ow)

        def __call__(self, image):
            size = self.get_size(image.size)
            image = T.resize(image, size)
            return image

    def build_transform():
        if cfg.INPUT.TO_BGR255:
            to_bgr_transform = T.Lambda(lambda x: x * 255)
        else:
            to_bgr_transform = T.Lambda(lambda x: x[[2, 1, 0]])

        normalize_transform = T.ImageNormalize(mean=cfg.INPUT.PIXEL_MEAN,
                                               std=cfg.INPUT.PIXEL_STD)
        min_size = cfg.INPUT.MIN_SIZE_TEST
        max_size = cfg.INPUT.MAX_SIZE_TEST
        transform = T.Compose([
            T.ToPILImage(),
            Resize(min_size, max_size),
            T.ToTensor(),
            to_bgr_transform,
            normalize_transform,
        ])
        return transform

    transforms = build_transform()
    image = transforms(original_image)
    image_list = to_image_list(image, cfg.DATALOADER.SIZE_DIVISIBILITY)
    predictions = model(image_list)

    predictions = predictions[0]
    if predictions.has_field("mask_scores"):
        scores = predictions.get_field("mask_scores")
    else:
        scores = predictions.get_field("scores")

    keep = jt.nonzero(scores > confidence_threshold).squeeze(1)
    predictions = predictions[keep]
    scores = predictions.get_field("scores")
    idx, _ = jt.argsort(scores, 0, descending=True)
    predictions = predictions[idx]

    result_diff(predictions)
Ejemplo n.º 8
0
def main():
    jt.flags.use_cuda = 1
    parent_path = os.path.abspath(__file__).split("/tools/")[0]
    parser = argparse.ArgumentParser(description="Object Detection Inference")
    parser.add_argument(
        "--config-file",
        default=
        f"{parent_path}/configs/maskrcnn_benchmark/e2e_mask_rcnn_R_50_FPN_1x.yaml",
        metavar="FILE",
        help="path to config file",
    )
    parser.add_argument(
        "--ckpt",
        help=
        "The path to the checkpoint for test, default is the latest checkpoint.",
        default=None,
    )
    parser.add_argument(
        "opts",
        help="Modify config options using the command-line",
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()

    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()

    save_dir = ""
    logger = setup_logger("detectron", save_dir)
    logger.info("Using {} GPUs".format(1))
    logger.info(cfg)

    logger.info("Collecting env info (might take some time)")
    logger.info("\n" + collect_env_info())

    model = build_detection_model(cfg)

    output_dir = cfg.OUTPUT_DIR
    checkpointer = DetectronCheckpointer(cfg, model, save_dir=output_dir)
    ckpt = cfg.MODEL.WEIGHT if args.ckpt is None else args.ckpt
    _ = checkpointer.load(ckpt, use_latest=args.ckpt is None)

    iou_types = ("bbox", )
    if cfg.MODEL.MASK_ON:
        iou_types = iou_types + ("segm", )
    if cfg.MODEL.KEYPOINT_ON:
        iou_types = iou_types + ("keypoints", )
    output_folders = [None] * len(cfg.DATASETS.TEST)
    dataset_names = cfg.DATASETS.TEST
    if cfg.OUTPUT_DIR:
        for idx, dataset_name in enumerate(dataset_names):
            output_folder = os.path.join(cfg.OUTPUT_DIR, "inference",
                                         dataset_name)
            mkdir(output_folder)
            output_folders[idx] = output_folder
    data_loaders_val = make_data_loader(cfg, is_train=False)
    for output_folder, dataset_name, data_loader_val in zip(
            output_folders, dataset_names, data_loaders_val):
        inference(
            model,
            data_loader_val,
            dataset_name=dataset_name,
            iou_types=iou_types,
            box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,
            bbox_aug=cfg.TEST.BBOX_AUG.ENABLED,
            expected_results=cfg.TEST.EXPECTED_RESULTS,
            expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
            output_folder=output_folder,
        )
Ejemplo n.º 9
0
def main(add_eval_flag=False):
    parser = argparse.ArgumentParser(
        description="PyTorch Object Detection Inference")
    parser.add_argument(
        "--config-file",
        default=cfg_file,
        metavar="FILE",
        help="path to config file",
    )
    parser.add_argument("--local_rank",
                        type=int,
                        default=int(os.environ['CUDA_VISIBLE_DIVICES']))
    parser.add_argument(
        "opts",
        help="Modify config options using the command-line",
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()

    num_gpus = int(
        os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
    args.distributed = num_gpus > 1

    # if args.distributed:
    #     torch.cuda.set_device(args.local_rank)
    #     torch.distributed.init_process_group(
    #         backend="nccl", init_method="env://"
    #     )
    #     synchronize()

    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()

    save_dir = ""
    logger = setup_logger("detectron", save_dir, get_rank())
    logger.info("Using {} GPUs".format(num_gpus))
    logger.info(cfg)

    model = build_detection_model(cfg)
    model.to(cfg.MODEL.DEVICE)

    output_dir = cfg.OUTPUT_DIR
    checkpointer = DetectronCheckpointer(cfg, model, save_dir=output_dir)
    _ = checkpointer.load(cfg.MODEL.WEIGHT)

    iou_types = ("bbox", )
    if cfg.MODEL.MASK_ON:
        iou_types = iou_types + ("segm", )

    output_folders = [None] * len(cfg.DATASETS.TEST)
    dataset_names = cfg.DATASETS.TEST
    if cfg.OUTPUT_DIR:
        for idx, dataset_name in enumerate(dataset_names):
            output_folder = os.path.join(cfg.OUTPUT_DIR, "inference",
                                         dataset_name)
            mkdir(output_folder)
            output_folders[idx] = output_folder
    data_loaders_val = make_data_loader(cfg,
                                        is_train=False,
                                        is_distributed=args.distributed)
    for output_folder, dataset_name, data_loader_val in zip(
            output_folders, dataset_names, data_loaders_val):
        coco_results, _ = \
            inference(
                model,
                data_loader_val,
                dataset_name=dataset_name,
                iou_types=iou_types,
                box_only=cfg.MODEL.RPN_ONLY,
                device=cfg.MODEL.DEVICE,
                expected_results=cfg.TEST.EXPECTED_RESULTS,
                expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
                output_folder=output_folder,
        )
    synchronize()

    def add_eval_fields():
        ar = coco_results.results['bbox']['AR50']
        ap = coco_results.results['bbox']['AP50']

        checkpoint_file = checkpointer.get_checkpoint_file()
        base_checkpoint_file = os.path.basename(checkpoint_file).split('.')[0]
        new_checkpoint_file = os.path.join(
            output_dir,
            base_checkpoint_file + '_ar{:.03}_ap_{:.03}.pth'.format(ar, ap))
        os.rename(checkpoint_file, new_checkpoint_file)

    if add_eval_flag:
        add_eval_fields()