Mask RCNN代码

Mask_RCNN入门(一)—— 跑通代码 教程地址:tensorflow版的Mask_RCNN clone项目 conda创建python=3.5.2(官方要求3.4+) conda create -n mask_rcnn python=3.5.2 看到项目READ.md中这个部分: 所以加下来不用按教程来一个一个包自己下载,直接使用项目目录下的requirements.txt,但是注意,不可以直接使用上面的代码,要做准备工作: 升级... 阅读详情

matterport/Mask rcnn

  • model.py是网络主要构建的文件
  • utils.py中的anchor产生函数部分,主要是涉及函数:

RPN部分

scales:(32, 64, 128, 256, 512)

ratios:(0.5, 1, 2)

feature_shapes:[[256, 256], [128, 128], [64, 64], [32, 32], [16, 16]]

feature_strides:[4, 8, 16, 32, 64]

anchor_stride:1

在generate_pyramid_anchor()中对generate_anchors()循环调用,scales, feature_shapes, feature_strides是一一对应来进入generate_anchors()函数。

input image的大小是1024x1024,那么经过4x下采样,得到(256, 256),同样,经过8x,得到(128, 128),这就是feature_strides和feature_shapes的对应关系。scales表示一个在各个FPN level上相同大小的anchor所产生的对应于input image的anchor的是不一样的。在(256, 256)产生的是32x32的,而在(128, 128)时,因为anchor大小不变,而感受野变大,变大2x,所以产生的是64x64的,以此类推。

generate_anchors()函数:当输入为generate_anchors(32, [0.5, 1, 2], [256, 256], 4, 1)时,在256x256大小的feature map上,计算可知,在feature map上的anchor大小是8×8的,映射到input image是32x32大小,其中的shifts_y与shifts_x就是对feature map 256×256上的element按照步长为anchor_stride来进行移动窗口,在此处设置anchor_stide为1,那么将会有256*256个,因为有三个ratios,所以一共有256×256×3个anchor,且通过操作 * feature_stride映射回到input image上。最后由中心坐标和长宽来求box的左上与右下坐标。

def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride):
    """
    scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128]
    ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2]
    shape: [height, width] spatial shape of the feature map over which
            to generate anchors.
    feature_stride: Stride of the feature map relative to the image in pixels.
    anchor_stride: Stride of anchors on the feature map. For example, if the
        value is 2 then generate anchors for every other feature map pixel.
    """
    # Get all combinations of scales and ratios
    # eg 32 和 [0.5, 1, 2]
    scales, ratios = np.meshgrid(np.array(scales), np.array(ratios))
    scales = scales.flatten() # array([32, 32, 32])
    ratios = ratios.flatten() # array([ 0.5,  1. ,  2. ])

    # Enumerate heights and widths from scales and ratios
    heights = scales / np.sqrt(ratios) # array([ 45.254834,  32.,  22.627417])
    widths = scales * np.sqrt(ratios) # array([ 22.627417,  32. ,  45.254834])

    # Enumerate shifts in feature space,eg anchor_stride = 1 , featrue_stride = 4 
    # here, shape = (256, 256)
    # shift_y.shape = (256, ), shift_x.shape = (256, )
    shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride
    shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride

    # shifts_x.shape = (256, 256)--->[[0, 1, ...., 256], [0, 1, ...., 256], ...] * 4
    # shifts_y.shape = (256, 256)--->[[0, 0, ...., 0], [1, 1, ...., 1], ....] * 4
    shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y)

    # Enumerate combinations of shifts, widths, and heights
    # box_widths.shape = (256*256, 3)----> 3 is [22.627417,  32. ,  45.254834]
    # box_centers_x.shape = (256*256, 3)--->256*256 is [0, 1, ...255, 0, 1, ...255,,...]
    box_widths, box_centers_x = np.meshgrid(widths, shifts_x)
    box_heights, box_centers_y = np.meshgrid(heights, shifts_y)

    # Reshape to get a list of (y, x) and a list of (h, w)
    # (256*256*3, 2)
    box_centers = np.stack([box_centers_y, box_centers_x], axis=2).reshape([-1, 2])
    box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2])

    # Convert to corner coordinates (y1, x1, y2, x2)
    boxes = np.concatenate([box_centers - 0.5 * box_sizes,
                            box_centers + 0.5 * box_sizes], axis=1)
    # if generate_anchors(32, [0.5, 1, 2], [256, 256], 4, 1), return boxes.shape=(196608, 4)
    return boxes


def generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides,
                             anchor_stride):
    """Generate anchors at different levels of a feature pyramid. Each scale
    is associated with a level of the pyramid, but each ratio is used in
    all levels of the pyramid.

    Returns:
    anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted
        with the same order of the given scales. So, anchors of scale[0] come
        first, then anchors of scale[1], and so on.

    scales (32, 64, 128, 256, 512)
    ratios = [0.5, 1, 2]
    here, feature_shapes*feature_strides = [[1024, 1024], [1024, 1024], ...], input image is 1024x1024
    feature_shapes = 
    [[256 256]
     [128 128]
     [ 64  64]
     [ 32  32]
     [ 16  16]]
    feature_strides = [4, 8, 16, 32, 64]
    anchor_stride = 1
    """
    # Anchors
    # [anchor_count, (y1, x1, y2, x2)]
    anchors = []
    for i in range(len(scales)):
        anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i],
                                        feature_strides[i], anchor_stride))
    return np.concatenate(anchors, axis=0)

model.py中的Class ProposalLayer,实现了网络中的Proposal层,是在rpn和rcnn的中间部分,这一层的输入是rpn_probs和rpn_bbox,代码中有标注,output的shape为(None, self.proposal_count, 4),可以看出是候选框的数量,4为坐标,proposalLayer层是对所有的经过rpn网络得到的proposal进行处理,从fg prob的得分选出top_k的候选框,再使用非极大值抑制进一步减少proposal数量。其中有个细节是利用rpn预测的rpn_bbox的(dy, dx, log(dh), log(dw))来对选出来的anchor原坐标(y1, x1, y2 ,x2)进行位置偏移的精修,rpn_bbox的预测是偏移量,处理的函数是:apply_box_deltas_graph(anchors, deltas)函数

