%% Using PARFOR to Speed Up an Image Contrast Enhancement Algorithm
% This example shows how to generate a standalone C library from MATLAB code that applies a simple histogram equalization function to images to improve image contrast. The example uses parfor to process each of the standard three RGB image planes on separate threads. The example also shows how to generate and run a MEX function in MATLAB prior to generating C code to verify that the MATLAB code is suitable for code generation.
% MATLAB Coder uses the OpenMP portable shared memory parallel programming standard to implement its support for parfor. See The OpenMP API Specification for Parallel Programming. Whereas MATLAB supports parfor by creating multiple worker sessions, MATLAB Coder uses OpenMP to create multiple threads running on the same machine.
%% Prerequisites
% In order to support parallelization, the compiler must support the OpenMP shared memory parallel programming standard. If your compiler does not have this support, then you can still run this example, but the generated code will run serially.
%% About the histequalize Function
% The histequalize.m function takes an image (represented as an NxMx3 matrix) and returns an image with enhanced contrast.

type histequalize

%
%% Generate the MEX Function
% Generate a MEX function using the codegen command.

codegen histequalize

% Before generating C code, you should first test the MEX function in MATLAB to ensure that it is functionally equivalent to the original MATLAB code and that no run-time errors occur. By default, codegen generates a MEX function named histequalize_mex in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.
%
%% Read in the Original Image
% Use the standard imread command to read the low-contrast image.

lcIm = imread('LowContrast.jpg');
image(lcIm);

%
%% Run the MEX Function (The Histogram Equalization Algorithm)
% Pass the low-contrast image.

hcIm = histequalize_mex(lcIm);

%
%% Display the Result

image(hcIm);

%
%% Generate Standalone C Code

codegen -config:lib histequalize

% Using codegen with the -config:lib option produces a standalone C library. By default, the code generated for the library is in the folder codegen/lib/histequalize/.
%
%% Inspect the Generated Function
% Notice that the generated code contains OpenMP pragmas that control parallelization of the code using multiple threads.

type codegen/lib/histequalize/histequalize.c

% Copyright 2018 The MathWorks, Inc.