maskrcnn_benchmark 代码详解之 anchor_generator.py

本文深入剖析maskrcnn_benchmark库中anchor_generator.py的代码,讲解如何生成不同步长、大小和长宽比的anchor,特别强调在采用FPN时,需确保stride、size数量与FPN层数一致,以实现目标检测任务中的有效锚点生成。

前言:

  在RPN中需要生成拥有不同步长(stride)不同大小(size)以及不同长环比(ratio)的anchor, 在maskrcnn_benchmark中,这一工作由anchor_generator.py完成。anchor_generator.py生成所需的不同特征图上的anchor,需要注意的是,如果在backbone中采用了FPN的话,需要保证,stride个数,size个数以及FPN的层数相同。其详细代码为:

# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math

import numpy as np
import torch
from torch import nn

from maskrcnn_benchmark.structures.bounding_box import BoxList


# todo 把anchors转换成buffer的list
class BufferList(nn.Module):
    """
    Similar to nn.ParameterList, but for buffers
    """

    def __init__(self, buffers=None):
        super(BufferList, self).__init__()
        # 如果存在anchor,则把他保存为buffer格式
        if buffers is not None:
            self.extend(buffers)

    def extend(self, buffers):
        offset = len(self)
        # 循环的把各个大小尺度下不同窗宽比anchor,保存为buffer
        for i, buffer in enumerate(buffers):
            self.register_buffer(str(offset + i), buffer)
        return self

    def __len__(self):
        return len(self._buffers)

    def __iter__(self):
        return iter(self._buffers.values())


class AnchorGenerator(nn.Module):
    """
    For a set of image sizes and feature maps, computes a set
    of anchors
    """

    def __init__(
        self,
        sizes=(128, 256, 512),
        aspect_ratios=(0.5, 1.0, 2.0),
        anchor_strides=(8, 16, 32),
        straddle_thresh=0,
    ):
        super(AnchorGenerator, self).__init__()
        # 如果只从一个特征图上提取特征,即不使用rpn
        if len(anchor_strides) == 1:
            # 获得anchor滑动步长
            anchor_stride = anchor_strides[0]
            cell_anchors = [
                generate_anchors(anchor_stride, sizes, aspect_ratios).float()
            ]
        else:
            # 如果anchor滑动步长列表与anchor大小的列表长度不同则报错
            if len(anchor_strides) != len(sizes):
                raise RuntimeError("FPN should have #anchor_strides == #sizes")
            # 循环的得到不同大小尺度不同步长情况下不同长宽比的anchor
            cell_anchors = [
                generate_anchors(
                    anchor_stride,
                    size if isinstance(size, (tuple, list)) else (size,),
                    aspect_ratios
                ).float()
                for anchor_stride, size in zip(anchor_strides, sizes)
            ]
        self.strides = anchor_strides
  
Traceback (most recent call last): File "tools/extract_clip_feature.py", line 20, in <module> from maskrcnn_benchmark.data import make_data_loader File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/data/__init__.py", line 2, in <module> from .build import make_data_loader, get_dataset_statistics File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/data/build.py", line 12, in <module> from maskrcnn_benchmark.utils.miscellaneous import save_labels File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/utils/miscellaneous.py", line 10, in <module> from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/structures/boxlist_ops.py", line 7, in <module> from maskrcnn_benchmark.layers import nms as _box_nms File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/layers/__init__.py", line 10, in <module> from .nms import nms File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/layers/nms.py", line 3, in <module> from ._utils import _C File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/layers/_utils.py", line 39, in <module> _C = _load_C_extensions() File "/root/.cache/huggingface/forget/lab/shichong/cyy/RECODE/maskrcnn_benchmark/layers/_utils.py", line 35, in _load_C_extensions extra_include_paths=extra_include_paths, File "/opt/conda/envs/recode/lib/python3.7/site-packages/torch/utils/cpp_extension.py", line 1296, in load keep_intermediates=keep_intermediates) File "/opt/conda/envs/recode/lib/python3.7/site-packages/torch/utils/cpp_extension.py", line 1534, in _jit_compile return _import_module_from_library(name, build_directory, is_python_module) File "/opt/conda/envs/recode/lib/python3.7/site-packages/torch/utils/cpp_extension.py", line 1936, in _import_module_from_library module = importlib.util.module_from_spec(spec) ImportError: /root/.cache/torch_extensions/py37_cu117/torchvision/torchvision.so: cannot open shared object file: No such file or directory
06-24
### 解决方案 以下是关于解决 `ImportError: cannot import name '_C' from 'maskrcnn_benchmark'` 的详细分析与解决方案。 #### 问题背景 错误的核心是无法正确导入 `_C` 模块。此模块通常是通过编译 C++ 或 CUDA 扩展代码生成的共享对象文件(如 `_C.so`),存储在 `maskrcnn_benchmark/_C.*.so` 中。如果该文件缺失或未正确生成,则会导致上述错误[^1]。 #### 环境依赖检查 确保安装了所有必要的依赖项,包括正确的 PyTorch、CUDA 和其他相关库版本。可以通过以下命令验证 PyTorch 是否正确安装以及是否支持 CUDA: ```python import torch print(torch.__version__) print(torch.cuda.is_available()) ``` 如果 CUDA 不可用或 PyTorch 版本与 CUDA 版本不匹配,可能导致编译失败。确保 PyTorch 版本与 CUDA 版本兼容[^2]。 #### 编译扩展模块 如果 `_C.so` 文件不存在或损坏,需要重新编译扩展模块。进入 `maskrcnn-benchmark` 源码目录并运行以下命令以重新构建模块: ```bash python setup.py build develop ``` 此命令会尝试重新编译 `_C` 模块。如果出现类似 `Microsoft Visual C++ 14.0 is required` 的错误,说明缺少必要的编译工具链。可以通过安装 Microsoft Visual Studio 来解决这个问题[^3]。 #### 替换导入路径 根据引用内容,可以尝试将 `from maskrcnn_benchmark import _C` 替换为 `from ._utils import _C`。此方法适用于某些特定场景,但需确保 `_utils` 模块存在且包含 `_C` 定义[^4]。 #### 检查源码完整性 如果上述方法无效,可能是源码本身存在问题。建议从官方 GitHub 仓库重新下载最新版本的 `maskrcnn-benchmark` 源码,并按照官方文档重新配置和编译[^5]。 #### 单卡训练验证 使用单卡训练脚本验证环境是否正常工作。运行以下命令进行测试: ```bash python /path_to_maskrcnn_benchmark/tools/train_net.py --config-file "/path/to/config/file.yaml" ``` 如果训练脚本能够正常运行,则表明问题已解决[^6]。 #### 示例代码修正 以下是修正后的代码片段(假设使用了替代导入路径): ```python # 原始代码 from maskrcnn_benchmark import _C # 替代代码 from ._utils import _C # 替换为正确的导入路径 ``` 如果上述修改无效,建议检查 `_C` 模块的生成过程,确保其正确编译。 --- ###
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值