class ProposalLayer(KE.Layer):
    """Receives anchor scores and selects a subset to pass as proposals
    to the second stage. Filtering is done based on anchor scores and
    non-max suppression to remove overlaps. It also applies bounding
    box refinment detals to anchors.

    Inputs:
        rpn_probs: [batch, anchors, (bg prob, fg prob)]
        rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]

    Returns:
        Proposals in normalized coordinates [batch, rois, (y1, x1, y2, x2)]
    """

    def __init__(self, proposal_count, nms_threshold, anchors,
                 config=None, **kwargs):
        """
        proposal_count = 2000 or 1000 below, nms_threshold=0.7
        anchors: [N, (y1, x1, y2, x2)] anchors defined in image coordinates
        """
        super(ProposalLayer, self).__init__(**kwargs)
        self.config = config
        self.proposal_count = proposal_count
        self.nms_threshold = nms_threshold
        self.anchors = anchors.astype(np.float32)

    def call(self, inputs):
        # inputs is [rpn_class, rpn_bbox]
        # Box Scores. Use the foreground class confidence. [Batch, num_rois, 1]
        scores = inputs[0][:, :, 1]
        # Box deltas [batch, num_rois, 4]
        deltas = inputs[1]
        # RPN_BBOX_STD_DEV = np.array([0.08, 0.08, 0.17, 0.17])
        # RPN_BBOX_STD_MEANS = np.array([0.02, 0.02, 0.01, 0.02])
        deltas = (deltas + np.reshape(self.config.RPN_BBOX_STD_MEANS, [1, 1, 4])) * np.reshape(self.config.RPN_BBOX_STD_DEV, [1, 1, 4])
        # Base anchors
        anchors = self.anchors

        # Improve performance by trimming to top anchors by score
        # and doing the rest on the smaller subset.

        # self.anchors generated by utils.generate_pyramid_anchors
        # anchor.shape = [anchor_num, 4]
        pre_nms_limit = min(6000, self.anchors.shape[0])
        ix = tf.nn.top_k(scores, pre_nms_limit, sorted=True,
                         name="top_anchors").indices
        scores = utils.batch_slice([scores, ix], lambda x, y: tf.gather(x, y),
                                   self.config.IMAGES_PER_GPU)
        deltas = utils.batch_slice([deltas, ix], lambda x, y: tf.gather(x, y),
                                   self.config.IMAGES_PER_GPU)
        anchors = utils.batch_slice(ix, lambda x: tf.gather(anchors, x),
                                    self.config.IMAGES_PER_GPU,
                                    names=["pre_nms_anchors"])

        # Apply deltas to anchors to get refined anchors.
        # [batch, N, (y1, x1, y2, x2)]
        boxes = utils.batch_slice([anchors, deltas],
                                  lambda x, y: apply_box_deltas_graph(x, y),
                                  self.config.IMAGES_PER_GPU,
                
mask-rcnn 代码解析01 1、代码来源link : 2、代码构成: 3、首先看一下 utils.py 看一下模型定义 from mrcnn import utils #因为model中导入utils.py 先看一下工具类型 如何定义函数的 def extract_bboxes(mask): 输入为mask 提取每个实例的bbox用于训练和监督 返回 bbox def compute_iou(box, boxes, box_area, boxes_area): """Calculates IoU. 阅读详情

相关推荐

【代码研读】Mask RCNN代码阅读笔记(一)总览篇

前言: mask-rcnn作为如今领域流行的代码框架,被广泛应用,为了学习的需要,结合网上的教程,写了以下的代码研读笔记 阅读的代码为:mask-rcnn benchmark 【github地址】 整体架构: mask-rcnn核心代码方面主要分为三个部分: backbone(骨架特征提取网络)+ rpn(粗分类的区域提议网络)+ roi_head(实现各部分功能的集成模块,如mask/detct...

云端筑梦师 904

Mask-RCNN(2) : 代码使用

当一个batch的长宽比率相差比较大的时候,我们真正输入网络的图片其实是很大的。,如果在验证的时候单张输入图片的话,那么我们输入网络的图片大小其实是和当前图片大小是一样的,此时我们对图片不需要太多处理。每隔10个epoch进行验证, 不过这样就没法获得保存每个epoch的验证结果,这样就没法根据每个epoch它的验证结果去绘制对应的曲线了。所以按照长宽比率进行排序之后,我们对它分组,然后再组内进行采样,这样我们输入网络的图片打包成batch它的大小会更小些,从而对。的,在目标检测中是没有使用到的。

@bangbang的博客 2007

计算机视觉 | 面试题:24、Faster_R_CNN和Mask_R_CNN的损失函数详解

问题 我的项目中涉及到这两个网络,而网络的最重要的部分除了巧妙的结构设计外,当属损失函数的设计了,所以很多时候面试官都会问我,损失函数使用的是啥,我想他们期待我给的答案是自己设计的损失函数吧,但是做项目的时候我那么菜,根本没有能力去设计好吧(说得好像现在有似的……),所以都是使用人家原有的损失函数,并没做修改。 时间久了,这些东西当再次被面试官问起的时候,希望我至少能把人家论文中的损失函数形式讲清楚吧。 简单介绍下这两个网络 目标检测的框架中包含4个关键模块,包括region proposal(生成ROI)

Mrrunsen的博客 1376

EEVDF调度算法核心实现解析(一)

本文深入解析Linux kernel 6.6引入的EEVDF调度算法核心实现,详细讲解其基于虚拟截止时间(virtual deadline)的进程挑选机制和红黑树优化设计。通过代码实例展示算法如何平衡系统响应速度与公平性,特别适合需要优化Linux系统性能的开发者参考。

weixin_42522953的博客 477

RealSense D435i深度相机实战:从像素坐标到三维空间的精准映射(Python实现)

本文详细介绍了使用RealSense D435i深度相机实现从二维像素坐标到三维空间坐标精准映射的两种Python实战方法:深度图反投影法与点云直接查找法。文章涵盖环境搭建、相机对齐、代码实现、性能对比及与YOLO等检测模型结合的进阶应用,并提供了关键的避坑指南和参数调优建议,帮助开发者在机器人、三维重建等项目中高效应用。

weixin_29291573的博客 382

STM32H743 LAN8720网口配置避坑指南:用CubeMX v6.5.0快速搞定LWIP+FreeRTOS

本文详细介绍了使用CubeMX v6.5.0配置STM32H743与LAN8720网口的LWIP+FreeRTOS方案,涵盖硬件连接、时钟配置、ETH外设初始化及LWIP协议栈调优等关键步骤。特别针对常见陷阱提供解决方案,帮助开发者快速实现稳定网络通信,适用于嵌入式网络开发场景。

weixin_33739523的博客 356

双目相机测距原理

普通双目相机具有如下特点:左右两个相机位于同一平面(光轴平行),且相机参数(焦距f)一致。其原理图如下:如图所示,P点为相应的物体位置,CL和CR为左右相机光心位置,PL和PR分别为左相机和右相机拍摄的P点成像结果。f为相机焦距,Z为物体距相机的深度距离,b为左右相机基线距离根据几何关系有:则相应的深度信息计算公式为:(1)其中XL-XR为视差。其余在两侧的情况同样可以用几何关系分析得到该表达式(1),即对于普通双目相机测距可以直接通过公式(1)得到深度结果。

doudou2weiwei的博客 4542

yolov5-6.0的稀疏化训练、结构化剪枝、微调

YOLOv5的BN剪枝、微调

qq_41920323的博客 4394

2025年09月中国电子学会青少年软件编程(Python)等级考试试卷(一级)答案 + 解析

2025年09月中国电子学会青少年软件编程(Python)等级考试试卷(一级)答案 + 解析

伶俐角少儿编程 639

10天冲刺国自然基金!用这套实战AI提示词指令教程,助你中标率翻倍!亲测DeepSeek和ChatGPT不好用

虽然以上国自然提示词指令经过反复实测,但并不是万能无脑帮你搞定所有,大模型AI的特性是你专业领域能力越强,它的智商表现就会更加强大,通过以上提示词教程的使用,大大提升中标概率是肯定的。还有就是大模型的使用上,不是市面上大家都说好的就一定适用,目前来看,Gemini和Claude的两个模型是非常适合国自然本子的修改的。在使用大模型进行国自然本子撰写修改时,首先是角色的设定,然后是目标和背景的描述,好用的提示词指令都是要经过无数次的实测,比对输出结果后又反复调整,达到最佳的效果状态的提示词指令。

智能AI让学术科研更容易 1245

基于Simulink实现电动汽车制动能量回收系统的仿真

通过上述步骤,我们成功实现了基于Simulink的电动汽车制动能量回收系统的仿真研究。该系统能够全面评估制动能量回收系统的性能,验证控制策略的有效性,并通过优化设计提高能量回收效率和制动安全性。引入智能预测:结合人工智能技术,实现更智能的能量回收控制策略。扩展功能:增加对多种车型和制动场景的支持,提升系统通用性。实验验证:将仿真模型应用于实际硬件,进行实验验证,评估其在实际工况下的表现。

xiaoheshang_123的博客 336

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

上一篇: 【E-Net & LinkNet】For Efficient
下一篇: 【RefineNet】RefineNet: Multi-Path Refinement Networks for High-Resolution Semantic Segmentation
One__Coder
博客等级 码龄10年 59粉丝 55原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值