目前,文本检测主要分为基于检测网络和分割网络实现,上文(风影:记录densenet-ocr识别网络转ncnn并移植到安卓手机)讲到将yolo3文本检测+densenet识别网络转ncnn推理,并成功移植到安卓上,本文介绍基于分割网络--dbnet文本检测,转ncnn推理并移植到安卓上。

模型转换步骤,dbnet(pytorch)--onnx--ncnn。

2.将pytorch转换为onnx格式,目前onnx支持动态输入,我们暂时可以先将图像的输入设为固定,比如,1280*1280*3,后面再手动修改ncnn模型结构;

device = torch.device("cpu")

print('device:', device)

checkpoint = torch.load(dbnet_modelfile, map_location=device)

config = checkpoint['config']

config['arch']['backbone']['pretrained'] = False

db_model = build_model(config['arch'])

db_model.load_state_dict(checkpoint['state_dict'])

db_model.to(device)

db_model.eval()

input_name = ['input']

output_name = ['output']

input = Variable(torch.randn(1,3, 1280, 1280))

torch.onnx.export(db_model, input, export_onnx_file,

input_names=input_name,

output_names=output_name,

verbose=True,

opset_version=11,

export_params=True,

keep_initializers_as_inputs=True,

# dynamic_axes={"input": {3: "time_step"},

# "output": {3: "time_step"}}

)

print('export done')

3.使用onnxruntime测试导出的模型是否正确;

mean = (0.485, 0.456, 0.406)

std = (0.229, 0.224, 0.225)

src_img = cv2.imread(img_path, 1)

img = cv2.cvtColor(src_img, cv2.COLOR_BGR2RGB)

h, w = img.shape[:2]

# img = resize_image(img, 640)

img = cv2.resize(img, (1280, 1280))

# 将图片由(w,h)变为(1,img_channel,h,w)

img1 = img / 255.0

img1 -= mean

img1 /= std

img1 = img1.transpose(2, 0, 1)

img1 = np.expand_dims(img1, axis=0)

img1 = np.float32(img1)

ort_session = onnxruntime.InferenceSession(export_onnx_file)

for input_meta in ort_session.get_inputs():

print(input_meta)

for output_meta in ort_session.get_outputs():

print(output_meta)

ort_inputs = {ort_session.get_inputs()[0].name: img1}

ort_outs = ort_session.run(["output"], ort_inputs)

pred_map = ort_outs[0]

pred_map = torch.from_numpy(pred_map)

post_process = seg_detector_representer.SegDetectorRepresenter(

thresh=0.3, box_thresh=0.7, max_candidates=1000, unclip_ratio=1.5)

batch = {'shape': [(h, w)]}

box_list, score_list = post_process.db_post_process(batch, pred_map)

box_list, score_list = box_list[0], score_list[0]

if len(box_list) > 0:

idx = box_list.reshape(box_list.shape[0], -1).sum(axis=1) > 0 # 去掉全为0的框

box_list, score_list = box_list[idx], score_list[idx]

else:

box_list, score_list = [], []

img2 = draw_bbox(src_img, box_list)

cv2.imwrite('./result/001_result2.jpg', img2)

print('onnxruntime_infer done')

4.对生成的onnx模型进行优化,使用大老师提供的工具daquexian/onnx-simplifier),目前不支持动态输入,命令 python -m onnxsim dbnet.onnx dbnet-sim.onnx,因为生成onnx的时候固定了输入大小,所以不需要--input-shape参数;

5.编译ncnn(Tencent/ncnn),将onnx模型转ncnn,命令 ./onnx/onnx2ncnn dbnet-sim.onnx dbnet-sim.param dbnet-sim.bin;打开dbnet-sim.param,并可视化下模型结构,Interp层有5个参数;

6.对生成的ncnn模型进行优化,命令 ./ncnnoptimize dbnet-sim.param dbnet-sim.bin dbnet-opt.param dbnet-opt.bin 0;优化后Interp层参数如下所示,此时模型只能输入固定尺寸1280*1280,找到./src/layer/interp.cpp文件,可以看到0代表resize_type,1和2分别是高和宽的缩放比例,3和4分别是输出的高和宽,此时需要手动修改Interp层参数以便支持动态输入,同时删除最后一层的参数;

int Interp::load_param(const ParamDict& pd)

{

resize_type = pd.get(0, 0);

height_scale = pd.get(1, 1.f);

width_scale = pd.get(2, 1.f);

output_height = pd.get(3, 0);

output_width = pd.get(4, 0);

if (resize_type < 0 || resize_type > 3)

{

NCNN_LOGE("unsupported resize type %d", resize_type);

return -1;

}

return 0;

}

7.使用ncnn进行推理;

ncnn::Net dbnet;

// the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models

char *param = "./models/dbnet-opt.param";

char *bin = "./models/dbnet-opt.bin";

char *save_file = "./imgs/result2.jpg";

dbnet.load_param(param);

dbnet.load_model(bin);

const float mean_vals_dbnet[3] = { 0.485 * 255, 0.456 * 255, 0.406 * 255 };

const float norm_vals_dbnet[3] = { 1.0 / 0.229 / 255.0, 1.0 / 0.224 / 255.0, 1.0 / 0.225 / 255.0 };

const float unclip_ratio = 1.5;

const float box_thresh = 0.5;

const float thresh = 0.3;

const int min_size = 3;

int srcwid, srchi, wid, hi;

srcwid = bgr.cols;

srchi = bgr.rows;

wid = srcwid;

hi = srchi;

float scale = 1.f;

int inshortsize = srcwid;

if (wid > hi)

{

scale = (float)inshortsize / wid;

wid = inshortsize;

hi = hi * scale;

}

else

{

scale = (float)inshortsize / hi;

hi = inshortsize;

wid = wid * scale;

}

if (hi % 32 != 0)

{

hi = (hi / 32 + 1) * 32;

}

if (wid % 32 != 0)

{

wid = (wid / 32 + 1) * 32;

}

ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR,

srcwid, srchi, wid, hi);

in.substract_mean_normalize(mean_vals_dbnet, norm_vals_dbnet);

ncnn::Extractor dbnet_ex = dbnet.create_extractor();

dbnet_ex.set_num_threads(4);

dbnet_ex.input("input", in);

ncnn::Mat dbnet_out;

dbnet_ex.extract("output", dbnet_out);

// post_process

cv::Mat fmapmat(hi, wid, CV_32FC1);

memcpy(fmapmat.data, (float*)dbnet_out.data, wid * hi * sizeof(float));

cv::Mat norfmapmat;

norfmapmat = fmapmat > thresh;

std::vector rsbox;

rsbox.clear();

std::vector<:vector>> contours;

cv::findContours(norfmapmat, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);

for (int i = 0; i < contours.size(); ++i)

{

std::vector<:point> minbox;

float minedgesize, alledgesize;

get_mini_boxes(contours[i], minbox, minedgesize, alledgesize);

if (minedgesize < min_size)

continue;

float score = box_score_fast(fmapmat, contours[i]);

if (score < box_thresh)

continue;

std::vector<:point> newbox;

unclip(minbox, alledgesize, newbox, unclip_ratio);

get_mini_boxes(newbox, minbox, minedgesize, alledgesize);

if (minedgesize < min_size + 2)

continue;

for (int j = 0; j < minbox.size(); ++j)

{

minbox[j].x = (minbox[j].x / (float)wid * srcwid);

minbox[j].x = (std::min)((std::max)(minbox[j].x, 0), srcwid);

minbox[j].y = (minbox[j].y / (float)hi * srchi);

minbox[j].y = (std::min)((std::max)(minbox[j].y, 0), srchi);

}

rsbox.push_back(TextBox(minbox, score));

}

cv::Mat srcmat = bgr.clone();

for (int i = 0; i < rsbox.size(); ++i)

{

DrawMatText(srcmat, rsbox[i].Box);

}

cv::imwrite(save_file, srcmat);

参考:

移植mysql到安卓手机_记录dbnet文本检测转ncnn并移植到安卓上相关推荐

  1. 安卓手机备份_安卓手机微信记录误删除怎么恢复?大师在线指导:分五步操作!-安卓手机 ——快科技(驱动之家旗下媒体)-...

    安卓手机微信记录误删除怎么恢复?随着现在我国科学技术的逐步改善,并伴随我们国人的爱国情怀日益高涨,现在身边的亲朋好友大部分都已经开始使用我们国产的安卓手机,作为日常生活和工作交流的重要工具之一.那我们 ...

  2. android系统通话记录,安卓手机通话记录怎么恢复?快速恢复

    原标题:安卓手机通话记录怎么恢复?快速恢复 安卓手机通话记录怎么恢复?我们的手机上只要打过电话,一定就会有手机通话记录,那么问题就出现了,若是我们不小心将我们我们的手机通话记录给删除了,我们又比较需要 ...

  3. 删除的android电话怎么找回,通话记录删除了怎么恢复?安卓手机通话记录恢复方法...

    通话记录删除了怎么恢复?安卓手机通话记录恢复方法 2018年11月08日 17:35作者:黄页编辑:黄页 分享 我们和他人通话结束后,手机上会出现通话记录,但是要是不小心把这些通话记录删除了该怎么办? ...

  4. 安卓手机微信记录还能找回吗

    安卓手机微信记录还能找回吗 现在只要用智能手机,十个有八个都会安装微信app,走到哪里聊到哪里.随着微信的不断啊改版,功能也越来越强.人们使用微信的目的也各不相同,一开始也许只是为了和亲朋好友聊天,但 ...

  5. 安卓手机如何防盗_安卓手机也能像苹果一样!教你如何查看安卓手机电池损耗...

    随着手机越来越轻薄,而电池的续航能力也愈发变得重要起来,我们都知道电池的寿命是有限的,每次给装置充电,都会损耗电池,降低电池的总容量.很多网友就会很好奇自己手机的电池损耗到底有多大,其实这样的事情在苹 ...

  6. 苹果手机怎么定位安卓手机_苹果手机一定比安卓手机强?我反倒觉得安卓吊打苹果!...

    自古以来,安卓.苹果哪家强就是个争论不休的议题. 今天就来聊聊,安卓手机到底有什么比苹果手机好的地方. 首先安卓系统和苹果系统最大的不同就是安卓是开源的,而苹果系统闭源. 苹果的封闭系统就好比一艘诺亚 ...

  7. 安卓手机怎么设置蓝牙耳机弹窗动画_AirPods耳机也能在安卓手机与windows系统里,有超赞的体验,只需这两款软件...

    AirPods刚发布,就被吐槽是绿豌豆,网友调侃它是植物大战僵尸里豌豆也不是空穴来风.看这造型.不过很多网友在实际上手体验里,却发出真香警告,看来万物都无法离开真香定律啊.AirPods 的这种真香定 ...

  8. 如何root安卓手机_你的手机你做主!免 ROOT 卸载安卓手机预装APP

    蛮多安卓手机会在系统内预装一堆 "乱七八糟的" APP,一些APP大多用户都不会用到.这些预装的APP有些会长期在后台运行,不断的消耗你的运存.消耗电量,最难受的是这些预装APP, ...

  9. 如何连接安卓手机_安卓手机如何使用AirPods

    苹果公司推出的无线蓝牙耳机AirPods可以说是市面上最好的无线耳机,配合iPhone使用能够给你带来畅快舒适的体验.有很多小米华为oppo,vivo等安卓手机用户也在问了,安卓手机能够支持AirPo ...

最新文章

  1. 爬虫之requests模块超时参数timeout的使用
  2. 一个好域名的作用和价值
  3. 一个Linux下C线程池的实现
  4. 风行未来oracle,oracle 7月份更新CVE-2020-14645 复现&利用
  5. 2.3.7 操作系统之管程和java中实现管程的机制
  6. 绝地求生2017.7.27服务器维护,绝地求生大逃杀更新内容 7月27日更新了什么
  7. linux系统 mysql日志文件太大。造成数据库无法正常启动怎么解决
  8. java 创建学生信息类_java定义一个表示学生信息的类
  9. oracle 11g ocp 笔记(14)--数据库备份和恢复配置
  10. CSS基础汇总——点击标题跳转详细博客【学习笔记】
  11. git远程仓库中master及其余分支间代码的合并
  12. mysql+centos7+主从复制
  13. 【iOS】UI基础Day2-笔记(毛玻璃、帧动画、音效等)
  14. 高流明投影仪品牌,这份投影仪行业数据告诉你答案
  15. vue做音乐播放器完整功能
  16. UE官网ARPG游戏学习笔记1
  17. 《JavaScript权威指南第7版》第11章 JavaScript标准库
  18. 一位拖延症患者程序员的自我救赎!
  19. 程序员常用的16款火爆软件,你get到了哪些软件?
  20. unity 太阳自发光_unity动态改变自发光

热门文章

  1. 黑马python培训_要一张纯黑的图片。纯黑的。
  2. cisco 无线ap ME和LAP模式切换
  3. centos7.9-kvm-ESXi相关操作
  4. 逍遥模拟器连接不到android,逍遥安卓模拟器无法连接网络的解决方法
  5. 智慧养老的发展形势及智慧养老热点、痛点、难点
  6. 【luogu P5055】【模板】可持久化文艺平衡树
  7. nodejs入门--node的下载与安装
  8. Linux --VS Code安装与配置
  9. html网页设计一个简单的用户登录页面
  10. Python报错处理libpng warning: iCCP: cHRM chunk does not match sRGB