Yes, it is possible to call a MATLAB script or function from C++ and retrieve the output, even if they are in different files. To achieve this, the MATLAB Engine API can be utilized.
1. Ensure that the "MatlabEngine.hpp" header file, which is part of the C++ Engine API provided by MATLAB, is included. Functions can be invoked using the feval and fevalAsync member functions of the matlab::engine::MATLABEngine class.
2. The Image Processing Toolbox can be accessed within MATLAB functions when called from C++. Ensure that the Toolbox is installed and the MATLAB engine is initialized. The engEvalString function allows execution of commands in the MATLAB environment from a C++ application. The syntax is as follows:
#include “engine.h”
int engEvalString(Engine *ep, const char *string)
3. When executing MATLAB code from C++, the output is returned as mxArray objects, which are MATLAB's primary data representation. A MATLAB matrix can be mapped to a C++ matrix using the following approach:
%% Get matrix dimensions
mwSize numRows = mxGetM(matlabMatrix);
mwSize numCols = mxGetN(matlabMatrix);
%% Get pointer to data
double *data = mxGetPr(matlabMatrix);
%% Map to C++ vector of vectors
std::vector<std::vector<double>> cppMatrix(numRows, std::vector<double>(numCols));
for (mwSize i = 0; i < numRows; ++i) {
for (mwSize j = 0; j < numCols; ++j) {
cppMatrix[i][j] = data[i + j * numRows]; // Column-major to row-major
}
}
4. Images are typically represented as 2D or 3D arrays of unsigned char (for grayscale or RGB images). Load the image data in C++ as an unsigned char array. Use mxCreateNumericMatrix to create an mxArray to hold the image data. Copy the image data into the mxArray and use engPutVariable to pass the mxArray to the MATLAB workspace.
Here are the links for the documentation for the same:
