Monday, May 6, 2024
HomeMatlabLinking to a Dynamic Library from MATLAB Coder for a Home windows...

Linking to a Dynamic Library from MATLAB Coder for a Home windows Pc Imaginative and prescient Software » Man on Simulink


In a earlier publish, I demonstrated the fundamentals of producing C/C++ code from a MATLAB operate and learn how to use that code to create a dynamic library (DLL) that may very well be utilized in an exterior software. As we speak, I would wish to construct upon that publish and apply it to a extra advanced instance. As an instance now we have developed some code in MATLAB® utilizing options from the Pc Imaginative and prescient Toolbox to carry out some picture evaluation, and wish to harness that energy in an exterior C++ software. On this doc, we’ll reveal this workflow by making a DLL from some MATLAB routines and calling them from an exterior C++ code.

MATLAB Picture Processing Code

On this instance, our code is performing characteristic detection on circuit boards to seek out factors of curiosity (corners) which can be utilized by the exterior software for some course of. In MATLAB, we have to load the picture, detect some options and extract them. The extracted options can be utilized in our software, so we’ll want entry to the ensuing array factors which point out the characteristic location.

The uncooked MATLAB code to carry out that is:

% Picture file title on the consumer aspect this can be a parameter

% High quality issue — on the consumer aspect this can be a parameter

% Learn the grayscale picture

% Discover nook candidates within the picture

corners = detectHarrisFeatures(I, ‘MinQuality’, qFac);

% Extract the legitimate corers

[~,valid_corners] = extractFeatures(I,corners);

To validate the outcomes on the MATLAB aspect, we’ll overlay the legitimate corners we extracted onto the picture. (Our consumer code will use these corners for different functions.)

J = insertMarker(I, valid_corners, ‘+’);

imshow(J);

In an effort to make our MATLAB code appropriate for era and manufacturing, we’ll put the above code right into a operate. This operate may have argument checking and an interface to go again the nook factors and a validity flag to the consumer routine. Here is the routine appropriate for code era:

operate [X, valid] = cornerFinder(imFileName, qFac)

% Use Harris nook detector on the enter file with a high quality issue given

% by qFac.

% Copyright 2022 The MathWorks(R), Inc.

% Carry out fundamental argument kind checking

arguments(Enter)

imFileName (1,:) char

qFac single

finish

% Allocate sorts for outputs (single, uint32, boolean)

X=zeros(0,2, ‘like’, qFac);

legitimate = false;

% Guarantee high quality issue is in vary.

if qFac < 0 || qFac > 1

fprintf(“Error: High quality issue have to be between 0 and 1.n”);

return;

finish

% Check to see that the given file exists and is readable

fID = fopen(imFileName, “r”);

if fID == -1

fprintf(“Error: File %s not discovered.n”, imFileName);

return;

finish

% Shut file take a look at

fclose(fID);

% Get the picture from the disk

I = imread(imFileName);

% Compute and extract the nook options

corners = detectHarrisFeatures(I, ‘MinQuality’, qFac);

[~,valid_corners] = extractFeatures(I,corners);

% Retailer the nook positions within the output array for the consumer and

% file the variety of factors. Set the legitimate flag to true.

X = valid_corners.Location;

legitimate = true;

finish

Producing Code and Making a Dynamic Library for Our Perform

To generate code for our operate and compile it right into a DLL for the Home windows atmosphere, we create a coder.config object within the workspace. The pc imaginative and prescient calls require the code to be in RowMajor mode, so we set that in our code configuration. Then we outline dummy arguments for the 2 inputs:
  • qFac: a single precision high quality issue
  • imFile: a variable-sized character array for the filename (right here we use coder.typeof to specify this)
Lastly, we generate code with the codegen command. This may create a C code illustration of the MATLAB routine which we’ll later compile right into a dynamic library.

cfg = coder.config(‘dll’);

% Outline enter argument sorts for coder

imFile = coder.typeof(‘a’, [1,2048], [0, 1]);

% Name the coder to generate the dynamic library

codegen -config cfg cornerFinder.m -args {imFile, qFac} -nargout 2 -report

Code era profitable: View report

Trying into cornerFinder.h from the report reveals the consumer interface for the generated library. It has the prototype for the cornerFinder C operate. Be aware that the operate has three enter arguments, the title of the picture file, it is dimensions and the standard issue. There are two outputs, the array of factors and the legitimate flag. The vital a part of the interface code is right here:

extern void cornerFinder(const char imFileName_data[],

const int imFileName_size[2], float qFac,

emxArray_real32_T *X, boolean_T *legitimate);

We’ll use this data later to assemble our consumer code.

Packaging the Library and Its Dependencies

