Search code examples
matlabimage-processingmatlab-coder

Problems with using mxarrays with the step function in MATLAB Coder


I'm trying to convert my image processing code on MATLAB into C by using MATLAB coder. using imread needs a coder.entrinsic declaration. However, this means that the output to imread will be an mxArray. This is a problem as I cannot use this with the step function. The error report from code generation is shown below:

Does anyone know a way around this?


Solution

  • When using coder.extrinsic, functions declared as extrinsic will return mxArray types. If you pass these to other Matlab functions, Coder will resolve everything well, but if you use them with your own functions or in any way try to manipulate them, you need to help Coder resolve them into a known type. You do this by pre-defining a variable and copying the mxArray into it, which will allow Coder to correctly convert to a standard data type. If you know the exact size beforehand, you can preallocate the variable before the call and skip the copy, but in this case it may be a bit trickier.

    In the case of your function, I assume you have a call somewhere that looks like:

    I = imread([some paramaters]);
    

    We need to get the mxArray type from the call to imread, then determine its dimensions so that another variable can be allocated in a native type. The determination of the mxArray dimensions using the size function itself needs to have a preallocated variable so that size does not return a mxArray also. Here are the steps:

    coder.extrinsic('imread');
    Itemp = imread([some paramaters]);
    idims = zeros(1,3); %Need to preallocate idims so it does not become an mxArray
    idims = size(Itemp)
    I = coder.nullcopy(zeros(idims, 'uint8'));  % Allocate but do not initialize an array of uint8 values of the same size as Itemp
    I = Itemp; % Copy the data from the mxArray into the final variable.
    

    If you know the exact size of the image before the call to imread, you can skip the copy and the second variable and simply preallocate the variable I to the correct size, but this is not typically the case for an image read.

    You can see a little more information on how to do this in the following help document from Mathworks:

    http://www.mathworks.com/help/simulink/ug/calling-matlab-functions.html#bq1h2z9-47