Documentation Center

  • Trial Software
  • Product Updates

Generate Code from Application Containing Image Processing Functions

This example shows how to generate C/C++ code using MATLAB® Coder™ from MATLAB applications that use Image Processing Toolbox™ functions. The example describes how to setup your MATLAB environment, prepare your MATLAB code for code generation, and work around any issues that you might encounter in your MATLAB code that prevent code generation. For detailed information about code generation, see Code Generation Workflow in the MATLAB Coder documentation.

Setup Your Compiler

This example shows how to specify which C/C++ compiler you want to use with MATLAB Coder to generate code.

Use the mex function with the -setup option to specify the C/C++ compiler you want to use with MATLAB Coder.

mex -setup
MEX configured to use 'Microsoft Visual C++ 2010 (C)' for C language compilation.
Warning: The MATLAB C and Fortran API has changed to support MATLAB variables with more than 2^32-1 elements.  In the near future you will be required to update your code to utilize the new API. You can find more information about this at:

To choose a different C compiler, select one from the following:
Microsoft Visual C++ 2010 (C)  mex -setup:C:\matlab\bin\win64\mexopts\msvc2010.xml C
Intel Visual C++ 12 with Microsoft Visual Studio 2008 (C)  mex -setup:C:\matlab\bin\win64\mexopts\intel_c_12_vs2008.xml C
Intel Visual C++ 12 with Microsoft Visual Studio 2010 (C)  mex -setup:C:\matlab\bin\win64\mexopts\intel_c_12_vs2010.xml C

To choose a different language, select one from the following:
 mex -setup C++ 
 mex -setup FORTRAN

Prepare Your MATLAB Code for Code Generation

This example shows how to use the MATLAB Coder app to evaluate your code's readiness for code generation. For example, the code may use functions that are not enabled for code generation.

For this example, copy the following code into a file and save it, giving it the name cellDetectionMATLAB.m. This code is a modified version of the Image Processing Toolbox example Detecting a Cell Using Image Segmentation (Detecting a Cell Using Image SegmentationDetecting a Cell Using Image Segmentation). To illustrate code generation, this version of the example removes the display code.

function BWfinal = cellDetectionMATLAB(I)
%cellDetectionMATLAB - detect cells using image segmentation.

[~, threshold] = edge(I, 'sobel');
fudgeFactor = .5;
BWs = edge(I,'sobel', threshold * fudgeFactor);

se90 = strel('line', 3, 90);
se0 = strel('line', 3, 0);

BWsdil = imdilate(BWs, [se90 se0]);

BWdfill = imfill(BWsdil, 'holes');

BWnobord = imclearborder(BWdfill, 4);

seD = strel('diamond',1);
BWfinal = imerode(BWnobord,seD);
BWfinal = imerode(BWfinal,seD);

Test the example code with a sample image. For this example, use the cell.tif file, included with the Image Processing Toolbox (matlab\toolbox\images\imdata\cell.tif).

I = imread('cell.tif');

Iseg = cellDetectionMATLAB(I);

% Display the original image and the segmented image side-by-side.

Create a copy of the MATLAB function for which you want to generate C/C++ code. Since you modify this code for code generation, it is good to work with a copy.


As a first step, change the name of the function in the function signature to match the file name and add the MATLAB Coder compilation directive %#codegen at the end of the function signature. This directive instructs the MATLAB code analyzer to diagnose issues that would prohibit successful code generation.

function BWfinal = cellDetectionCodeGeneration(I) %#codegen

Open the MATLAB Coder app. In MATLAB, select the Apps tab, navigate to Code Generation and click the MATLAB Coder app. (Alternatively, you can enter coder at the MATLAB command prompt.)

In the MATLAB Coder Project dialog, create a new code generation project. This example names the project cellDetection.prj. Click OK to create the project and open the MATLAB Coder dialog box.

Add your MATLAB code file to the project. Click Add files and, for this example, select cellDetectionCodeGeneration.m.

Define the size and data type of the inputs to your function. When you add the file, MATLAB Coder determines the input arguments required by your file and populates the entry-point area. Every input must be specified to be of fixed size, variable size or a constant. For this example, the function accepts one input—an image I. To define the size of this input image, click the Click to define label.

There are several ways to specify the size of your input argument. For fixed size inputs, choose the class and size of the input. For variable-sized inputs, select the class and specify the upper bound on the size. For an unbounded input, select the unbounded option (:Inf). To define a constant, choose the Define Constant option. This example specifies the size and class of the input by providing MATLAB Coder with an example of the input. Click Define by Example and specify the example imread('cell.tif'). (For more information about defining inputs, see the MATLAB Coder documentation.)

After you specify the size and class of the input, MATLAB Coder displays the View code generation readiness issues option, if it finds issues that need addressing. Click this option to view issues that prevent you from generating code.

MATLAB Coder opens the Project Code Generation Readiness dialog, providing a readiness score and a list of issues that must be addressed. For this example, MATLAB Coder highlights one issue: the example code uses an Image Processing Toolbox function (imclearborder) that has not been enabled for code generation.

