Python Detectron2-在目标检测的阈值下提取区域特征

Python Detectron2-在目标检测的阈值下提取区域特征,python,machine-learning,pytorch,object-detection,detectron,Python,Machine Learning,Pytorch,Object Detection,Detectron,我尝试使用该框架提取类别检测高于某个阈值的区域特征。我将在稍后的管道中使用这些功能(类似于:第3.1节培训维尔伯特),到目前为止,我已经用它培训了一个面具R-CNN,并在一些自定义数据上对其进行了微调。它表现得很好。我想做的是从我训练过的模型中为生成的边界框提取特征 编辑:我查看了关闭我帖子的用户所写的内容,并试图对其进行改进。尽管读者需要了解我所做的事情的背景。如果你对我如何改进这个问题有任何想法,或者你对如何做我想做的事情有一些见解,欢迎你的反馈 我有一个问题: 为什么我只得到一个预测实例,

我尝试使用该框架提取类别检测高于某个阈值的区域特征。我将在稍后的管道中使用这些功能(类似于:第3.1节培训维尔伯特),到目前为止,我已经用它培训了一个面具R-CNN,并在一些自定义数据上对其进行了微调。它表现得很好。我想做的是从我训练过的模型中为生成的边界框提取特征

编辑:我查看了关闭我帖子的用户所写的内容,并试图对其进行改进。尽管读者需要了解我所做的事情的背景。如果你对我如何改进这个问题有任何想法,或者你对如何做我想做的事情有一些见解,欢迎你的反馈

