从 OpenCV dnn 导出模型训练参数(按caffe格式)

先从Torch、tensorflow 等导入模型:

    String t7model="mosaic.t7";//Torch
	// 加载模型
	dnn::Net net = cv::dnn::readNetFromTorch(t7model.c_str());

然后读出各层名称:

	std::vector lname=net.getLayerNames() ;

按名称得到id,:

	    int id=net.getLayerId(lname[i]);

按id得到各层训练参数:

	Mat blob=net.getParam(id, j);

然后按caffe格式保存。

完整cpp:

//从OpenCV导出风格模型训练参数: 加载模型 -> 取得各层名和参数 -> 导出成caffe 格式
#include 
#include 
#include 
#include 

using namespace cv;
using namespace std;
 
//字符串是否包含子串
bool endsWith(const String &str, const char *substr)
{
	int lc=str.length() - strlen(substr);
	if (lc>=0)//子串<母串(长度)
	{
		return str.rfind(substr) == lc;
	}
	else//子串>母串
		return false;
}



//保存一个参数,这里只有 2、4 维的情况
void save_mat (ofstream& fout,Mat& b)  
{  
	fout <<"  blobs {\n";
	if(b.isContinuous()) //连续
	{
		
		float* outData=b.ptr(0);
		if(b.dims==2)
		{
			for (int i=0; i lname=net.getLayerNames() ;
    for (size_t i = 0; i != lname.size(); i++)
    {
        cout<<"层名:"<

 

你可能感兴趣的:(风格转换)