%% Generate Code for Sobel Edge Detection That Uses Half-Precision Data Type
%
% This example shows how to generate a standalone C++ library from a 
% MATLAB(R) function that performs Sobel edge detection of images by using 
% half-precision floating point numbers. The Sobel edge algorithm accepts an image 
% that is represented as a matrix and returns an image emphasizing the high 
% spatial frequency regions that correspond to its edges. This example also 
% shows how to test the genenrated code by using a MEX function.  

% Copyright 2020 The MathWorks, Inc. 

%% Sobel Edge Detection Algorithm
% In the Sobel edge detection algorithm, a 2-D spatial gradient operation 
% is performed on a grayscale image. This operation emphasizes the high 
% spatial frequency regions that correspond to the edges in the image.

type sobelEdgeDetectionAlg

%%
% The Sobel edge algorithm computes the horizontal gradient |h| and the 
% vertical gradient |v| of the input image by using two orthogonal 
% filter kernels |maskX| and |maskY|. After the filtering operation, the 
% algorithm computes the gradient magnitude and applies a threhold to find 
% the regions of the image that correspond to the edges.

%% Read Images and Pack Data Into RGBA Packed Column Major Order
% Use the <docid:matlab_ref#btnczv9-1 imread> function to read the 
% images. |imread| represents the RGB channels of an images with integers, 
% one for each pixel. The integers range from 0 to 255. Simply casting 
% inputs to half type might result in overflow during convolutions. To  
% avoid this issue, scale the images to values between 0 and 1. 
im = imread('peppers.png');
figure();
image(im);
imPacked = half(im)/255;
thresh = half(100)/255;

%% Generate MEX
% Generate a C++ MEX function for the |sobelEdgeDetectionAlg| function
% by using the <docid:coder_ref#br46oyi-1 codegen> command.
cfg = coder.config('mex');
cfg.TargetLang = 'C++';
cfg.GenerateReport = true;
codegen -config cfg -args {imPacked,thresh} sobelEdgeDetectionAlg

%% Run Generated MEX and Display Detected Edge
% Before generating C++ code, you must first test the MEX function inside 
% MATLAB environment to make sure 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 |sobelEdgeDetectionAlg_mex| in the 
% current folder. This allows you to test the MATLAB code and MEX function 
% and compare the results.
out_disp = sobelEdgeDetectionAlg_mex(imPacked,thresh);
figure();
imagesc(out_disp);

%% Generate Static C++ Library
% Use the |codegen| command to produces a C++ static library. By default, the 
% generated library is located in the folder 
% |codegen/lib/sobelEdgeDetectionAlg/|.
cfg = coder.config('lib');
cfg.TargetLang = 'C++';
cfg.GenerateReport = true;
codegen -config cfg -args {imPacked,thresh} sobelEdgeDetectionAlg; 

%% Inspect the Generated Function

type codegen/lib/sobelEdgeDetectionAlg/sobelEdgeDetectionAlg.cpp

