您的位置:首页 > 编程语言 > MATLAB

matlab与c#混合编程之图像参数传递

2016-09-08 16:42 357 查看
先上代码

//命名空间
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 MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using read_image;
using System.IO;
using preprocess;

//函数一:在该函数中读入图片
private void openImage_button(object sender, EventArgs e)
{
string fullPathname;
openFileDialog.Filter = "*.BMP,*.JPG;*.GIF|*.BMP;*.JPG;*.GIF"; ;
openFileDialog.ShowDialog();
this.textBox1.SelectedText = openFileDialog.FileName;
fullPathname = openFileDialog.FileName;
Image a = Image.FromFile(fullPathname);
bit_original = new Bitmap(a);
height = bit_original.Height;
width = bit_original.Width;
display_image(bit_original);
}

//函数二:在该函数中传递图片给matlab程序
private void process_button(object sender, EventArgs e)
{
try
{
byte[,,] rgb=new byte[3,height,width] ;

for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
rgb[0,i,j] = bit_original.GetPixel(j, i).R;
rgb[1,i,j] = bit_original.GetPixel(j, i).G;
rgb[2,i,j] = bit_original.GetPixel(j, i).B;
}
}
MWNumericArray matrix = rgb;
MWArray flag = 0;
ImageProcess prepro = new ImageProcess();
MWArray result = prepro.preprocess(matrix, flag);
Bitmap ans = new Bitmap(width,height);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
tmp = result[i+1,j+1].ToString();
if (tmp=="1")
ans.SetPixel(j, i, Color.White);
else
ans.SetPixel(j, i, Color.Black);
}
}
display_image(ans);

}
catch (Exception ex)
{
textBox1.SelectedText = ex.Message;
}
}

//函数三:在图片框控件中显示位图
private void display_image(Bitmap img)
{
Bitmap bit = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(bit);
g.DrawImage(img, new Rectangle(0, 0, bit.Width, bit.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
pictureBox1.Image = bit;
}


以上为程序主要的三个函数,实现功能为读入一个rgb图像,对图像进行灰度化二值化等处理后返回一个黑白图像,返回图像的像素值只有0和1。函数一为一个按钮的响应函数,该函数将选择的图片保存为Bitmap类型。函数二首先将Bitmap类型图片转化为三维Byte类型数据,然后转化为MWNumericArray类型。我封装的matlab类名是ImageProcess,调用的preprocess函数接受两个参数,一个是图片矩阵,另外一个是标志变量flag,将它定为MWArray类型的。

然后将result转化为Bitmap型以便在图片框中显示处理后的图片。但该种方法效率奇慢,正在探索如何用Lockbit方法给Bitmap对象赋值。

实际运行中有以下问题:

1. 如果一定要将编译平台选为64位的,否则会出错。



2. 混编的处理效率太低,需要找到提高效率的方法。

3. 要将MWArray.dll添加到引用里,并添加以下语句

using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息