How to using matlab function to process image in c# (visual studio) ?

32 views (last 30 days)
Hi All,
I am try to use Matlab function in c# inside visual studio 2023.
but i got the error when call the fucntion.
I hope someone could help me to fix this error.
this is my step.
  1. Export the matlab function to .Net by using deploytool in Matlab.
  2. Add dll file to reference in C# project
  3. Then call matlab function to...
I attached matlab function and my c# code, dll file of matlab function as well.
Thanks and Regards
Han

Accepted Answer

Sugandhi
Sugandhi on 14 May 2023
Hi Jenifer,
I understand that you are trying to use Matlab function in c# inside visual studio 2023.
You can use MATLAB functions in C# (Visual Studio) by using the MATLAB Engine for .NET. The MATLAB Engine for .NET is a library that allows you to call MATLAB functions and execute MATLAB code from .NET applications.
To use the MATLAB Engine for .NET in your C# (Visual Studio) project, follow these steps:
1. Install the MATLAB software on your computer.
2. In Visual Studio, create a new .NET project (either a Console Application or a Windows Forms Application).
3. Add a reference to the MATLAB Engine for .NET library (`MathWorks.MATLAB.NET.Utility.dll`). You can find this library in your MATLAB installation folder (typically in the `toolbox\dotnetbuilder\bin\win64\v{version}` folder).
4. In your C# code, add the following using statement to import the `MathWorks.MATLAB.NET.Utility` namespace: `using MathWorks.MATLAB.NET.Utility;`
5. Instantiate a new `MLApp` object as follows: `MLApp matlab = new MLApp();`
6. Use the `mlab.Execute` method to execute MATLAB code, or use the `mlab.Feval` method to call MATLAB functions.
Here is an example of how to use the MATLAB Engine for .NET to call a MATLAB function from C#:
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
// ...
// Instantiate a new MLApp object
MLApp matlab = new MLApp();
// Call a MATLAB function
MWArray result = null;
matlab.Feval("myfunction", 1, out result, arg1, arg2, arg3);
// Convert the result to a C# array
double[] resultArray = (double[])result.ToArray();
In this example, `myfunction` is a MATLAB function that takes three input arguments (`arg1`, `arg2`, and `arg3`) and returns a 1-by-n array. The `Feval` method is used to call the function and return the result. The result is then converted to a C# array using the `ToArray` method of the `MWArray` class.
Make sure to replace `myfunction`, `arg1`, `arg2`, and `arg3` with the appropriate function name and input arguments for your use case.
Regarding ERROR:
The "Initialization Error: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception" error message typically indicates that there is a problem with the installation or configuration of the MATLAB Runtime environment required to use the MATLAB Engine API for .NET in your C# project.
To resolve this error, you can try the following steps:
1. Make sure that you have installed the correct version of the MATLAB Runtime environment for your version of MATLAB and Visual Studio. You can download the MATLAB Runtime from the MathWorks website.
2. Make sure that the MATLAB Runtime is properly configured on your system. This means that the environment variable 'PATH' must be updated correctly. You can follow the steps provided in the following MathWorks Support article to configure the MATLAB Runtime on your system: https://www.mathworks.com/help/compiler_sdk/dotnet/ug/deployment.html
3. Make sure that the required dependencies for the MATLAB Engine API for .NET are installed on your system. These include the Microsoft Visual C++ Runtime Library and the Microsoft .NET Framework.
4. Check if you have set up the correct version of the MATLAB Compiler Runtime (MCR). If you are unsure, you can use the command "mcrinstaller" in your MATLAB prompt to check the installed MCR versions.
  1 Comment
Jenifer NG
Jenifer NG on 15 May 2023
Edited: Jenifer NG on 15 May 2023
Thanks You for your support!
I fix the error but when i try to processed the image in c# with this matlab function the output image value is black only 0 values.
If you have time, could you help to lookat my code?
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using MathWorks.Im2;
using MathWorks.MATLAB.NET.Arrays;
namespace Net_Mat
{
public partial class Form1 : Form
{
imageProcessing improcessing = null;
public Form1()
{
InitializeComponent();
}
private void LoadImage_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.jpg;*.jpeg;*.png;*.gif;*.bmp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string imagePath = openFileDialog.FileName;
pictureBox1.Image = Image.FromFile(imagePath);
}
}
private void processImage_Click(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(pictureBox1.Image);
try
{
improcessing = new imageProcessing();
}
catch (Exception ex)
{
MessageBox.Show($"Initialization Error: {ex.InnerException.Message}");
return;
}
int width = bitmap.Width;
int height = bitmap.Height;
byte[,] imageArray = new byte[height, width];
// Populate the array
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
Color pixel = bitmap.GetPixel(j, i);
imageArray[i, j] = pixel.R; // Use the red channel as grayscale intensity
}
}
MWNumericArray mwImage = new MWNumericArray(imageArray);
MWArray processedImage = improcessing.thresholdImage(mwImage);
bool[,] boolArray = (bool[,])((MWLogicalArray)processedImage).ToArray();
// Convert the 2D boolean array to a Bitmap
Bitmap bitmap2 = new Bitmap(boolArray.GetLength(1), boolArray.GetLength(0)); // width, height
for (int i = 0; i < boolArray.GetLength(0); i++)
{
for (int j = 0; j < boolArray.GetLength(1); j++)
{
bitmap.SetPixel(j, i, boolArray[i, j] ? Color.White : Color.Black);
}
}
pictureBox2.Image = bitmap2;
// Save the processed image to a specific folder
string saveFolderPath = @"C:\Users\hanav\Desktop\New folder";
string saveFilePath = Path.Combine(saveFolderPath, "processed_image.Bmp");
try
{
bitmap2.Save(saveFilePath, System.Drawing.Imaging.ImageFormat.Bmp);
MessageBox.Show("Image saved successfully.");
}
catch (Exception ex)
{
MessageBox.Show($"Error saving image: {ex.Message}");
}
}
}
}
Thanks so much!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!