我正在尝试使用 MLApp
类(特别是 feval
函数)从 C# 调用 MATLAB 函数。
由于我是初学者,所以我在互联网上查找并找到了调用 MATLAB 函数的帮助。我只是简单地调用了一个 MATLAB 函数,该函数接受两个整数作为输入,并且 MATLAB 正确返回总和和差值。但我真正需要这样做的原因是将图像发送到 MATLAB 函数并执行一些分析。
到目前为止,我还没有在互联网上找到任何有用的东西。这个类可以用来将图像传递给 MATLAB 函数吗?如果可以,如何实现?如果不行还有什么办法吗?
MATLAB
function [x,y] = myfunc(a,b)
x = a + b;
y = a-b;
C#
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"cd 'D:\Program Files\MATLAB\MATLAB Production Server\R2015a\bin'");
object result = null;
matlab.Feval("myfunc", 2, out result, 3, 2);
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
最佳答案
一种简单的方法是将图像从 C# 应用程序保存到磁盘,然后调用 MATLAB(使用 COM Automation ,就像 shown 一样)通过将文件名作为字符串传递给它来评估图像处理函数。 MATLAB 函数只需按名称加载图像,对其进行处理,然后将结果保存为另一个图像。然后将 MATLAB 函数的输出图像路径返回给 C#,C# 最终会自行读取它。
所以在 C# 中你会这样做:
static void Main(string[] args)
{
var img = ...; // image data
string input_image = @"C:\path\to\image.png";
save_image(img, input_image); // save your image to disk
MLApp.MLApp matlab = new MLApp.MLApp();
object result = null;
matlab.Feval("my_processing_func", 1, out result, image);
object[] res = result as object[];
string output_image = (string) res[0];
var img_processed = load_image(output_image); // load image from disk
}
在 MATLAB 端,该函数执行以下操作:
function out_fname = my_processing_func(in_fname)
% read input image
img = imread(in_fname);
% ... apply some image processing functions
img = process(img);
% write resulting image to disk
out_fname = [tempname() '.png'];
imwrite(img, out_fname);
end
您还可以使用 PutFullMatrix
和 GetFullMatrix
函数在 C# 和 MATLAB COM 服务器之间传递数据。图像只是一个数值矩阵。请记住,MATLAB 按列优先顺序存储数组。
以下示例代码展示了如何使用 C# 从 MATLAB 工作区检索变量:https://stackoverflow.com/a/21123727/97160
第三种选择是使用 MATLAB Compiler SDK工具箱。这使您可以将 MATLAB 函数编译/打包到 .NET 程序集中,该程序集可以在没有 MATLAB 的计算机上使用(需要 MCR 运行时)。
关于c# - 将图像作为参数从 C# 发送到 matlab 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36517541/