首页 > 编程语言 >mmdetection 生成c++ 的anchor头文件

mmdetection 生成c++ 的anchor头文件

时间:2022-10-18 15:24:44浏览次数:36  
标签:10 头文件 anchors level args savefilepath mmdetection total anchor

import os
import os.path as osp

import numpy as np
from mmcv import Config
from mmdet.models import build_detector
import math
import argparse
import pickle


def save_cplus_h(multi_level_anchors, savefilepath):
    """
    multi_level_anchors.shape: [[box1,box2, ...], [], ...]
    """
    _template = '''
    
#ifndef _ANCHOR_H
#define _ANCHOR_H

#include "stdlib.h"
#include <vector>

/*
 * 目标检测的anchor框 头文件
 * */

static std::vector<std::vector<std::vector<float>>> ssd_anchor_all_levels = {
//        // stride 8
//        {
//                {-10., 0, -10., 20.},      // x1 y1 x2 y2
//                {-10., 0, -10., 20.},
//                {-10., 0, -10., 20.},
//        },
//
//        // stride 16
//        {
//                {-10., 0, -10., 20.},      // x1 y1 x2 y2
//                {-10., 0, -10., 20.},
//                {-10., 0, -10., 20.},
//        },
//
//        // stride 32
//        {
//                {-10., 0, -10., 20.},      // x1 y1 x2 y2
//                {-10., 0, -10., 20.},
//                {-10., 0, -10., 20.},
//        },
//
//        //...
        @here
};


#endif //_ANCHOR_H
    '''
    with open(savefilepath, 'w', encoding='utf-8') as f:
        m = ''
        for anchors in multi_level_anchors:
            # [N,4]
            a = '{\n'
            for x1, y1, x2, y2 in anchors:
                line = '{' + f'{x1}, {y1}, {x2}, {y2}' + '},\n'
                a += line
            a += '},\n'
        m += a
        _template = _template.replace('@here', m)
        f.write(_template)
    return


def parse_args():
    parser = argparse.ArgumentParser(
        description='Convert MMDetection models to ONNX')
    parser.add_argument('config', help='test config file path')
    parser.add_argument('--output-file', type=str, default='anchor.npy')
    parser.add_argument(
        '--shape',
        type=int,
        nargs='+',
        default=[3, 224, 320],
        help='input image size (CHW)')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = parse_args()
    CONFIG = args.config

    assert args.output_file is not None
    INPUT_C, INPUT_H, INPUT_W = tuple(args.shape)

    cfg = Config.fromfile(CONFIG)
    model = build_detector(cfg.model)

    model.eval()
    assert hasattr(model, 'bbox_head')
    strides_tuple_list = model.bbox_head.anchor_generator.strides
    featmap_sizes = []
    c, h, w = INPUT_C, INPUT_H, INPUT_W
    for sh, sw in strides_tuple_list:
        featmap_sizes.append((math.ceil(h / sh + 0.5), math.ceil(w / sw + 0.5)))
        print([sh, sw], featmap_sizes)
    multi_level_anchors = model.bbox_head.anchor_generator.grid_anchors(featmap_sizes, 'cpu')

    total_anchors = np.concatenate(multi_level_anchors, axis=0)

    print(total_anchors.shape)
    print(total_anchors[:10])

    wh = np.array([[w, h] * 2])
    total_anchors_norm = total_anchors / wh

    ###################### 转bin #######################################################
    anchor_num = total_anchors.shape[0]
    total_anchors_bin_file = total_anchors_norm.reshape((1, 1, -1))
    # todo:  bbox_coder
    target_stds = cfg.model.bbox_head.bbox_coder.target_stds
    target_stds = np.array(target_stds * anchor_num).reshape((1, 1, -1))
    # [1,2,anchor_nums * 4]
    total_anchors_bin_file_res = np.concatenate((total_anchors_bin_file, target_stds), axis=1)
    _savefilepath_bin = f'{args.output_file[:-4]}.bin'
    total_anchors_bin_file_res.astype('float32').tofile(_savefilepath_bin)

    # .npy for python caffe
    _savefilepath_npy = f'{args.output_file[:-4]}.npy'
    np.save(_savefilepath_npy, total_anchors_norm)
    print(_savefilepath_bin)
    print(_savefilepath_npy)

    # 单独保存每个尺度的anchor
    # [[box1,box2, ...], [], ...]
    _savefilepath_pkl_per_levels = f'{args.output_file[:-4]}_per_level.pkl'
    f = open(_savefilepath_pkl_per_levels, 'wb')
    multi_level_anchors = [i.cpu().numpy() for i in multi_level_anchors]
    pickle.dump(multi_level_anchors, f)
    f.close()
    print(_savefilepath_pkl_per_levels)

    # 保存c++ 的头文件
    _savefilepath_h_per_levels = f'{args.output_file[:-4]}_per_level.h'
    save_cplus_h(multi_level_anchors, _savefilepath_h_per_levels)
    print(_savefilepath_h_per_levels)
    print('done.')

 