To address this readiness issue, you must replace the call to imclearborder with a call to another function that can perform the same operation but that uses functions that have been enabled for code generation. The example uses imclearborder to remove connected objects on the border of the image. This task can be accomplished using a combination of several other Image Processing Toolbox functions, such as imreconstruct, padarray and imerode, which all support code generation. The following is the code for this new function, named my_imclearborder.m. Note that this function does not accept a connectivity argument.

function out = my_imclearborder(im)%#codegen
% my_imclearborder - helper function algorithmically equivalent to
% imclearborder.

marker = im;

% Define connectivity matrix for 4-connectivity.
conn = [0 1 0;...
        1 1 1;...
        0 1 0];
% Find elements of marker connected to outside.
imb = padarray(true(size(marker)),[1 1],0,'both');
imb = imerode(imb,conn);
out = imb(2:end-1,2:end-1);

% Set all elements of the marker image that are not connected to the
% outside to the lowest possible value.
marker(out) = false;

out = imreconstruct(marker, im, conn);

out = im & ~out;

Modify the example code file, cellDetectionCodeGeneration.m, to use this new function. Replace the call to imclearborder with a call to the my_imclearborder function. Note that you must delete the connectivity argument in the call.

function BWfinal = cellDetectionCodeGeneration(I) %#codegen
BWnobord = my_imclearborder(BWdfill);

When you have addressed all readiness issues, the MATLAB Coder dialog no longer displays the View code generation readiness issues link.

Generate Code

This example shows how to generate C/C++ code from MATLAB code, using MATLAB Coder. Note that, even though you performed the MATLAB Coder readiness checks, additional issues might arise during the build process that can prevent code generation. While the readiness checks look at function dependencies to determine readiness, the build process examines coding patterns. This example illustrates how to address issues that arise in the build process that prevent successful code generation.

Select the Build tab and click Build.

Initially, the build fails.

Click Open Error Report to get details of the errors. The report lists the errors and uses red underlining to highlight the location of errors in the source code. For this example, the first error indicates that on line 11 the code passes in an array of objects and code generation does not support arrays of objects passed as arguments. The remaining errors are a result of this first error.

Address issues identified in the report. For this example, you must modify the call to imdilate to avoid passing an array of strel objects. This is accomplished by replacing the single call to imdilate, where the example passes an array of strel objects, with two separate calls to imdilate, as shown in the following code snippet.

BWsdil = imdilate(BWs, se90);
BWsdil = imdilate(BWsdil, se0);

With that change, the build process succeeds and MATLAB Coder generates code.

By default, MATLAB Coder generates a MEX function with the name cellDetectionCodeGeneration_mex, but you can choose to generate other types of code. Use the Output type menu to generate a C/C++ static library, dynamic library, or standalone executable. MATLAB Coder creates a codegen subfolder in your work folder that contains the generated output. For more information about generating code, see the MATLAB Coder documentation.

Test your code. Run the mex version of your function and then compare the output with the regular MATLAB code.

im = imread('cell.tif');
out = cellDetectionCodeGeneration_mex(im);

ans =


If you chose the C/C++ Dynamic Library option, MATLAB Coder generates the following interface. This interface can be used to integrate with an external application:

type codegen\dll\cellDetectionCodeGeneration\cellDetectionCodeGeneration.h
 * cellDetectionCodeGeneration.h
 * Code generation for function 'cellDetectionCodeGeneration'

/* Include files */
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include "rtwtypes.h"
#include "cellDetectionCodeGeneration_types.h"

/* Function Declarations */
#ifdef __cplusplus
extern "C" {
extern void cellDetectionCodeGeneration(const unsigned char I[30369], boolean_T BWfinal[30369]);
#ifdef __cplusplus
/* End of code generation (cellDetectionCodeGeneration.h) */

The function signature exposed indicates there are two inputs. The first input I is expected to be an unsigned char with 30369 elements. This is used to pass the input image on which cell detection is to be performed. The type of the input image in MATLAB (uint8) is represented as an unsigned char. The size of the image is 159 x 191, i.e. 30369 elements. The number of elements is specified through the interface since the input was defined to be fixed size. The second input BWfinal is expected to be a boolean_T with 30369 elements. This is used to pass a pointer to the output image.

Note that there is a difference in the way MATLAB and C store arrays in memory. MATLAB stores arrays in column-major order and C stores arrays in row-major order. To illustrate, consider the following array:

[ 1  2
  3  4 ]

MATLAB stores the array in memory as [1 3 2 4 ] where C stores the elements as [1 2 3 4 ]. You must account for this difference when working with arrays.

You can also generate a standalone executable using the "C/C++ Executable" option. In this case a main function that invokes the generated code must be specified. Note that there are no ready-made utilities for importing data. For an example, refer to the Using Dynamic Memory Allocation for an "Atoms" Simulation in the MATLAB Coder documentation.

Was this topic helpful?