Now that we have generated our library code, we have to do two issues. First we have to present directions on learn how to construct our library on the consumer aspect. To do that we’ll use the codebuild performance to generate CMake artifacts. Second, we’ll accumulate the code and all of the dependent libraries and package deal them for distribution. We’ll use the packNGo performance from MATLAB. This may generate a zipper file with all we want on the consumer aspect.

codebuild(‘./codegen/dll/cornerFinder’, ‘BuildMethod’, ‘CMake’, ‘BuildVariant’, ‘SHARED_LIBRARY’);

packNGo(‘./codegen/dll/cornerFinder’, ‘packType’, ‘hierarchical’, ‘fileName’, ‘myCornerFinderExample’);

This sequence of instructions generates what we’ll must go to our consumer. The codebuild command creates a CMakeLists.txt file which we’ll ultimately use to create a DLL from our code. The packNGo command generates a file referred to as myCornerFinderExample.zip. Inside this file are two different zip recordsdata, mlrFiles.zip and sDirFiles.zip. The primary of those accommodates all of the MATLAB runtime recordsdata and libraries wanted for the pc imaginative and prescient performance, and the second accommodates the generated code. On my machine, I now have this in my Present Folder:

ZipFileContents.png

Utilizing Our Archive to Construct a DLL with CMake

As soon as now we have our archive, we are able to hand it to our good friend who will compile it. They start by unzipping the archive and its subarchives. This produces a listing tree that appears like this:

C:work> dir /B c:workmyCornerFinderExample

mlrFiles

mlrFiles.zip

sDirFiles

sDirFiles.zip

As soon as they’ve this, they will create the DLL from the command line in Home windows utilizing the Ninja instrument from the Visible Studio 2019 instruments:

C:work> cmake -G Ninja -B ./construct -DCMAKE_BUILD_TYPE=Launch -DMATLAB_ROOT=./myCornerFinderExample/mlrFiles/R2022b -S ./myCornerFinderExample/sDirFiles/codegen/dll/cornerFinder

C:work> cmake –build construct

This may create cornerFinder_win64.dll and cornerFinder_win64.lib. These can be within the .buildcodegendllcornerFinder listing.

Create a Easy Consumer Software

Now that our good friend has constructed our dynamic library, they will name it from their C++ program by way of the cornerFinder routine proven within the header above. On the coronary heart of this code, which is named myClientCode.cpp, is the decision to the cornerFinder operate. The traces of curiosity are right here:

/* Name the entry-point ‘cornerFinder’. */

emxInitArray_real32_T(&X, 2);

cornerFinder(imFileName_data, imFileName_size, qFac, X, &legitimate);

// Free the picture array

emxDestroyArray_real32_T(X);

The primary two traces create an array for storage of the corners and run the detector. The final line frees the purpose array.

Now our good friend creates a CMakeLists.txt file for his or her consumer code. It seems like this:

cmake_minimum_required(VERSION 3.12)

undertaking(MyClient)

set(CMAKE_CXX_STANDARD 14)

add_executable(myClient myClientCode.cpp)

target_include_directories(myClient PRIVATE

../myCornerFinderExample/sDirFiles/codegen/dll/cornerFinder

../myCornerFinderExample/mlrFiles/R2022b/extern/embrace )

target_link_directories(myClient PRIVATE ../construct/codegen/dll/cornerFinder

../myCornerFinderExample/mlrFiles/R2022b/extern/lib/win64/microsoft/

../myCornerFinderExample/mlrFiles/R2022b/toolbox/imaginative and prescient/builtins/src/ocvcg/opencv/win64/lib

)

target_link_libraries(myClient PRIVATE cornerFinder_win64.lib)

The consumer software is constructed equally to the DLL in earlier steps. On the command line within the ClientCode listing our good friend executes these instructions:

C:workClientCode> cmake -G Ninja -B construct -DCMAKE_BUILD_TYPE=Launch

C:workClientCode> cmake –build construct

This may generate myClient.exe. As soon as the generated and dependent DLLs are added to the PATH atmosphere variable, the consumer program will be executed to supply:

C:workClientCode> set PATH=C:workbuildcodegendllcornerFinder;%PATH%

C:workClientCode> set PATH=C:workmyCornerFinderExamplemlrFilesR2022bbinwin64;%PATH%

C:workClientCode> .buildmyClient.exe

Discovered some corners!

Variety of factors: 31 by 2

31.19 135.873

247.013 188.08

(Right here, we have eliminated all however the first and final rows of output information for brevity.)

Accessing This Instance

Now It is Your Flip

Inform us how you’ve got been utilizing the packNGo and codebuild instruments.

© 2023 The MathWorks, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments