tensorflow转NCNN

2024-06-03 22:32
文章标签 tensorflow ncnn

本文主要是介绍tensorflow转NCNN,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于NCNN见NCNN cmake VS2017 编译

目前腾讯的NCNN没有tensorflow2ncnn的工具,目前有一种解决方案是把tensorflow的.pb模型转为coreml模型,接着转为onnx模型,最后转成NCNN。

下面提供一个tensorflow转NCNN的方法,据说在基于MobileNetV2修改的模型上测试通过,模型输出正确;我自己训练的基于ResNet结构的简单分类模型,用该方法试了,模型输出也正确。该方法的步骤如下:

1、使用freeze_graph.py生成.pb模型;参见【tensorflow】生成.pb文件

2、使用tf-coreml将tf模型转换为coreml模型

安装tf-coreml所需依赖项如下:
Python
tensorflow >= 1.5.0
coremltools >= 0.8
numpy >= 1.6.2
protobuf >= 3.1.0

因为我是windows,安装coremltools要用如下命令(电脑里要有安装git):

pip install git+https://github.com/apple/coremltools
pip install -U tfcoreml

tfcoreml安装好了,用如下脚本把tf的.pb模型转为coreml模型

import tfcoreml as tf_convertertf_converter.convert(tf_model_path = r'C:\software\tensorflow-onnx-master\examples\WorkCardModel.pb', mlmodel_path = r'C:\software\tensorflow-onnx-master\examples\my_model.mlmodel', output_feature_names = ['resnet/predictions/Reshape_1:0'])

转换成功,会看到如下结果:

Core ML model generated. Saved at location: C:\software\tensorflow-onnx-master\examples\my_model.mlmodel Core ML input(s): [name: "input_x__0"
type {multiArrayType {shape: 3shape: 96shape: 96dataType: DOUBLE}
}
]
Core ML output(s): [name: "resnet__predictions__Reshape_1__0"
type {multiArrayType {shape: 3dataType: DOUBLE}
}
]

3、使用WinMLTools将coreml转换为onnx模型

pip install -U winmltools

安装好winmltools之后,执行如下脚本:

from coremltools.models.utils import load_spec
from winmltools import convert_coreml
from winmltools.utils import save_model# Load model file
model_coreml = load_spec(r'C:\software\tensorflow-onnx-master\examples\my_model.mlmodel')# Convert it!
# The automatic code generator (mlgen) uses the name parameter to generate class names.
model_onnx = convert_coreml(model_coreml, 7, name='ExampleModel')# Save the produced ONNX model in binary format
save_model(model_onnx, r'C:\software\tensorflow-onnx-master\examples\example.onnx')

4、在之前已经编译好的目录下C:\software\ncnn\build-vs2017\tools\onnx,使用onnx2ncnn将onnx模型转换为ncnn

# 默认生成ncnn.bin和ncnn.param
onnx2ncnn.exe example.onnx# 或者制定名称
onnx2ncnn.exe example.onnx example.bin example.param

生成两个文件:ncnn.bin和ncnn.param

基于ncnn/examples里的squeezenet.cpp修改的三分类模型ncnn.bin和ncnn.param使用代码如下:

// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>#include "platform.h"
#include "net.h"
#if NCNN_VULKAN
#include "gpu.h"
#endif // NCNN_VULKANstatic int detect_squeezenet(const cv::Mat& bgr, std::vector<float>& cls_scores)
{ncnn::Net squeezenet;#if NCNN_VULKANsqueezenet.opt.use_vulkan_compute = true;
#endif // NCNN_VULKANsqueezenet.load_param("ncnn.param");squeezenet.load_model("ncnn.bin");ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, 96, 96);const float mean_vals[3] = { 0.f, 0.f, 0.f };const float norm_vals[3] = { 1.0 / 255, 1.0 / 255, 1.0 / 255 };in.substract_mean_normalize(mean_vals, norm_vals);ncnn::Extractor ex = squeezenet.create_extractor();ex.input("input_x__0", in);ncnn::Mat out;ex.extract("resnet__predictions__Reshape_1__0", out);cls_scores.resize(out.w);for (int j = 0; j < out.w; j++){cls_scores[j] = out[j];}return 0;
}int main(int argc, char** argv)
{if (argc != 2){fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);return -1;}const char* imagepath = argv[1];cv::Mat m = cv::imread(imagepath, 1);if (m.empty()){fprintf(stderr, "cv::imread %s failed\n", imagepath);return -1;}#if NCNN_VULKANncnn::create_gpu_instance();
#endif // NCNN_VULKANstd::vector<float> cls_scores;double start, timeConsume;start = static_cast<double>(cv::getTickCount());for (int i = 0; i < 1; i++)detect_squeezenet(m, cls_scores);for(int i = 0; i < 3; i++)std::cout << cls_scores[i] << std::endl;timeConsume = ((double)cv::getTickCount() - start) / cv::getTickFrequency();printf("time: %f s\n", timeConsume);#if NCNN_VULKANncnn::destroy_gpu_instance();
#endif // NCNN_VULKANreturn 0;
}

 

参考:

将其他模型文件转化成Core ML模型文件(PB)

https://github.com/Tencent/ncnn/issues/5

tensorflow模型转ncnn模型

Convert ML models to ONNX with WinMLTools

这篇关于tensorflow转NCNN的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1028289

相关文章

win10不用anaconda安装tensorflow-cpu并导入pycharm

记录一下防止忘了 一、前提:已经安装了python3.6.4,想用tensorflow的包 二、在pycharm中File-Settings-Project Interpreter点“+”号导入很慢,所以直接在cmd中使用 pip install -i https://mirrors.aliyun.com/pypi/simple tensorflow-cpu下载好,默认下载的tensorflow

稀疏自编码器tensorflow

自编码器是一种无监督机器学习算法,通过计算自编码的输出与原输入的误差,不断调节自编码器的参数,最终训练出模型。自编码器可以用于压缩输入信息,提取有用的输入特征。如,[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]四比特信息可以压缩成两位,[0,0],[1,0],[1,1],[0,1]。此时,自编码器的中间层的神经元个数为2。但是,有时中间隐藏层的神经元

Tensorflow实现与门感知机

感知机是最简单的神经网络,通过输入,进行加权处理,经过刺激函数,得到输出。通过输出计算误差,调整权重,最终,得到合适的加权函数。 今天,我通过tensorflow实现简单的感知机。 首先,初始化变量:     num_nodes = 2     output_units = 1     w = tf.Variable(tf.truncated_normal([num_nodes,output

Tensorflow lstm实现的小说撰写预测

最近,在研究深度学习方面的知识,结合Tensorflow,完成了基于lstm的小说预测程序demo。 lstm是改进的RNN,具有长期记忆功能,相对于RNN,增加了多个门来控制输入与输出。原理方面的知识网上很多,在此,我只是将我短暂学习的tensorflow写一个预测小说的demo,如果有错误,还望大家指出。 1、将小说进行分词,去除空格,建立词汇表与id的字典,生成初始输入模型的x与y d

Deepin Linux安装TensorFlow

Deepin Linux安装TensorFlow 1.首先检查是否有Python,一般deepin系统都自带python的。   2.安装pip Sudo appt-get install pip来安装pip,如果失败就先更新一下sudo apt-get updata,然后再sudo apt-get install pip,如果定位失败,就sudo apt-get install pyth

终止distributed tensorflow的ps进程

1.直接终止: $ ps -ef | grep python | grep 文件名 | awk {'print $2'} | xargs kill文件名为当前运行的程序,名称如:distribute.py 2.查找pid,后kill: $ ps -ef | grep python | grep 文件名 | awk {'print $2'}$ kill -9 <pid>

Python(TensorFlow和PyTorch)两种显微镜成像重建算法模型(显微镜学)

🎯要点 🎯受激发射损耗显微镜算法模型:🖊恢复嘈杂二维和三维图像 | 🖊模型架构:恢复上下文信息和超分辨率图像 | 🖊使用嘈杂和高信噪比的图像训练模型 | 🖊准备半合成训练集 | 🖊优化沙邦尼尔损失和边缘损失 | 🖊使用峰值信噪比、归一化均方误差和多尺度结构相似性指数量化结果 | 🎯训练荧光显微镜模型和对抗网络图形转换模型 🍪语言内容分比 🍇Python图像归一化

【tensorflow CNN】构建cnn网络,识别mnist手写数字识别

#coding:utf8"""构建cnn网络,识别mnistinput conv1 padding max_pool([2,2],strides=[2,2]) conv2 x[-1,28,28,1] 卷积 [5,5,1,32] -> [-1,24,24,32]->[-1,28,

【tensorflow 全连接神经网络】 minist 手写数字识别

主要内容: 使用tensorflow构建一个三层全连接传统神经网络,作为字符识别的多分类器。通过字符图片预测对应的数字,对mnist数据集进行预测。 # coding: utf-8from tensorflow.examples.tutorials.mnist import input_dataimport tensorflow as tfimport matplotlib.pyplot

【tensorflow 使用错误】tensorflow2.0 过程中出现 Error : Failed to get convolution algorithm

如果在使用 tensorflow 过程中出现 Error : Failed to get convolution algorithm ,这是因为显卡内存被耗尽了。 解决办法: 在代码的开头加入如下两句,动态分配显存 physical_device = tf.config.experimental.list_physical_devices("GPU")tf.config.experiment