标签:10,头文件,anchors,level,args,savefilepath,mmdetection,total,anchor
From: https://www.cnblogs.com/dxscode/p/16802641.html

相关文章

  • linux main文件链接头文件(.h .c)的方法
     main文件链接其他.c.h文件的原理就是把其他.c.h文件编译为库函数(静态库或者动态库)方法1:静态函数 建立:fun.hfun.cmain.c三个文件注意的点:fun.c中不能带有头......
  • 在Visual Studio中添加属于自己的头文件(附万能头文件的代码)
    首先我们先找到VisualStudio编辑器中的“解决方案”,右键点击并在下拉菜单中找到属性并点击。点击后会出现一个弹窗,在里面找到“调试源文件”,在右边列表中找到include文件......
  • 基础知识 | 目标检测中Anchor的认识及理解
    近期好多同学在私信让我说一些基础性的知识。好多入门的同学在纠结Anchor的设置,而且部分同学私信,可不可以把这个基础知识详细说一次,今天就单独开一次小课,一起来学习FasterR......
  • CVPR:IoU优化——在Anchor-Free中提升目标检测精度(附源码)
    计算机视觉研究院专栏作者:Edison_G目前的anchor-free目标检测器非常简单和有效,但缺乏精确的标签分配方法,这限制了它们与经典的基于Anchor的模型竞争的潜力公众号ID|ComputerV......
  • vscode include<stdio.h>头文件红色的解决办法
    原因是标准库没识别到。前提需要安装c/c++插件第一步:点击下面win按钮,选择配置JSON第二步:打开c_cpp_properties.json,添加include路径,放在最上面......
  • qml教程-3-锚点anchor布局
    importQtQuick2.15Window{width:400height:600visible:trueRectangle{anchors.fill:parentcolor:'yellowgreen'}}importQtQuick......
  • 干货实践 | Anchor优化后在目标检测提升这么明显
    “计算机视觉研究院”计算机视觉研究院专栏作者:Edison_G目标检测发展已经到了一个瓶颈,但是依然有很多优秀的产出,比如最近比较火热的“Anchor—Free”,貌似在该机制下精度有一......
  • MT4 serverAPI开发接口(头文件)
    如有疑问请联系v:yunkeji5868同managerAPI接口一样,下面是serverAPI提供的接口,可以保存为.h文件直接导入到自己工程中使用。具体如果使用可看我的其他文章。 //+-------......
  • WLC Anchor认证发生的位置
    Foreign/AnchorScenariobetween9800WLCsFormobilityguestscenarios,thereare twomaincontrollerroles:Foreigncontroller:thisWLCownsthelayer2......
  • mmdetection使用wandb查看训练日志
    mmdetection查看日志之前一直是在用TextLoggerHook,已经觉得挺方便的了,自从用了wandb之后,发现wandb真不错,看log更方便了,回不去了。wandb的简单配置:wandb官网:https://wandb......