我有一个问题:

  • 为什么我只得到一个预测实例,但当我查看 在预测CLS得分时,超过1个通过 门槛
  • 我相信这是产生ROI特性的正确方法:

    images = ImageList.from_tensors(lst[:1], size_divisibility=32).to("cuda")  # preprocessed input tensor
    #setup config
    cfg = get_cfg()
    cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml"))
    cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
    cfg.SOLVER.IMS_PER_BATCH = 1
    cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  # only has one class (pnumonia)
    #Just run these lines if you have the trained model im memory
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7   # set the testing threshold for this model
    #build model
    model = build_model(cfg)
    DetectionCheckpointer(model).load("output/model_final.pth")
    model.eval()#make sure its in eval mode
    
    #run model
    with torch.no_grad():
        features = model.backbone(images.tensor.float())
        proposals, _ = model.proposal_generator(images, features)
        instances = model.roi_heads._forward_box(features, proposals)
    
    然后

    这应该是我的ROI特性

    我非常困惑的是,我可以使用提案和提案箱以及它们的班级分数,而不是使用推理时产生的边界框,来获得这张图片的前n个特征。很酷,所以我尝试了以下方法:

    proposal_boxes = [x.proposal_boxes for x in proposals]
    proposal_rois = model.roi_heads.box_pooler([features[f] for f in model.roi_heads.in_features], proposal_boxes)
    #found here: https://detectron2.readthedocs.io/_modules/detectron2/modeling/roi_heads/roi_heads.html
    box_features = model.roi_heads.box_head(proposal_rois)
    predictions = model.roi_heads.box_predictor(box_features)
    pred_instances, losses = model.roi_heads.box_predictor.inference(predictions, proposals)
    
    我应该在哪里获得我的提案箱功能及其功能。检查此预测对象时,我看到每个框的分数:

    CLS在预测对象中的得分

    (tensor([[ 0.6308, -0.4926],
             [-1.6662,  1.5430],
             [-0.2080,  0.4856],
             ...,
             [-6.9698,  6.6695],
             [-5.6361,  5.4046],
             [-4.4918,  4.3899]], device='cuda:0', grad_fn=<AddmmBackward>),
    
    tensor([[ 0.2502,  0.2461, -0.4559, -0.3304],
            [-0.1359, -0.1563, -0.2821,  0.0557],
            [ 0.7802,  0.5719, -1.0790, -1.3001],
            ...,
            [-0.8594,  0.0632,  0.2024, -0.6000],
            [-0.2020, -3.3195,  0.6745,  0.5456],
            [-0.5542,  1.1727,  1.9679, -2.3912]], device='cuda:0',
           grad_fn=<AddmmBackward>)
    
    在我的预测对象中,我得到了相同的最高分数,但只有1个实例,而不是2个(我设置了
    cfg.MODEL.ROI\u HEADS.score\u THRESH\u TEST=0.7
    ):

    预测实例

    [Instances(num_instances=1, image_height=800, image_width=800, fields=[pred_boxes: Boxes(tensor([[548.5992, 341.7193, 756.9728, 438.0507]], device='cuda:0',
            grad_fn=<IndexBackward>)), scores: tensor([0.7546], device='cuda:0', grad_fn=<IndexBackward>), pred_classes: tensor([0], device='cuda:0')])]
    

    你就快到了。看看你会发现,它并不是简单地排序框候选人的分数。首先,它应用箱增量来重新调整提案箱。然后计算非最大抑制以删除非重叠框(同时应用其他超设置,如分数阈值)。最后,它根据得分对顶级k盒子进行排名。这可能解释了为什么您的方法生成相同的框分数,但不同数量的输出框及其坐标

    回到您原来的问题,以下是在一次推理过程中提取建议框特征的方法:

    image = cv2.imread('my_image.jpg')
    height, width = image.shape[:2]
    image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
    inputs = [{"image": image, "height": height, "width": width}]
    with torch.no_grad():
        images = model.preprocess_image(inputs)  # don't forget to preprocess
        features = model.backbone(images.tensor)  # set of cnn features
        proposals, _ = model.proposal_generator(images, features, None)  # RPN
    
        features_ = [features[f] for f in model.roi_heads.box_in_features]
        box_features = model.roi_heads.box_pooler(features_, [x.proposal_boxes for x in proposals])
        box_features = model.roi_heads.box_head(box_features)  # features of all 1k candidates
        predictions = model.roi_heads.box_predictor(box_features)
        pred_instances, pred_inds = model.roi_heads.box_predictor.inference(predictions, proposals)
        pred_instances = model.roi_heads.forward_with_given_boxes(features, pred_instances)
    
        # output boxes, masks, scores, etc
        pred_instances = model._postprocess(pred_instances, inputs, images.image_sizes)  # scale box to orig size
        # features of the proposed boxes
        feats = box_features[pred_inds]
    

    我认为这个问题不应该被删除。可能是因为编辑而打电话,但仅仅因为我有多个问题,并不意味着我就把问题解决了。当然,文章中有很多文本,但这是为了上下文,否则我会得到一个“可复制的代码…”如果有任何关于如何改进的建议,我愿意改进。我还有一个问题,你能告诉我在哪里可以学习如何可视化这些特征的正确方向吗?如果你想可视化检测框的特征,请使用一种降维方法,如PCA或更好的T-SNE(参见)。您应该期望同一语义类的长方体特征彼此接近。如果您只是想可视化长方体坐标,请使用内置的可视化工具类Detectron2,请参阅,谢谢!抱歉,如果我的问题不清楚,我感兴趣的是可视化功能,类似于我们如何将CNN的功能图可视化为原始图像上的热图覆盖。或者,我会满足于将这些高级功能可视化,比如深度梦。我们可以从pooler中获取特征图并将其覆盖在图像上吗?不幸的是,我不知道直接的方法。以下是一些可供选择的方向:(1)使用检测到的遮罩和框分数分别表示热图面积和强度;(2) 使用激活可视化方法(如GradCam)来可视化给定目标最活跃的区域。注意:在案例(2)中,您需要在detectron2中为GradCam定义自己的目标函数,因为GradCam最初是为单对象分类设计的。非常感谢您的帮助!我真的想出来了,不算太糟,我做了技术1。我甚至开发了一个基于注意力的多模态分类模型,并使用它设计了一个可视化的收费系统,将注意力映射到文本和边界框之间!再次感谢你,这直接进入了我的论文!
    tensor([[ 0.2502,  0.2461, -0.4559, -0.3304],
            [-0.1359, -0.1563, -0.2821,  0.0557],
            [ 0.7802,  0.5719, -1.0790, -1.3001],
            ...,
            [-0.8594,  0.0632,  0.2024, -0.6000],
            [-0.2020, -3.3195,  0.6745,  0.5456],
            [-0.5542,  1.1727,  1.9679, -2.3912]], device='cuda:0',
           grad_fn=<AddmmBackward>)
    
    [Boxes(tensor([[532.9427, 335.8969, 761.2068, 438.8086],#this box vs the instance box
             [102.7041, 352.5067, 329.4510, 440.7240],
             [499.2719, 317.9529, 764.1958, 448.1386],
             ...,
             [ 25.2890, 379.3329,  28.6030, 429.9694],
             [127.1215, 392.6055, 328.6081, 489.0793],
             [164.5633, 275.6021, 295.0134, 462.7395]], device='cuda:0'))]
    
    image = cv2.imread('my_image.jpg')
    height, width = image.shape[:2]
    image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
    inputs = [{"image": image, "height": height, "width": width}]
    with torch.no_grad():
        images = model.preprocess_image(inputs)  # don't forget to preprocess
        features = model.backbone(images.tensor)  # set of cnn features
        proposals, _ = model.proposal_generator(images, features, None)  # RPN
    
        features_ = [features[f] for f in model.roi_heads.box_in_features]
        box_features = model.roi_heads.box_pooler(features_, [x.proposal_boxes for x in proposals])
        box_features = model.roi_heads.box_head(box_features)  # features of all 1k candidates
        predictions = model.roi_heads.box_predictor(box_features)
        pred_instances, pred_inds = model.roi_heads.box_predictor.inference(predictions, proposals)
        pred_instances = model.roi_heads.forward_with_given_boxes(features, pred_instances)
    
        # output boxes, masks, scores, etc
        pred_instances = model._postprocess(pred_instances, inputs, images.image_sizes)  # scale box to orig size
        # features of the proposed boxes
        feats = box_features[pred_inds]