MATLAB Answers


Generating mex file from Matlab code containing regionprops

Asked by Michael
on 12 Jun 2012

I'm trying to generate a mex file from Matlab code without much success.

The function I want to compile calls the function regionprops from the Image Processing Toolbox. Since this function is not supported by Matlab Coder, I am declaring it as extrinsic. My problem is declaring the output of regionprops. The output is a vector of structures with a single field of type double and variable size (1D vector always). An example of my code follows:

function outVar = MyFunction( img ) %#codegen
coder.extrinsic( 'regionprops' );
% Some kind of declaration for properties should be added here %
properties = regionprops( img, 'PixelIdxList' );
outVar = 0;
for i = 1:length( properties )
    outVar = outVar + properties(i).PixelIdxList( end );

The question is, how to declare the variable "properties" and what kind of flags to use during compilation so that a structure with a variable sized field can be compiled.

Any help is greatly appreciated.



Ashish Uthama
on 12 Jun 2012

could you say more about the full application? Why not write a function which interfaces with regionprops and declare that function extrinsic?

on 13 Jun 2012

I am writing a computer vision application. I have an input image and its segmentation with a different label on each region. I use regionprops on the segmentation to calculate information on each segment, and then I use this information as features for each segment.

Your suggestion of declaring regionprops as extrinsinc is what I want to do. The problem is that I don't know how to declare the output of regionprops so that I can index it afterwards. Also some of the output in the struct returned by regionprops may be dynamic length arrays (like PixelIdxList), I am having trouble declaring these dynamic length vectors.

1 Answer

Answer by Ashish Uthama
on 13 Jun 2012
 Accepted answer


function outVar = myapp %#codegen
idxList    = 1;
properties = struct('PixelIdxList',idxList);
BW = imread('text.png');
properties  = regionprops(BW, 'PixelIdxList');
outVar = 0;
for i = 1:length( properties )
    outVar = outVar + properties(i).PixelIdxList( end );


Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!