C#调用libtorch + opencv

本文档介绍了如何在VS2017中创建C++ DLL项目,结合libtorch 1.5.0和opencv 4.0.1进行深度学习模型部署。详细步骤包括创建新项目、编写源文件、加入头文件、定义模块文件及生成解决方案。在C#端,需将libtorch的DLL文件放入项目bin目录,并创建C#控制台应用进行调用,可能会遇到DLL加载失败的问题,通常是因为路径错误或缺失依赖库。
上文在VS上配置好了libtorch,紧接着就是把这个放到实验室的项目中,
而实验室开发的应用程序目前使用的是C#,
所以需要使用C#调用CPP程序,也就是先将CPP程序编写为动态链接库进行调用

深度学习模型部署:VS2017(c++) + libtorch(1.5.0) + opencv(4.0.1)

参考资料

加入libtorch

1.创建新项目在这里插入图片描述

然后会弹出对话框,在应用程序类型中选择:

  • 应用程序类型选择DLL,

  • 附加项选择预编译头文件和SDL。
    在这里插入图片描述

2.编写源文件

// Project1.cpp : 定义 DLL 应用程序的导出函数。

#include "stdafx.h"

#include <opencv2/opencv.hpp>    
#include <iostream>
#include "opencv2/core/core.hpp"
#include <opencv2/imgproc/imgproc.hpp>  
#include "opencv2/highgui/highgui.hpp"
#include <cv.h> 
#include "Project1.h"
#include <torch/script.h>
using namespace cv;

void LoadModel() {
	torch::jit::script::Module module;
	try {
		// Deserialize the ScriptModule from a file using torch::jit::load().
		module = torch::jit::load("D:/Users/98747/Downloads/torch_script_eval.pt");
	}
	catch (const c10::Error& e) {
		std::cerr << "error loading the model\n";
		return ;
	}
	Mat image;
	image = imread("D:/Users/98747/Desktop/PIC/dog2.jpg");
	std::vector<int64_t> sizes = { 1, 3, image.rows, image.cols };
	at::TensorOptions options(at::ScalarType::Byte);
	at::Tensor tensor_image = torch::from_blob(image.data, at::IntList(sizes), options);
	tensor_image = tensor_image.toType(at::kFloat);
	at::Tensor result = module.forward({ tensor_image }).toTensor();

	auto max_result = result.max(1, true);
	auto max_index = std::get<1>(max_result).item<float>();
	int res = (int)max_index;
	if (res) {
		std::cout << "cat" << std::endl;
	}
	else {
		std::cout << "dog" << std::endl;
	}
	return ;
}

注意点:

  1. 这里的函数编写,可以按照C#中设定的接口来写,也就是C#中需要什么这里就传什么参数,返回什么参数
  2. 不需要main()函数了,本来就只是当做一个库函数

3.加入头文件

头文件有固定的格式;

#pragma once
#ifdef PROJECT1_EXPORTS
#define PROJECT1_EXPORTS __declspec(dllexport)

#else
#define PROJECT1_EXPORTS __declspec(dllexport)
#endif // DEMO_EXPORTS

PROJECT1_EXPORTS void LoadModel();

4.加入模块定义文件.def

在这里插入图片描述
同理:也有固定的格式:

LIBRARY XXX  			// 库名为XXX,省略库名即默认为动态链接库文件名
EXPORTS					// 输出 
   LoadModel @1 		// 带序号的输出函数名 

5.生成解决方案在这里插入图片描述

done!

C#调用

1.准备工作:

  1. 将libtorch中的所有dll文件放到项目文件夹中bin目录下
  2. 将刚才的Project1.dll放到项目文件夹中bin目录下

2.创建C#控制台应用

添加程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;//***********需要手动添加***********

namespace demo_cpp
{
    class Program
    {
        [DllImport(@"D:\C#_DATA\demo_cpp\demo_cpp\bin\Project1.dll", EntryPoint = "LoadModel")]
        public static extern void LoadModel();
        static void Main(string[] args)
        {
            Console.WriteLine("C#调用CPP");
            LoadModel();
            Console.ReadKey();
        }
    }
}

3.结果

在这里插入图片描述

可能的报错:

有可能会有报错:无法加载DLL。
在这里插入图片描述
两种可能

  1. Project1.dll路径没写对
  2. libtorch所需要的dll文件没放进去
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值