我在Visual Studio 2012上使用C#Windows窗体应用程序,在MATLAB R2016a上使用MATLAB函数。我需要将Windows窗体应用程序中的PictureBox图像传递给MATLAB函数。我已经知道如何使用this link作为参考将MATLAB连接到C#。
但是当我在我的情况下使用这个方法时,我会得到这个COMException:
使用亮度时出错
输出参数太多。
这是我的C#代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace IP_Tasks
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void openImage_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}
private void openImage2btn_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox3.Load(openFileDialog1.FileName);
}
}
private void displayChannelbtn_Click(object sender, EventArgs e)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(@"cd
C:\Users\owner\Documents\MATLAB\ChannelBrightness");
// Define the output
object result = null;
matlab.Feval("Brightness",1,out result,pictureBox1.Image, brightnessChannel.SelectedIndex,brightnessOffsettxt.Text);
object[] res = result as object[];
byte[] data = (byte[]) res[0];
MemoryStream stream = new MemoryStream(data);
// Display result
Bitmap bitmap = new Bitmap(stream);
pictureBox2.Image = bitmap;
}
}
}
这是我的MATLAB功能代码:
function [ result ] = Brightness(Image, Ch, Offset)
newBuf=Image;
if (Ch == 0)
newBuf(:,:,1)= Image(:,:,1)+Offset;
elseif (Ch == 1)
newBuf(:,:,2)= Image(:,:,2)+Offset;
else
newBuf(:,:,3)= Image(:,:,3)+Offset;
end
result=newBuf;
end
我尝试在C#代码中添加断点以了解异常发生的位置,并且我发现它出现在此行中:
matlab.Feval("Brightness",1,out result,pictureBox1.Image,
brightnessChannel.SelectedIndex,brightnessOffsettxt.Text);
我之前在MATLAB上使用过MATLAB函数,但没有任何问题。