vendor: OpenCV 5.0.0 snapshot at 755e50675d97db9b7d449d8bd6b09888646f6c6e
This commit is contained in:
@@ -0,0 +1,336 @@
|
||||
# ----------------------------------------------------------------------------
|
||||
# CMake file for Matlab/Octave support
|
||||
#
|
||||
# Matlab code generation and compilation is broken down into two distinct
|
||||
# stages: configure time and build time. The idea is that we want to give
|
||||
# the user reasonable guarantees that once they type 'make', wrapper
|
||||
# generation is unlikely to fail. Therefore we run a series of tests at
|
||||
# configure time to check the working status of the core components.
|
||||
#
|
||||
# Configure Time
|
||||
# During configure time, the script attempts to ascertain whether the
|
||||
# generator and mex compiler are working for a given architecture.
|
||||
# Currently this involves:
|
||||
# 1) Generating a simple CV_EXPORTS_W symbol and checking whether a file
|
||||
# of the symbol name is generated
|
||||
# 2) Compiling a simple mex gateway to check that Bridge.hpp and mex.h
|
||||
# can be found, and that a file with the mexext is produced
|
||||
#
|
||||
# Build Time
|
||||
# If the configure time tests pass, then we assume Matlab wrapper generation
|
||||
# will not fail during build time. We simply glob all of the symbols in
|
||||
# the OpenCV module headers, generate intermediate .cpp files, then compile
|
||||
# them with mex.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Architecture checks
|
||||
# ----------------------------------------------------------------------------
|
||||
# make sure we're on a supported architecture with Matlab and Python (with jinja2) installed
|
||||
if(APPLE_FRAMEWORK OR ANDROID OR NOT MATLAB_FOUND)
|
||||
ocv_module_disable(matlab)
|
||||
elseif(NOT PYTHON_DEFAULT_AVAILABLE)
|
||||
message(WARNING "A required dependency of the matlab module (Python) was not found. Disabling Matlab bindings...")
|
||||
ocv_module_disable(matlab)
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED HAVE_PYTHON_JINJA2)
|
||||
# Bindings generator requires Jinja2 python package
|
||||
execute_process(COMMAND "${PYTHON_DEFAULT_EXECUTABLE}" -c "import jinja2; print(jinja2.__version__)"
|
||||
RESULT_VARIABLE _result
|
||||
OUTPUT_VARIABLE _jinja2_version
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
if(NOT _result EQUAL 0)
|
||||
set(HAVE_PYTHON_JINJA2 0 CACHE INTERNAL "")
|
||||
else()
|
||||
message(STATUS "Python Jinja version: ${_jinja2_version}")
|
||||
set(HAVE_PYTHON_JINJA2 1 CACHE INTERNAL "")
|
||||
endif()
|
||||
endif()
|
||||
if(NOT HAVE_PYTHON_JINJA2)
|
||||
message(WARNING "A required dependency of the matlab module (Python Jinja2 package) was not found (installation command: \"pip install jinja2\"). Disabling Matlab bindings...")
|
||||
ocv_module_disable(matlab)
|
||||
endif()
|
||||
|
||||
|
||||
# PREPEND
|
||||
# Given a list of strings IN and a TOKEN, prepend the token to each string
|
||||
# and append to OUT. This is used for passing command line "-I", "-L" and "-l"
|
||||
# arguments to mex. e.g.
|
||||
# prepend("-I" OUT /path/to/include/dir) --> -I/path/to/include/dir
|
||||
macro(PREPEND TOKEN OUT IN)
|
||||
foreach(VAR ${IN} ${ARGN})
|
||||
list(APPEND ${OUT} "${TOKEN}${VAR}")
|
||||
endforeach()
|
||||
endmacro()
|
||||
|
||||
|
||||
# WARN_MIXED_PRECISION
|
||||
# Formats a warning message if the compiler and Matlab bitness is different
|
||||
macro(WARN_MIXED_PRECISION COMPILER_BITNESS MATLAB_BITNESS)
|
||||
set(MSG "Your compiler is ${COMPILER_BITNESS}-bit")
|
||||
set(MSG "${MSG} but your version of Matlab is ${MATLAB_BITNESS}-bit.")
|
||||
set(MSG "${MSG} To build Matlab bindings, please switch to a ${MATLAB_BITNESS}-bit compiler.")
|
||||
message(WARNING ${MSG})
|
||||
endmacro()
|
||||
|
||||
ocv_assert(DEFINED MATLAB_ARCH)
|
||||
ocv_assert(DEFINED MATLAB_MEX_SCRIPT)
|
||||
ocv_assert(DEFINED MATLAB_MEXEXT)
|
||||
|
||||
# If the user built OpenCV as X-bit, but they have a Y-bit version of Matlab,
|
||||
# attempting to link to OpenCV during binding generation will fail, since
|
||||
# mixed precision pointers are not allowed. Disable the bindings.
|
||||
math(EXPR ARCH "${CMAKE_SIZEOF_VOID_P} * 8")
|
||||
if (${ARCH} EQUAL 32 AND ${MATLAB_ARCH} MATCHES "64")
|
||||
warn_mixed_precision("32" "64")
|
||||
ocv_module_disable(matlab)
|
||||
return()
|
||||
elseif (${ARCH} EQUAL 64 AND NOT ${MATLAB_ARCH} MATCHES "64")
|
||||
warn_mixed_precision("64" "32")
|
||||
ocv_module_disable(matlab)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# If it's MSVC, warn the user that bindings will only be built in Release mode.
|
||||
# Debug mode seems to cause issues...
|
||||
if (MSVC)
|
||||
message(STATUS "Warning: Matlab bindings will only be built in Release configurations")
|
||||
endif()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Configure time components
|
||||
# ----------------------------------------------------------------------------
|
||||
set(the_description "The Matlab/Octave bindings")
|
||||
ocv_add_module(matlab BINDINGS
|
||||
OPTIONAL opencv_core
|
||||
opencv_imgproc opencv_ml
|
||||
opencv_imgcodecs opencv_videoio opencv_highgui
|
||||
opencv_objdetect opencv_flann opencv_features
|
||||
opencv_photo opencv_video opencv_videostab
|
||||
opencv_calib opencv_geometry
|
||||
opencv_stitching opencv_superres
|
||||
opencv_xfeatures2d
|
||||
opencv_optflow
|
||||
opencv_xphoto
|
||||
)
|
||||
|
||||
# get the commit information
|
||||
execute_process(COMMAND git log -1 --pretty=%H OUTPUT_VARIABLE GIT_COMMIT ERROR_QUIET)
|
||||
string(REGEX REPLACE "(\r?\n)+$" "" GIT_COMMIT "${GIT_COMMIT}")
|
||||
|
||||
# set the path to the C++ header and doc parser, and template engine
|
||||
set(HDR_PARSER_PATH ${OpenCV_SOURCE_DIR}/modules/python/src2)
|
||||
|
||||
# set mex compiler options
|
||||
prepend("-I" MEX_INCLUDE_DIRS ${CMAKE_BINARY_DIR})
|
||||
prepend("-I" MEX_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
if (MSVC)
|
||||
prepend("-L" MEX_LIB_DIR ${LIBRARY_OUTPUT_PATH}/${CMAKE_CFG_INTDIR})
|
||||
else()
|
||||
prepend("-L" MEX_LIB_DIR ${LIBRARY_OUTPUT_PATH})
|
||||
endif()
|
||||
set(MEX_OPTS "-largeArrayDims")
|
||||
|
||||
if (BUILD_TESTS)
|
||||
add_subdirectory(test)
|
||||
endif()
|
||||
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
|
||||
|
||||
# intersection of available modules and optional dependencies
|
||||
# 1. populate the command-line include directories (-I/path/to/module/header, ...)
|
||||
# 2. populate the command-line link libraries (-lopencv_core, ...) for Debug and Release
|
||||
set(MATLAB_DEPS ${OPENCV_MODULE_${the_module}_REQ_DEPS} ${OPENCV_MODULE_${the_module}_OPT_DEPS})
|
||||
foreach(opencv_module ${MATLAB_DEPS})
|
||||
if (HAVE_${opencv_module})
|
||||
string(REPLACE "opencv_" "" module ${opencv_module})
|
||||
list(APPEND opencv_modules ${module})
|
||||
list(APPEND ${the_module}_ACTUAL_DEPS ${opencv_module})
|
||||
prepend("-I" MEX_INCLUDE_DIRS "${OPENCV_MODULE_${opencv_module}_LOCATION}/include")
|
||||
prepend("-l" MEX_LIBS ${opencv_module}${OPENCV_DLLVERSION})
|
||||
prepend("-l" MEX_DEBUG_LIBS ${opencv_module}${OPENCV_DLLVERSION}${OPENCV_DEBUG_POSTFIX})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# add extra headers by hand
|
||||
list(APPEND opencv_extra_hdrs "core=${OPENCV_MODULE_opencv_core_LOCATION}/include/opencv2/core/base.hpp")
|
||||
list(APPEND opencv_extra_hdrs "video=${OPENCV_MODULE_opencv_video_LOCATION}/include/opencv2/video/tracking.hpp")
|
||||
list(APPEND opencv_extra_hdrs "optflow=${OPENCV_MODULE_opencv_optflow_LOCATION}/include/opencv2/optflow.hpp")
|
||||
|
||||
|
||||
# pass the OPENCV_CXX_EXTRA_FLAGS through to the mex compiler
|
||||
# remove the visibility modifiers, so the mex gateway is visible
|
||||
# TODO: get mex working without warnings
|
||||
string(REGEX REPLACE "[^\ ]*visibility[^\ ]*" "" MEX_CXXFLAGS "${OPENCV_EXTRA_FLAGS} ${OPENCV_EXTRA_CXX_FLAGS}")
|
||||
|
||||
# Configure checks
|
||||
# Check to see whether the generator and the mex compiler are working.
|
||||
# The checks currently test:
|
||||
# - whether the python generator can be found
|
||||
# - whether the python generator correctly outputs a file for a definition
|
||||
# - whether the mex compiler can find the required headers
|
||||
# - whether the mex compiler can compile a trivial definition
|
||||
if (NOT MEX_WORKS)
|
||||
# attempt to generate a gateway for a function
|
||||
message(STATUS "Trying to generate Matlab code")
|
||||
execute_process(
|
||||
COMMAND ${PYTHON_DEFAULT_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/generator/gen_matlab.py
|
||||
--hdrparser ${HDR_PARSER_PATH}
|
||||
--extra "test=${CMAKE_CURRENT_SOURCE_DIR}/test/test_generator.hpp"
|
||||
--outdir ${CMAKE_BINARY_DIR}/junk
|
||||
ERROR_VARIABLE GEN_ERROR
|
||||
OUTPUT_QUIET
|
||||
)
|
||||
|
||||
if (GEN_ERROR)
|
||||
message(${GEN_ERROR})
|
||||
message(STATUS "Error generating Matlab code. Disabling Matlab bindings...")
|
||||
ocv_module_disable(matlab)
|
||||
return()
|
||||
else()
|
||||
message(STATUS "Trying to generate Matlab code - OK")
|
||||
endif()
|
||||
|
||||
# attempt to compile a gateway using mex
|
||||
message(STATUS "Trying to compile mex file")
|
||||
execute_process(
|
||||
COMMAND ${MATLAB_MEX_SCRIPT} ${MEX_OPTS} "CXXFLAGS=\$CXXFLAGS ${MEX_CXX_FLAGS}"
|
||||
${MEX_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}/test/test_compiler.cpp
|
||||
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/junk
|
||||
ERROR_VARIABLE MEX_ERROR
|
||||
OUTPUT_QUIET
|
||||
)
|
||||
|
||||
if (MEX_ERROR)
|
||||
message(${MEX_ERROR})
|
||||
message(STATUS "Error compiling mex file. Disabling Matlab bindings...")
|
||||
ocv_module_disable(matlab)
|
||||
return()
|
||||
else()
|
||||
message(STATUS "Trying to compile mex file - OK")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# if we make it here, mex works!
|
||||
set(MEX_WORKS True CACHE BOOL ADVANCED)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Build time components
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# proxies
|
||||
# these proxies are used to trigger the add_custom_commands
|
||||
# (which do the real work) only when they're outdated
|
||||
set(GENERATE_PROXY ${CMAKE_CURRENT_BINARY_DIR}/generate.proxy)
|
||||
set(COMPILE_PROXY ${CMAKE_CURRENT_BINARY_DIR}/compile.proxy)
|
||||
# TODO: Remove following line before merging with master
|
||||
file(REMOVE ${GENERATE_PROXY} ${COMPILE_PROXY})
|
||||
|
||||
# generate
|
||||
# call the python executable to generate the Matlab gateways
|
||||
add_custom_command(
|
||||
OUTPUT ${GENERATE_PROXY}
|
||||
COMMAND ${PYTHON_DEFAULT_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/generator/gen_matlab.py
|
||||
--hdrparser ${HDR_PARSER_PATH}
|
||||
--moduleroot ${OpenCV_SOURCE_DIR}/modules ${OPENCV_EXTRA_MODULES_PATH}
|
||||
--modules ${opencv_modules}
|
||||
--extra ${opencv_extra_hdrs}
|
||||
--outdir ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND ${PYTHON_DEFAULT_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/generator/build_info.py
|
||||
--os ${CMAKE_SYSTEM}
|
||||
--arch ${ARCH} ${CMAKE_SYSTEM_PROCESSOR}
|
||||
--compiler ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}
|
||||
--mex_arch ${MATLAB_ARCH}
|
||||
--mex_script ${MATLAB_MEX_SCRIPT}
|
||||
--cxx_flags ${MEX_CXXFLAGS}
|
||||
--opencv_version ${OPENCV_VERSION}
|
||||
--commit ${GIT_COMMIT}
|
||||
--modules ${opencv_modules}
|
||||
--configuration $<CONFIGURATION>
|
||||
--outdir ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND ${PYTHON_DEFAULT_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/generator/cvmex.py
|
||||
--opts="${MEX_OPTS}"
|
||||
--include_dirs="${MEX_INCLUDE_DIRS}"
|
||||
--lib_dir="${MEX_LIB_DIR}"
|
||||
--libs="${MEX_LIBS}"
|
||||
--flags ${MEX_CXXFLAGS}
|
||||
--outdir ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/test/help.m ${CMAKE_CURRENT_BINARY_DIR}/+cv
|
||||
COMMAND ${CMAKE_COMMAND} -E touch ${GENERATE_PROXY}
|
||||
COMMENT "Generating Matlab source files"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/build_info.py"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/cvmex.py"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/filters.py"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/gen_matlab.py"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/parse_tree.py"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/templates/functional.cpp"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/generator/templates/template_function_base.cpp"
|
||||
)
|
||||
|
||||
# compile
|
||||
# call the mex compiler to compile the gateways
|
||||
# because we don't know the source files at configure-time, this
|
||||
# has to be executed in a separate script in cmake's script processing mode
|
||||
add_custom_command(
|
||||
OUTPUT ${COMPILE_PROXY}
|
||||
COMMAND ${CMAKE_COMMAND} -DMATLAB_MEX_SCRIPT=${MATLAB_MEX_SCRIPT}
|
||||
-DMATLAB_MEXEXT=${MATLAB_MEXEXT}
|
||||
-DMEX_OPTS=${MEX_OPTS}
|
||||
-DMEX_CXXFLAGS=${MEX_CXX_FLAGS}
|
||||
-DMEX_INCLUDE_DIRS="${MEX_INCLUDE_DIRS}"
|
||||
-DMEX_LIB_DIR="${MEX_LIB_DIR}"
|
||||
-DCONFIGURATION="$<CONFIGURATION>"
|
||||
-DMEX_LIBS="${MEX_LIBS}"
|
||||
-DMEX_DEBUG_LIBS="${MEX_DEBUG_LIBS}"
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/compile.cmake
|
||||
COMMAND ${CMAKE_COMMAND} -E touch ${COMPILE_PROXY}
|
||||
COMMENT "Compiling Matlab source files. This could take a while..."
|
||||
)
|
||||
|
||||
# targets
|
||||
# opencv_matlab_sources --> opencv_matlab
|
||||
add_custom_target(${the_module}_sources ALL DEPENDS ${GENERATE_PROXY})
|
||||
add_custom_target(${the_module} ALL DEPENDS ${COMPILE_PROXY})
|
||||
add_dependencies(${the_module} ${the_module}_sources ${${the_module}_ACTUAL_DEPS})
|
||||
|
||||
if (ENABLE_SOLUTION_FOLDERS)
|
||||
set_target_properties(${the_module} PROPERTIES FOLDER "modules")
|
||||
endif()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Install time components
|
||||
# ----------------------------------------------------------------------------
|
||||
# NOTE: Trailing slashes on the DIRECTORY paths are important!
|
||||
# TODO: What needs to be done with rpath????
|
||||
|
||||
# install the +cv directory verbatim
|
||||
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION ${OPENCV_INCLUDE_INSTALL_PATH})
|
||||
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/+cv/ DESTINATION matlab/+cv)
|
||||
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cv.m DESTINATION matlab)
|
||||
|
||||
# update the custom mex compiler to point to the install locations
|
||||
string(REPLACE ";" "\\ " MEX_OPTS "${MEX_OPTS}")
|
||||
string(REPLACE ";" "\\ " MEX_LIBS "${MEX_LIBS}")
|
||||
string(REPLACE " " "\\ " MEX_CXXFLAGS ${MEX_CXXFLAGS})
|
||||
string(REPLACE ";" "\\ " MEX_INCLUDE_DIRS "${MEX_INCLUDE_DIRS}")
|
||||
install(CODE
|
||||
"execute_process(
|
||||
COMMAND ${PYTHON_DEFAULT_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/generator/cvmex.py
|
||||
--opts=${MEX_OPTS}
|
||||
--include_dirs=-I${CMAKE_INSTALL_PREFIX}/${OPENCV_INCLUDE_INSTALL_PATH}
|
||||
--lib_dir=-L${CMAKE_INSTALL_PREFIX}/${OPENCV_LIB_INSTALL_PATH}
|
||||
--libs=${MEX_LIBS}
|
||||
--flags=${MEX_CXXFLAGS}
|
||||
--outdir ${CMAKE_INSTALL_PREFIX}/matlab
|
||||
)"
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this
|
||||
// license. If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of the copyright holders may not be used to endorse or promote
|
||||
// products derived from this software without specific prior written
|
||||
// permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is"
|
||||
// and any express or implied warranties, including, but not limited to, the
|
||||
// implied warranties of merchantability and fitness for a particular purpose
|
||||
// are disclaimed. In no event shall the Intel Corporation or contributors be
|
||||
// liable for any direct, indirect, incidental, special, exemplary, or
|
||||
// consequential damages (including, but not limited to, procurement of
|
||||
// substitute goods or services; loss of use, data, or profits; or business
|
||||
// interruption) however caused and on any theory of liability, whether in
|
||||
// contract, strict liability, or tort (including negligence or otherwise)
|
||||
// arising in any way out of the use of this software, even if advised of the
|
||||
// possibility of such damage.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -0,0 +1,397 @@
|
||||
OpenCV Matlab Code Generator
|
||||
============================
|
||||
This module contains a code generator to automatically produce Matlab mex wrappers for other modules within the OpenCV library. Once compiled and added to the Matlab path, this gives users the ability to call OpenCV methods natively from within Matlab.
|
||||
|
||||
|
||||
Build
|
||||
-----
|
||||
The Matlab code generator is fully integrated into the OpenCV build system. If cmake finds a Matlab installation available on the host system while configuring OpenCV, it will attempt to generate Matlab wrappers for all OpenCV modules. If cmake is having trouble finding your Matlab installation, you can explicitly point it to the root by defining the `MATLAB_ROOT_DIR` variable. For example, on a Mac you could type:
|
||||
|
||||
cmake -DMATLAB_ROOT_DIR=/Applications/MATLAB_R2013a.app ..
|
||||
|
||||
If you prefer using the gui version of cmake (cmake-gui), you can use the *Add Entry* option in the GUI to manually add the *path* variable `MATLAB_ROOT_DIR`.
|
||||
|
||||
|
||||
Install
|
||||
-------
|
||||
In order to use the bindings, you will need to add them to the Matlab path. The path to add is:
|
||||
|
||||
1. `${CMAKE_BUILD_DIR}/modules/matlab` if you are working from the build tree, or
|
||||
2. `${CMAKE_INSTALL_PREFIX}/matlab` if you have installed OpenCV
|
||||
|
||||
In Matlab, simply run:
|
||||
|
||||
addpath('/path/to/opencv/matlab/');
|
||||
|
||||
|
||||
Run
|
||||
---
|
||||
Once you've added the bindings directory to the Matlab path, you can start using them straight away! OpenCV calls need to be prefixed with a 'cv' qualifier, to disambiguate them from Matlab methods of the same name. For example, to compute the dft of a matrix, you might do the following:
|
||||
|
||||
```matlab
|
||||
% load an image (Matlab)
|
||||
I = imread('cameraman.tif');
|
||||
|
||||
% compute the DFT (OpenCV)
|
||||
If = cv.dft(I, cv.DFT_COMPLEX_OUTPUT);
|
||||
```
|
||||
|
||||
As you can see, both OpenCV methods and constants can be used with 'cv' qualification. You can also call:
|
||||
|
||||
help cv.dft
|
||||
|
||||
to get help on the purpose and call signature of a particular method, or
|
||||
|
||||
help cv
|
||||
|
||||
to get general help regarding the OpenCV bindings. If you ever run into issues with the bindings
|
||||
|
||||
cv.buildInformation();
|
||||
|
||||
will produce a printout of diagnostic information pertaining to your particular build of OS, OpenCV and Matlab. It is useful to submit this information alongside a bug report to the OpenCV team.
|
||||
|
||||
Writing your own mex files
|
||||
--------------------------
|
||||
The Matlab bindings come with a set of utilities to help you quickly write your own mex files using OpenCV definitions. By doing so, you have all the speed and freedom of C++, with the power of OpenCV's math expressions and optimizations.
|
||||
|
||||
The first thing you need to learn how to do is write a mex-file with Matlab constructs. Following is a brief example:
|
||||
|
||||
```cpp
|
||||
// include useful constructs
|
||||
// this automatically includes opencv core.hpp and mex.h)
|
||||
#include <opencv2/matlab/bridge.hpp>
|
||||
using namespace cv;
|
||||
using namespace matlab;
|
||||
using namespace bridge;
|
||||
|
||||
// define the mex gateway
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// claim the inputs into scoped management
|
||||
MxArrayVector raw(prhs, prhs+nrhs);
|
||||
|
||||
// add an argument parser to automatically handle basic options
|
||||
ArgumentParser parser("my function");
|
||||
parser.addVariant("variant1", 1, 1, "opt");
|
||||
MxArrayVector reordered = parser.parse(raw);
|
||||
|
||||
// if we get here, we know the inputs are valid and reordered. Unpack...
|
||||
BridgeVector inputs(reordered.begin(), reordered.end());
|
||||
Mat required = inputs[0].toMat();
|
||||
string optional = inputs[1].empty() ? "Default string" : inputs[1].toString();
|
||||
|
||||
try {
|
||||
// Do stuff...
|
||||
} catch(Exception& e) {
|
||||
error(e.what());
|
||||
} catch(...) {
|
||||
error("Uncaught exception occurred");
|
||||
}
|
||||
|
||||
// allocate an output
|
||||
Bridge out;
|
||||
out = required;
|
||||
plhs[0] = out.toMxArray().releaseOwnership();
|
||||
}
|
||||
```
|
||||
|
||||
There are a couple of important things going on in this example. Firstly, you need to include `<opencv2/matlab/bridge.hpp>` to enable the bridging capabilities. Once you've done this, you get some nice utilities for free. `MxArray` is a class that wraps Matlab's `mxArray*` class in an OOP-style interface. `ArgumentParser` is a class that handles default, optional and named arguments for you, along with multiple possible calling syntaxes. Finally, `Bridge` is a class that allows bidirectional conversions between OpenCV/std and Matlab types.
|
||||
|
||||
Once you have written your file, it can be compiled with the provided mex utility:
|
||||
|
||||
cv.mex('my_function.cpp');
|
||||
|
||||
This utility automatically links in all of the necessary OpenCV libraries to make your function work.
|
||||
|
||||
NOTE: OpenCV uses exceptions throughout the codebase. It is a **very** good idea to wrap your code in exception handlers to avoid crashing Matlab in the event of an exception being thrown.
|
||||
|
||||
------------------------------------------------------------------
|
||||
|
||||
|
||||
Developer
|
||||
=========
|
||||
The following sections contain information for developers seeking to use, understand or extend the Matlab bindings. The bindings are generated in python using a powerful templating engine called Jinja2. Because Matlab mex gateways have a common structure, they are well suited to templatization. There are separate templates for formatting C++ classes, Matlab classes, C++ functions, constants (enums) and documentation.
|
||||
|
||||
The task of the generator is two-fold:
|
||||
|
||||
1. To parse the OpenCV headers and build a semantic tree that can be fed to the template engine
|
||||
2. To define type conversions between C++/OpenCV and Matlab types
|
||||
|
||||
Once a source file has been generated for each OpenCV definition, and type conversions have been established, the mex compiler is invoked to produce the mex gateway (shared object) and link in the OpenCV libraries.
|
||||
|
||||
|
||||
File layout
|
||||
-----------
|
||||
opencv/modules/matlab (this module)
|
||||
|
||||
* `CMakeLists.txt` (main cmake configuration file)
|
||||
* `README.md` (this file)
|
||||
* `compile.cmake` (the cmake script for compiling generated source code)
|
||||
* `generator` (the folder containing generator code)
|
||||
* `filters.py` (template filters)
|
||||
* `gen_matlab.py` (the binding generator control script)
|
||||
* `parse_tree.py` (python class to refactor the hdr_parser.py output)
|
||||
* `templates` (the raw templates for populating classes, constants, functions and docs)
|
||||
* `include` (C++ headers for the bindings)
|
||||
* `mxarray.hpp` (C++ OOP-style interface for Matlab mxArray* class)
|
||||
* `bridge.hpp` (type conversions)
|
||||
* `map.hpp` (hash map interface for instance storage and method lookup)
|
||||
* `test` (generator, compiler and binding test scripts)
|
||||
|
||||
|
||||
Call Tree
|
||||
---------
|
||||
The cmake call tree can be broken into 3 main components:
|
||||
|
||||
1. configure time
|
||||
2. build time
|
||||
3. install time
|
||||
|
||||
**Find Matlab (configure)**
|
||||
The first thing to do is discover a Matlab installation on the host system. This is handled by the `OpenCVFindMatlab.cmake` in `opencv/cmake`. On Windows machines it searches the registry and path, while on *NIX machines it searches a set of canonical install paths. Once Matlab has been found, a number of variables are defined, such as the path to the mex compiler, the mex libraries, the mex include paths, the architectural extension, etc.
|
||||
|
||||
**Test the generator (configure)**
|
||||
Attempt to produce a source file for a simple definition. This tests whether python and pythonlibs are correctly invoked on the host.
|
||||
|
||||
**Test the mex compiler (configure)**
|
||||
Attempt to compile a simple definition using the mex compiler. A mex file is actually just a shared object with a special exported symbol `_mexFunction` which serves as the entry-point to the function. As such, the mex compiler is just a set of scripts configuring the system compiler. In most cases this is the same as the OpenCV compiler, but *could* be different. The test checks whether the mex and generator includes can be found, the system libraries can be linked and the passed compiler flags are compatible.
|
||||
|
||||
If any of the configure time tests fail, the bindings will be disabled, but the main OpenCV configure will continue without error. The configuration summary will contain the block:
|
||||
|
||||
Matlab
|
||||
mex: /Applications/MATLAB_R2013a.app/bin/mex
|
||||
compiler/generator: Not working (bindings will not be generated)
|
||||
|
||||
**Generate the sources (build)**
|
||||
Given a set of modules (the intersection of the OpenCV modules being built and the matlab module optional dependencies), the `CppHeaderParser()` from `opencv/modules/python/src2/hdr_parser.py` will parse the module headers and produce a set of definitions.
|
||||
|
||||
The `ParseTree()` from `opencv/modules/matlab/generator/parse_tree.py` takes this set of definitions and refactors them into a semantic tree better suited to templatization. For example, a trivial definition from the header parser may look something like:
|
||||
|
||||
```python
|
||||
[fill, void, ['/S'], [cv::Mat&, mat, '', ['/I', '/O']]]
|
||||
```
|
||||
|
||||
The equivalent refactored output will look like:
|
||||
|
||||
```python
|
||||
Function
|
||||
name = 'fill'
|
||||
rtype = 'void'
|
||||
static = True
|
||||
req =
|
||||
Argument
|
||||
name = 'mat'
|
||||
type = 'cv::Mat'
|
||||
ref = '&'
|
||||
I = True
|
||||
O = True
|
||||
default = ''
|
||||
```
|
||||
|
||||
The added semantics (Namespace, Class, Function, Argument, name, etc) make it easier for the templating engine to parse, slice and populate definitions.
|
||||
|
||||
Once the definitions have been parsed, `gen_matlab.py` passes each definition to the template engine with the appropriate template (class, function, enum, doc) and the filled template gets written to the `${CMAKE_CURRENT_BUILD_DIR}/src` directory.
|
||||
|
||||
The generator relies upon a proxy object called `generate.proxy` to determine when the sources are out of date and need to be re-generated.
|
||||
|
||||
**Compile the sources (build)**
|
||||
Once the sources have been generated, they are compiled by the mex compiler. The `compile.cmake` script in `opencv/modules/matlab/` takes responsibility for iterating over each source file in `${CMAKE_CURRENT_BUILD_DIR}/src` and compiling it with the passed includes and OpenCV libraries.
|
||||
|
||||
The flags used to compile the main OpenCV libraries are also forwarded to the mex compiler. So if, for example, you compiled OpenCV with SSE support, the mex bindings will also use SSE. Likewise, if you compile OpenCV in debug mode, the bindings will link to the debug version of the libraries.
|
||||
|
||||
Importantly, the mex compiler includes the `mxarray.hpp`, `bridge.hpp` and `map.hpp` files from the `opencv/modules/matlab/include` directory. `mxarray.hpp` defines a `MxArray` class which wraps Matlab's `mxArray*` type in a more friendly OOP-syle interface. `bridge.hpp` defines a `Bridge` class which is able to perform type conversions between Matlab types and std/OpenCV types. It can be extended with new definitions using the plugin interface described in that file.
|
||||
|
||||
The compiler relies upon a proxy object called `compile.proxy` to determine when the generated sources are out of date and need to be re-compiled.
|
||||
|
||||
**Install the files (install)**
|
||||
At install time, the mex files are put into place at `${CMAKE_INSTALL_PREFIX}/matlab` and their linkages updated.
|
||||
|
||||
|
||||
Jinja2
|
||||
------
|
||||
Jinja2 is a powerful templating engine, similar to python's builtin `string.Template` class but implementing the model-view-controller paradigm. For example, a trivial view could be populated as follows:
|
||||
|
||||
**view.py**
|
||||
|
||||
```html+django
|
||||
<title>{{ title }}</title>
|
||||
<ul>
|
||||
{% for user in users %}
|
||||
<li><a href="{{ user.url }}">{{ user.username | sanitize }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
```
|
||||
|
||||
**model.py**
|
||||
|
||||
```python
|
||||
class User(object):
|
||||
__init__(self):
|
||||
self.username = ''
|
||||
self.url = ''
|
||||
|
||||
def sanitize(text):
|
||||
"""Filter for escaping html tags to prevent code injection"""
|
||||
```
|
||||
|
||||
**controller.py**
|
||||
|
||||
```python
|
||||
def populate(users):
|
||||
# initialize jinja
|
||||
jtemplate = jinja2.Environment(loader=FileSystemLoader())
|
||||
|
||||
# add the filters to the engine
|
||||
jtemplate['sanitize'] = sanitize
|
||||
|
||||
# get the view
|
||||
template = jtemplate.get_template('view')
|
||||
|
||||
# populate the template with a list of User objects
|
||||
populated = template.render(title='all users', users=users)
|
||||
|
||||
# write to file
|
||||
with open('users.html', 'wb') as f:
|
||||
f.write(populated)
|
||||
```
|
||||
|
||||
Thus the style and layout of the view is kept separate from the content (model). This modularity improves readability and maintainability of both the view and content and (for my own sanity) has helped significantly in debugging errors.
|
||||
|
||||
File Reference
|
||||
--------------
|
||||
**gen_matlab.py**
|
||||
gen_matlab has the following call signature:
|
||||
|
||||
gen_matlab.py --jinja2 path/to/jinja2/engine
|
||||
--hdrparser path/to/hdr_parser/dir
|
||||
--rstparser path/to/rst_parser/dir
|
||||
--moduleroot path/to/opencv/modules
|
||||
--modules [core imgproc highgui ...]
|
||||
--extra namespace=/additional/header/to/parse
|
||||
--outdir /path/to/place/generated/src
|
||||
|
||||
**build_info.py**
|
||||
build_info has the following call signature:
|
||||
|
||||
build_info.py --jinja2 path/to/jinja2/engine
|
||||
--os operating_system_string
|
||||
--arch [bitness processor]
|
||||
--compiler [id version]
|
||||
--mex_arch arch_string
|
||||
--mex_script /path/to/mex/script
|
||||
--cxx_flags [-list -of -flags -to -passthrough]
|
||||
--opencv_version version_string
|
||||
--commit commit_hash_if_using_git
|
||||
--modules core imgproc highgui etc
|
||||
--configuration Debug/Release
|
||||
--outdir path/to/place/build/info
|
||||
|
||||
**cvmex.py**
|
||||
cvmex.py, the custom compiler generator, has the following call signature:
|
||||
|
||||
cvmex.py --jinja2 path/to/jinja2/engine
|
||||
--opts [-list -of -opts]
|
||||
--include_dirs [-list -of -opencv_include_directories]
|
||||
--lib_dir opencv_lib_directory
|
||||
--libs [-lopencv_core -lopencv_imgproc ...]
|
||||
--flags [-Wall -opencv_build_flags ...]
|
||||
--outdir /path/to/generated/output
|
||||
|
||||
**parse_tree.py**
|
||||
To build a parse tree, first parse a set of headers, then invoke the parse tree to refactor the output:
|
||||
|
||||
```python
|
||||
# parse a set of definitions into a dictionary of namespaces
|
||||
parser = CppHeaderParser()
|
||||
ns['core'] = parser.parse('path/to/opencv/core.hpp')
|
||||
|
||||
# refactor into a semantic tree
|
||||
parse_tree = ParseTree()
|
||||
parse_tree.build(ns)
|
||||
|
||||
# iterate over the tree
|
||||
for namespace in parse_tree.namespaces:
|
||||
for clss in namespace.classes:
|
||||
# do stuff
|
||||
for method in namespace.methods:
|
||||
# do stuff
|
||||
```
|
||||
|
||||
**mxarray.hpp**
|
||||
mxarray.hpp defines a class called `MxArray` which provides an OOP-style interface for Matlab's homogeneous `mxArray*` type. To create an `MxArray`, you can either inherit an existing array
|
||||
|
||||
```cpp
|
||||
MxArray mat(prhs[0]);
|
||||
```
|
||||
|
||||
or create a new array
|
||||
|
||||
```cpp
|
||||
MxArray mat(5, 5, Matlab::Traits<double>::ScalarType);
|
||||
MxArray mat = MxArray::Matrix<double>(5, 5);
|
||||
```
|
||||
|
||||
The default constructor allocates a `0 x 0` array. Once you have encapculated an `mxArray*` you can access its properties through member functions:
|
||||
|
||||
```cpp
|
||||
mat.rows();
|
||||
mat.cols();
|
||||
mat.size();
|
||||
mat.channels();
|
||||
mat.isComplex();
|
||||
mat.isNumeric();
|
||||
mat.isLogical();
|
||||
mat.isClass();
|
||||
mat.className();
|
||||
mat.real();
|
||||
mat.imag();
|
||||
```
|
||||
|
||||
The MxArray object uses scoped memory management. If you wish to pass an MxArray back to Matlab (as a lhs pointer), you need to explicitly release ownership of the array so that it is not destroyed when it leaves scope:
|
||||
|
||||
```cpp
|
||||
plhs[0] = mat.releaseOwnership();
|
||||
```
|
||||
|
||||
mxarray.hpp also includes a number of helper utilities that make working in mex-world a little easier. One such utility is the `ArgumentParser`. `ArgumentParser` automatically handles required and optional arguments to a method, and even enables named arguments as used in many core Matlab functions. For example, if you had a function with the following signature:
|
||||
|
||||
```cpp
|
||||
void f(Mat first, Mat second, Mat mask=Mat(), int dtype=-1);
|
||||
```
|
||||
|
||||
then you can create an `ArgumentParser` as follows:
|
||||
|
||||
```cpp
|
||||
ArgumentParser parser("f");
|
||||
parser.addVariant("f", 2, 2, "mask", "dtype");
|
||||
MxArrayVector inputs = parser.parse(prhs, prhs+nrhs);
|
||||
```
|
||||
|
||||
and that will make available the following calling syntaxes:
|
||||
|
||||
```matlab
|
||||
f(first, second);
|
||||
f(first, second, mask);
|
||||
f(first, second, mask, dtype);
|
||||
f(first, second, 'dtype', dtype, 'mask', mask); % optional ordering does not matter
|
||||
f(first, second, 'dtype', dtype); % only second optional argument provided
|
||||
f(first, second, mask, 'dtype', dtype); % mixture of ordered and named
|
||||
```
|
||||
|
||||
Further, the output of the `parser.parse()` method will always contain the total number of required and optional arguments that the method can take, with unspecified arguments given by empty matrices. Thus, to check if an optional argument has been given, you can do:
|
||||
|
||||
```cpp
|
||||
int dtype = inputs[3].empty() ? -1 : inputs[3].scalar<double>();
|
||||
```
|
||||
|
||||
**bridge.hpp**
|
||||
The bridge interface defines a `Bridge` class which provides type conversion between std/OpenCV and Matlab types. A type conversion must provide the following:
|
||||
|
||||
```cpp
|
||||
Bridge& operator=(const MyObject&);
|
||||
MyObject toMyObject();
|
||||
operator MyObject();
|
||||
```
|
||||
|
||||
The binding generator will then automatically call the conversion operators (either explicitly or implicitly) if your `MyObject` class is encountered as an input or return from a parsed definition.
|
||||
@@ -0,0 +1,197 @@
|
||||
# ----- Find Matlab/Octave -----
|
||||
#
|
||||
# OpenCVFindMatlab.cmake attempts to locate the install path of Matlab in order
|
||||
# to extract the mex headers, libraries and shell scripts. If found
|
||||
# successfully, the following variables will be defined
|
||||
#
|
||||
# MATLAB_FOUND: true/false
|
||||
# MATLAB_ROOT_DIR: Root of Matlab installation
|
||||
# MATLAB_BIN: The main Matlab "executable" (shell script)
|
||||
# MATLAB_MEX_SCRIPT: The mex script used to compile mex files
|
||||
# MATLAB_INCLUDE_DIRS:Path to "mex.h"
|
||||
# MATLAB_LIBRARY_DIRS:Path to mex and matrix libraries
|
||||
# MATLAB_LIBRARIES: The Matlab libs, usually mx, mex, mat
|
||||
# MATLAB_MEXEXT: The mex library extension. It will be one of:
|
||||
# mexwin32, mexwin64, mexglx, mexa64, mexmac,
|
||||
# mexmaci, mexmaci64, mexsol, mexs64
|
||||
# MATLAB_ARCH: The installation architecture. It is **usually**
|
||||
# the MEXEXT with the preceding "mex" removed,
|
||||
# though it's different for linux distros.
|
||||
#
|
||||
# There doesn't appear to be an elegant way to detect all versions of Matlab
|
||||
# across different platforms. If you know the matlab path and want to avoid
|
||||
# the search, you can define the path to the Matlab root when invoking cmake:
|
||||
#
|
||||
# cmake -DMATLAB_ROOT_DIR='/PATH/TO/ROOT_DIR' ..
|
||||
|
||||
# ----- set_library_presuffix -----
|
||||
#
|
||||
# Matlab tends to use some non-standard prefixes and suffixes on its libraries.
|
||||
# For example, libmx.dll on Windows (Windows does not add prefixes) and
|
||||
# mkl.dylib on OS X (OS X uses "lib" prefixes).
|
||||
# On some versions of Windows the .dll suffix also appears to not be checked.
|
||||
#
|
||||
# This function modifies the library prefixes and suffixes used by
|
||||
# find_library when finding Matlab libraries. It does not affect scopes
|
||||
# outside of this file.
|
||||
function(set_libarch_prefix_suffix)
|
||||
if (UNIX AND NOT APPLE)
|
||||
set(CMAKE_FIND_LIBRARY_PREFIXES "lib" PARENT_SCOPE)
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES ".so" ".a" PARENT_SCOPE)
|
||||
elseif (APPLE)
|
||||
set(CMAKE_FIND_LIBRARY_PREFIXES "lib" PARENT_SCOPE)
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES ".dylib" ".a" PARENT_SCOPE)
|
||||
elseif (WIN32)
|
||||
set(CMAKE_FIND_LIBRARY_PREFIXES "lib" PARENT_SCOPE)
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib" ".dll" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
|
||||
|
||||
# ----- locate_matlab_root -----
|
||||
#
|
||||
# Attempt to find the path to the Matlab installation. If successful, sets
|
||||
# the absolute path in the variable MATLAB_ROOT_DIR
|
||||
function(locate_matlab_root)
|
||||
|
||||
# --- UNIX/APPLE ---
|
||||
if (UNIX)
|
||||
# possible root locations, in order of likelihood
|
||||
set(SEARCH_DIRS_ /Applications /usr/local /opt/local /usr /opt)
|
||||
foreach (DIR_ ${SEARCH_DIRS_})
|
||||
file(GLOB MATLAB_ROOT_DIR_ ${DIR_}/MATLAB/R* ${DIR_}/MATLAB_R*)
|
||||
if (MATLAB_ROOT_DIR_)
|
||||
# sort in order from highest to lowest
|
||||
# normally it's in the format MATLAB_R[20XX][A/B]
|
||||
# TODO: numerical rather than lexicographic sort. However,
|
||||
# CMake does not support floating-point MATH(EXPR ...) at this time.
|
||||
list(SORT MATLAB_ROOT_DIR_)
|
||||
list(REVERSE MATLAB_ROOT_DIR_)
|
||||
list(GET MATLAB_ROOT_DIR_ 0 MATLAB_ROOT_DIR_)
|
||||
set(MATLAB_ROOT_DIR ${MATLAB_ROOT_DIR_} PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# --- WINDOWS ---
|
||||
elseif (WIN32)
|
||||
# 1. search the path environment variable
|
||||
find_program(MATLAB_ROOT_DIR_ matlab PATHS ENV PATH)
|
||||
if (MATLAB_ROOT_DIR_)
|
||||
# get the root directory from the full path
|
||||
# /path/to/matlab/rootdir/bin/matlab.exe
|
||||
get_filename_component(MATLAB_ROOT_DIR_ ${MATLAB_ROOT_DIR_} PATH)
|
||||
get_filename_component(MATLAB_ROOT_DIR_ ${MATLAB_ROOT_DIR_} PATH)
|
||||
set(MATLAB_ROOT_DIR ${MATLAB_ROOT_DIR_} PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# 2. search the registry
|
||||
# determine the available Matlab versions
|
||||
set(REG_EXTENSION_ "SOFTWARE\\Mathworks\\MATLAB")
|
||||
set(REG_ROOTS_ "HKEY_LOCAL_MACHINE" "HKEY_CURRENT_USER")
|
||||
foreach(REG_ROOT_ ${REG_ROOTS_})
|
||||
execute_process(COMMAND reg query "${REG_ROOT_}\\${REG_EXTENSION_}" OUTPUT_VARIABLE QUERY_RESPONSE_ ERROR_VARIABLE UNUSED_)
|
||||
if (QUERY_RESPONSE_)
|
||||
string(REGEX MATCHALL "[0-9]\\.[0-9]" VERSION_STRINGS_ ${QUERY_RESPONSE_})
|
||||
list(APPEND VERSIONS_ ${VERSION_STRINGS_})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# select the highest version
|
||||
list(APPEND VERSIONS_ "0.0")
|
||||
list(SORT VERSIONS_)
|
||||
list(REVERSE VERSIONS_)
|
||||
list(GET VERSIONS_ 0 VERSION_)
|
||||
|
||||
# request the MATLABROOT from the registry
|
||||
foreach(REG_ROOT_ ${REG_ROOTS_})
|
||||
get_filename_component(QUERY_RESPONSE_ [${REG_ROOT_}\\${REG_EXTENSION_}\\${VERSION_};MATLABROOT] ABSOLUTE)
|
||||
if (NOT ${QUERY_RESPONSE_} MATCHES "registry$")
|
||||
set(MATLAB_ROOT_DIR ${QUERY_RESPONSE_} PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
|
||||
|
||||
# ----- locate_matlab_components -----
|
||||
#
|
||||
# Given a directory MATLAB_ROOT_DIR, attempt to find the Matlab components
|
||||
# (include directory and libraries) under the root. If everything is found,
|
||||
# sets the variable MATLAB_FOUND to TRUE
|
||||
function(locate_matlab_components MATLAB_ROOT_DIR)
|
||||
# get the mex extension
|
||||
find_file(MATLAB_MEXEXT_SCRIPT_ NAMES mexext mexext.bat PATHS ${MATLAB_ROOT_DIR}/bin NO_DEFAULT_PATH)
|
||||
execute_process(COMMAND ${MATLAB_MEXEXT_SCRIPT_}
|
||||
OUTPUT_VARIABLE MATLAB_MEXEXT_
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
if (NOT MATLAB_MEXEXT_)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# map the mexext to an architecture extension
|
||||
set(ARCHITECTURES_ "maci64" "maci" "glnxa64" "glnx64" "sol64" "sola64" "win32" "win64" )
|
||||
foreach(ARCHITECTURE_ ${ARCHITECTURES_})
|
||||
if(EXISTS ${MATLAB_ROOT_DIR}/bin/${ARCHITECTURE_})
|
||||
set(MATLAB_ARCH_ ${ARCHITECTURE_})
|
||||
break()
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# get the path to the libraries
|
||||
set(MATLAB_LIBRARY_DIRS_ ${MATLAB_ROOT_DIR}/bin/${MATLAB_ARCH_})
|
||||
|
||||
# get the libraries
|
||||
set_libarch_prefix_suffix()
|
||||
find_library(MATLAB_LIB_MX_ mx PATHS ${MATLAB_LIBRARY_DIRS_} NO_DEFAULT_PATH)
|
||||
find_library(MATLAB_LIB_MEX_ mex PATHS ${MATLAB_LIBRARY_DIRS_} NO_DEFAULT_PATH)
|
||||
find_library(MATLAB_LIB_MAT_ mat PATHS ${MATLAB_LIBRARY_DIRS_} NO_DEFAULT_PATH)
|
||||
set(MATLAB_LIBRARIES_ ${MATLAB_LIB_MX_} ${MATLAB_LIB_MEX_} ${MATLAB_LIB_MAT_})
|
||||
|
||||
# get the include path
|
||||
find_path(MATLAB_INCLUDE_DIRS_ mex.h ${MATLAB_ROOT_DIR}/extern/include)
|
||||
|
||||
# get the mex shell script
|
||||
find_program(MATLAB_MEX_SCRIPT_ NAMES mex mex.bat PATHS ${MATLAB_ROOT_DIR}/bin NO_DEFAULT_PATH)
|
||||
|
||||
# get the Matlab executable
|
||||
find_program(MATLAB_BIN_ NAMES matlab PATHS ${MATLAB_ROOT_DIR}/bin NO_DEFAULT_PATH)
|
||||
|
||||
# export into parent scope
|
||||
if (MATLAB_MEX_SCRIPT_ AND MATLAB_LIBRARIES_ AND MATLAB_INCLUDE_DIRS_)
|
||||
set(MATLAB_BIN ${MATLAB_BIN_} PARENT_SCOPE)
|
||||
set(MATLAB_MEX_SCRIPT ${MATLAB_MEX_SCRIPT_} PARENT_SCOPE)
|
||||
set(MATLAB_INCLUDE_DIRS ${MATLAB_INCLUDE_DIRS_} PARENT_SCOPE)
|
||||
set(MATLAB_LIBRARIES ${MATLAB_LIBRARIES_} PARENT_SCOPE)
|
||||
set(MATLAB_LIBRARY_DIRS ${MATLAB_LIBRARY_DIRS_} PARENT_SCOPE)
|
||||
set(MATLAB_MEXEXT ${MATLAB_MEXEXT_} PARENT_SCOPE)
|
||||
set(MATLAB_ARCH ${MATLAB_ARCH_} PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# FIND MATLAB COMPONENTS
|
||||
# ----------------------------------------------------------------------------
|
||||
if (NOT MATLAB_FOUND)
|
||||
|
||||
# attempt to find the Matlab root folder
|
||||
if (NOT MATLAB_ROOT_DIR)
|
||||
locate_matlab_root()
|
||||
endif()
|
||||
|
||||
# given the matlab root folder, find the library locations
|
||||
if (MATLAB_ROOT_DIR)
|
||||
locate_matlab_components(${MATLAB_ROOT_DIR})
|
||||
endif()
|
||||
find_package_handle_standard_args(Matlab DEFAULT_MSG
|
||||
MATLAB_MEX_SCRIPT MATLAB_INCLUDE_DIRS
|
||||
MATLAB_ROOT_DIR MATLAB_LIBRARIES
|
||||
MATLAB_LIBRARY_DIRS MATLAB_MEXEXT
|
||||
MATLAB_ARCH MATLAB_BIN)
|
||||
endif()
|
||||
@@ -0,0 +1,9 @@
|
||||
# ========================= matlab =========================
|
||||
if(WITH_MATLAB OR MATLAB_FOUND)
|
||||
status("")
|
||||
status(" Matlab:" MATLAB_FOUND THEN "YES" ELSE "NO")
|
||||
if(MATLAB_FOUND)
|
||||
status(" mex:" MATLAB_MEX_SCRIPT THEN "${MATLAB_MEX_SCRIPT}" ELSE NO)
|
||||
status(" Compiler/generator:" MEX_WORKS THEN "Working" ELSE "Not working (bindings will not be generated)")
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,20 @@
|
||||
OCV_OPTION(WITH_MATLAB "Include Matlab support (opencv_contrib)" OFF IF (NOT ANDROID AND NOT IOS AND NOT WINRT))
|
||||
|
||||
ocv_assert(OPENCV_INITIAL_PASS)
|
||||
|
||||
if(WITH_MATLAB OR DEFINED MATLAB_FOUND)
|
||||
ocv_cmake_hook_append(STATUS_DUMP_EXTRA "${CMAKE_CURRENT_LIST_DIR}/hooks/STATUS_DUMP_EXTRA.cmake")
|
||||
endif()
|
||||
|
||||
# --- Matlab/Octave ---
|
||||
if(WITH_MATLAB AND NOT DEFINED MATLAB_FOUND)
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/OpenCVFindMatlab.cmake)
|
||||
if(NOT MATLAB_FOUND)
|
||||
message(WARNING "Matlab or compiler (mex) was not found. Disabling Matlab bindings...")
|
||||
ocv_module_disable(matlab)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT OPENCV_DOCS_INCLUDE_MATLAB)
|
||||
list(APPEND DOXYGEN_BLACKLIST "matlab")
|
||||
endif()
|
||||
@@ -0,0 +1,56 @@
|
||||
# LISTIFY
|
||||
# Given a string of space-delimited tokens, reparse as a string of
|
||||
# semi-colon delimited tokens, which in CMake land is exactly equivalent
|
||||
# to a list
|
||||
macro(listify OUT_LIST IN_STRING)
|
||||
string(REPLACE " " ";" ${OUT_LIST} ${IN_STRING})
|
||||
endmacro()
|
||||
|
||||
# listify multiple-argument inputs
|
||||
listify(MEX_INCLUDE_DIRS_LIST ${MEX_INCLUDE_DIRS})
|
||||
if (${CONFIGURATION} MATCHES "Debug")
|
||||
listify(MEX_LIBS_LIST ${MEX_DEBUG_LIBS})
|
||||
else()
|
||||
listify(MEX_LIBS_LIST ${MEX_LIBS})
|
||||
endif()
|
||||
|
||||
# if it's MSVC building a Debug configuration, don't build bindings
|
||||
if ("${CONFIGURATION}" MATCHES "Debug")
|
||||
message(STATUS "Matlab bindings are only available in Release configurations. Skipping...")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Compile
|
||||
# -----------------------------------------------------------------------------
|
||||
# for each generated source file:
|
||||
# 1. check if the file has already been compiled
|
||||
# 2. attempt compile if required
|
||||
# 3. if the compile fails, throw an error and cancel compilation
|
||||
file(GLOB SOURCE_FILES "${CMAKE_CURRENT_BINARY_DIR}/src/*.cpp")
|
||||
list(LENGTH SOURCE_FILES __size)
|
||||
message("Matlab: compiling ${__size} files")
|
||||
set(__index 0)
|
||||
foreach(SOURCE_FILE ${SOURCE_FILES})
|
||||
MATH(EXPR __index "${__index}+1")
|
||||
# strip out the filename
|
||||
get_filename_component(FILENAME ${SOURCE_FILE} NAME_WE)
|
||||
message("[${__index}/${__size}] Compiling: ${FILENAME}")
|
||||
# compile the source file using mex
|
||||
if (NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/+cv/${FILENAME}.${MATLAB_MEXEXT}" OR
|
||||
"${SOURCE_FILE}" IS_NEWER_THAN "${CMAKE_CURRENT_BINARY_DIR}/+cv/${FILENAME}.${MATLAB_MEXEXT}"
|
||||
)
|
||||
execute_process(
|
||||
COMMAND ${MATLAB_MEX_SCRIPT} ${MEX_OPTS} "CXXFLAGS=\$CXXFLAGS ${MEX_CXXFLAGS}" ${MEX_INCLUDE_DIRS_LIST}
|
||||
${MEX_LIB_DIR} ${MEX_LIBS_LIST} ${SOURCE_FILE}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/+cv
|
||||
OUTPUT_QUIET
|
||||
ERROR_VARIABLE FAILED
|
||||
)
|
||||
endif()
|
||||
# TODO: If a mex file fails to compile, should we error out?
|
||||
# TODO: Warnings are currently treated as errors...
|
||||
if (FAILED)
|
||||
message(FATAL_ERROR "Failed to compile ${FILENAME}: ${FAILED}")
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
def substitute(build, output_dir):
|
||||
|
||||
# setup the template engine
|
||||
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
|
||||
jtemplate = Environment(loader=FileSystemLoader(template_dir), trim_blocks=True, lstrip_blocks=True)
|
||||
|
||||
# add the filters
|
||||
jtemplate.filters['csv'] = csv
|
||||
jtemplate.filters['stripExtraSpaces'] = stripExtraSpaces
|
||||
|
||||
# load the template
|
||||
template = jtemplate.get_template('template_build_info.m')
|
||||
|
||||
# create the build directory
|
||||
output_dir = output_dir+'/+cv'
|
||||
if not os.path.isdir(output_dir):
|
||||
os.mkdir(output_dir)
|
||||
|
||||
# populate template
|
||||
populated = template.render(build=build, time=time)
|
||||
with open(os.path.join(output_dir, 'buildInformation.m'), 'wb') as f:
|
||||
f.write(populated.encode('utf-8'))
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""
|
||||
Usage: python build_info.py
|
||||
--os os_version_string
|
||||
--arch [bitness processor]
|
||||
--compiler [id version]
|
||||
--mex_arch arch_string
|
||||
--mex_script /path/to/mex/script
|
||||
--cxx_flags [-list -of -flags -to -passthrough]
|
||||
--opencv_version version_string
|
||||
--commit commit_hash_if_using_git
|
||||
--modules [core imgproc highgui etc]
|
||||
--configuration Debug/Release
|
||||
--outdir /path/to/write/build/info
|
||||
|
||||
build_info.py generates a Matlab function that can be invoked with a call to
|
||||
>> cv.buildInformation();
|
||||
|
||||
This function prints a summary of the user's OS, OpenCV and Matlab build
|
||||
given the information passed to this module. build_info.py invokes Jinja2
|
||||
on the template_build_info.m template.
|
||||
"""
|
||||
|
||||
# parse the input options
|
||||
import sys, re, os, time
|
||||
from argparse import ArgumentParser
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('--os')
|
||||
parser.add_argument('--arch', nargs=2)
|
||||
parser.add_argument('--compiler', nargs='+')
|
||||
parser.add_argument('--mex_arch')
|
||||
parser.add_argument('--mex_script')
|
||||
parser.add_argument('--mex_opts', default=['-largeArrayDims'], nargs='*')
|
||||
parser.add_argument('--cxx_flags', default=[], nargs='*')
|
||||
parser.add_argument('--opencv_version', default='', nargs='?')
|
||||
parser.add_argument('--commit', default='Not in working git tree', nargs='?')
|
||||
parser.add_argument('--modules', nargs='+')
|
||||
parser.add_argument('--configuration')
|
||||
parser.add_argument('--outdir')
|
||||
build = parser.parse_args()
|
||||
|
||||
from filters import *
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
# populate the build info template
|
||||
substitute(build, build.outdir)
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
def substitute(cv, output_dir):
|
||||
|
||||
# setup the template engine
|
||||
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
|
||||
jtemplate = Environment(loader=FileSystemLoader(template_dir), trim_blocks=True, lstrip_blocks=True)
|
||||
|
||||
# add the filters
|
||||
jtemplate.filters['cellarray'] = cellarray
|
||||
jtemplate.filters['split'] = split
|
||||
jtemplate.filters['csv'] = csv
|
||||
|
||||
# load the template
|
||||
template = jtemplate.get_template('template_cvmex_base.m')
|
||||
|
||||
# create the build directory
|
||||
output_dir = output_dir+'/+cv'
|
||||
if not os.path.isdir(output_dir):
|
||||
os.mkdir(output_dir)
|
||||
|
||||
# populate template
|
||||
populated = template.render(cv=cv, time=time)
|
||||
with open(os.path.join(output_dir, 'mex.m'), 'wb') as f:
|
||||
f.write(populated.encode('utf-8'))
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""
|
||||
Usage: python cvmex.py
|
||||
--opts [-list -of -opts]
|
||||
--include_dirs [-list -of -opencv_include_directories]
|
||||
--lib_dir opencv_lib_directory
|
||||
--libs [-lopencv_core -lopencv_imgproc ...]
|
||||
--flags [-Wall -opencv_build_flags ...]
|
||||
--outdir /path/to/generated/output
|
||||
|
||||
cvmex.py generates a custom mex compiler that automatically links OpenCV
|
||||
libraries to built sources where appropriate. The calling syntax is the
|
||||
same as the builtin mex compiler, with added cv qualification:
|
||||
>> cv.mex(..., ...);
|
||||
"""
|
||||
|
||||
# parse the input options
|
||||
import sys, re, os, time
|
||||
from argparse import ArgumentParser
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('--opts')
|
||||
parser.add_argument('--include_dirs')
|
||||
parser.add_argument('--lib_dir')
|
||||
parser.add_argument('--libs')
|
||||
parser.add_argument('--flags')
|
||||
parser.add_argument('--outdir')
|
||||
cv = parser.parse_args()
|
||||
|
||||
from filters import *
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
# populate the mex base template
|
||||
substitute(cv, cv.outdir)
|
||||
@@ -0,0 +1,177 @@
|
||||
from textwrap import TextWrapper
|
||||
import re, os
|
||||
# precompile a URL matching regular expression
|
||||
urlexpr = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE)
|
||||
|
||||
def inputs(args):
|
||||
'''Keeps only the input arguments in a list of elements.
|
||||
'''
|
||||
try:
|
||||
return [arg for arg in args['only'] if arg.I and not arg.O]
|
||||
except:
|
||||
return [arg for arg in args if arg.I]
|
||||
|
||||
def ninputs(fun):
|
||||
'''Counts the number of input arguments in the input list'''
|
||||
return len(inputs(fun.req)) + len(inputs(fun.opt))
|
||||
|
||||
def outputs(args):
|
||||
'''Determines whether any of the given arguments is an output
|
||||
reference, and returns a list of only those elements.
|
||||
In OpenCV, output references are preceded by CV_OUT or has *OutputArray* type
|
||||
'''
|
||||
try:
|
||||
return [arg for arg in args['only'] if arg.O and not arg.I]
|
||||
except:
|
||||
return [arg for arg in args if arg.O]
|
||||
|
||||
def only(args):
|
||||
'''Returns exclusively the arguments which are only inputs
|
||||
or only outputs'''
|
||||
d = {};
|
||||
d['only'] = args
|
||||
return d
|
||||
|
||||
def void(arg):
|
||||
'''Is the input 'void' '''
|
||||
return arg == 'void'
|
||||
|
||||
def flip(arg):
|
||||
'''flip the sign of the input'''
|
||||
return not arg
|
||||
|
||||
def noutputs(fun):
|
||||
'''Counts the number of output arguments in the input list'''
|
||||
return int(not void(fun.rtp)) + len(outputs(fun.req)) + len(outputs(fun.opt))
|
||||
|
||||
def convertibleToInt(string):
|
||||
'''Can the input string be evaluated to an integer?'''
|
||||
salt = '1+'
|
||||
try:
|
||||
exec(salt+string)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def binaryToDecimal(string):
|
||||
'''Attempt to convert the input string to floating point representation'''
|
||||
try:
|
||||
return str(eval(string))
|
||||
except:
|
||||
return string
|
||||
|
||||
def formatMatlabConstant(string, table):
|
||||
'''
|
||||
Given a string representing a Constant, and a table of all Constants,
|
||||
attempt to resolve the Constant into a valid Matlab expression
|
||||
For example, the input
|
||||
DEPENDENT_VALUE = 1 << FIXED_VALUE
|
||||
needs to be converted to
|
||||
DEPENDENT_VALUE = bitshift(1, cv.FIXED_VALUE);
|
||||
'''
|
||||
# split the string into expressions
|
||||
words = re.split('(\W+)', string)
|
||||
# add a 'cv' prefix if an expression is also a key in the lookup table
|
||||
words = ''.join([('cv.'+word if word in table else word) for word in words])
|
||||
# attempt to convert arithmetic expressions and binary/hex to decimal
|
||||
words = binaryToDecimal(words)
|
||||
# convert any remaining bitshifts to Matlab 'bitshift' methods
|
||||
shift = re.sub('[\(\) ]', '', words).split('<<')
|
||||
words = 'bitshift('+shift[0]+', '+shift[1]+')' if len(shift) == 2 else words
|
||||
return words
|
||||
|
||||
def matlabURL(string):
|
||||
"""This filter is used to construct a Matlab specific URL that calls the
|
||||
system browser instead of the (insanely bad) builtin Matlab browser"""
|
||||
return re.sub(urlexpr, '<a href="matlab: web(\'\\1\', \'-browser\')">\\1</a>', string)
|
||||
|
||||
def capitalizeFirst(text):
|
||||
'''Capitalize only the first character of the text string'''
|
||||
return text[0].upper() + text[1:]
|
||||
|
||||
def toUpperCamelCase(text):
|
||||
'''variable_name --> VariableName'''
|
||||
return ''.join([capitalizeFirst(word) for word in text.split('_')])
|
||||
|
||||
def toLowerCamelCase(text):
|
||||
'''variable_name --> variableName'''
|
||||
upper_camel = toUpperCamelCase(test)
|
||||
return upper_camel[0].lower() + upper_camel[1:]
|
||||
|
||||
def toUnderCase(text):
|
||||
'''VariableName --> variable_name'''
|
||||
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
|
||||
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
||||
|
||||
def stripTags(text):
|
||||
'''
|
||||
strip or convert html tags from a text string
|
||||
<code>content</code> --> content
|
||||
<anything> --> ''
|
||||
< --> <
|
||||
> --> >
|
||||
&le --> <=
|
||||
&ge --> >=
|
||||
'''
|
||||
upper = lambda pattern: pattern.group(1).upper()
|
||||
text = re.sub('<code>(.*?)</code>', upper, text)
|
||||
text = re.sub('<([^=\s].*?)>', '', text)
|
||||
text = re.sub('<', '<', text)
|
||||
text = re.sub('>', '>', text)
|
||||
text = re.sub('&le', '<=', text)
|
||||
text = re.sub('&ge', '>=', text)
|
||||
return text
|
||||
|
||||
def qualify(text, name):
|
||||
'''Adds uppercase 'CV.' qualification to any occurrences of name in text'''
|
||||
return re.sub(name.upper(), 'CV.'+name.upper(), text)
|
||||
|
||||
def slugify(text):
|
||||
'''A_Function_name --> a-function-name'''
|
||||
return text.lower().replace('_', '-')
|
||||
|
||||
def filename(fullpath):
|
||||
'''Returns only the filename without an extension from a file path
|
||||
eg. /path/to/file.txt --> file
|
||||
'''
|
||||
return os.path.splitext(os.path.basename(fullpath))[0]
|
||||
|
||||
def split(text, delimiter=' '):
|
||||
'''Split a text string into a list using the specified delimiter'''
|
||||
return text.split(delimiter)
|
||||
|
||||
def csv(items, sep=', '):
|
||||
'''format a list with a separator (comma if not specified)'''
|
||||
return sep.join(item for item in items)
|
||||
|
||||
def cellarray(items, escape='\''):
|
||||
'''format a list of items as a matlab cell array'''
|
||||
return '{' + ', '.join(escape+item+escape for item in items) + '}'
|
||||
|
||||
def stripExtraSpaces(text):
|
||||
'''Removes superfluous whitespace from a string, including the removal
|
||||
of all leading and trailing whitespace'''
|
||||
return ' '.join(text.split())
|
||||
|
||||
def comment(text, wrap=80, escape='% ', escape_first='', escape_last=''):
|
||||
'''comment filter
|
||||
Takes a string in text, and wraps it to wrap characters in length with
|
||||
preceding comment escape sequence on each line. escape_first and
|
||||
escape_last can be used for languages which define block comments.
|
||||
Examples:
|
||||
C++ inline comment comment(80, '// ')
|
||||
C block comment: comment(80, ' * ', '/*', ' */')
|
||||
Matlab comment: comment(80, '% ')
|
||||
Matlab block comment: comment(80, '', '%{', '%}')
|
||||
Python docstrings: comment(80, '', '\'\'\'', '\'\'\'')
|
||||
'''
|
||||
|
||||
tw = TextWrapper(width=wrap-len(escape))
|
||||
if escape_first:
|
||||
escape_first = escape_first+'\n'
|
||||
if escape_last:
|
||||
escape_last = '\n'+escape_last
|
||||
escapn = '\n'+escape
|
||||
lines = text.split('\n')
|
||||
wlines = (tw.wrap(line) for line in lines)
|
||||
return escape_first+escape+escapn.join(escapn.join(line) for line in wlines)+escape_last
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python
|
||||
import sys, re, os, time
|
||||
from string import Template
|
||||
from parse_tree import ParseTree, todict, constants
|
||||
from filters import *
|
||||
|
||||
updated_files = []
|
||||
|
||||
def update_file(fname, content):
|
||||
if fname in updated_files:
|
||||
print('ERROR(gen_matlab.py): attemption to write file multiple times: {}'.format(fname))
|
||||
return
|
||||
updated_files.append(fname)
|
||||
if os.path.exists(fname):
|
||||
with open(fname, 'rb') as f:
|
||||
old_content = f.read()
|
||||
if old_content == content:
|
||||
#print('Up-to-date: {}'.format(fname))
|
||||
return
|
||||
print('Updating: {}'.format(fname))
|
||||
else:
|
||||
print('Writing: {}'.format(fname))
|
||||
with open(fname, 'wb') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
class MatlabWrapperGenerator(object):
|
||||
"""
|
||||
MatlabWrapperGenerator is a class for generating Matlab mex sources from
|
||||
a set of C++ headers. MatlabWrapperGenerator objects can be default
|
||||
constructed. Given an instance, the gen() method performs the translation.
|
||||
"""
|
||||
|
||||
def gen(self, module_roots, modules, extras, output_dir):
|
||||
"""
|
||||
Generate a set of Matlab mex source files by parsing exported symbols
|
||||
in a set of C++ headers. The headers can be input in one (or both) of
|
||||
two methods:
|
||||
1. specify module_root and modules
|
||||
Given a path to the OpenCV module root and a list of module names,
|
||||
the headers to parse are implicitly constructed.
|
||||
2. specifiy header locations explicitly in extras
|
||||
Each element in the list of extras must be of the form:
|
||||
'namespace=/full/path/to/extra/header.hpp' where 'namespace' is
|
||||
the namespace in which the definitions should be added.
|
||||
The output_dir specifies the directory to write the generated sources
|
||||
to.
|
||||
"""
|
||||
# dynamically import the parsers
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
import hdr_parser
|
||||
|
||||
# parse each of the files and store in a dictionary
|
||||
# as a separate "namespace"
|
||||
parser = hdr_parser.CppHeaderParser()
|
||||
|
||||
ns = dict((key, []) for key in modules)
|
||||
path_template = Template('${module}/include/opencv2/${module}.hpp')
|
||||
|
||||
for module in modules:
|
||||
for module_root in module_roots:
|
||||
# construct a header path from the module root and a path template
|
||||
header = os.path.join(module_root, path_template.substitute(module=module))
|
||||
if os.path.isfile(header):
|
||||
break
|
||||
else:
|
||||
raise Exception('no header found for module %s!' % module)
|
||||
|
||||
# parse the definitions
|
||||
ns[module] = parser.parse(header)
|
||||
|
||||
for extra in extras:
|
||||
module = extra.split("=")[0]
|
||||
header = extra.split("=")[1]
|
||||
ns[module] = ns[module] + parser.parse(header) if module in ns else parser.parse(header)
|
||||
|
||||
# cleanify the parser output
|
||||
parse_tree = ParseTree()
|
||||
parse_tree.build(ns)
|
||||
|
||||
# setup the template engine
|
||||
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
|
||||
jtemplate = Environment(loader=FileSystemLoader(template_dir), trim_blocks=True, lstrip_blocks=True)
|
||||
|
||||
# add the custom filters
|
||||
jtemplate.filters['formatMatlabConstant'] = formatMatlabConstant
|
||||
jtemplate.filters['convertibleToInt'] = convertibleToInt
|
||||
jtemplate.filters['toUpperCamelCase'] = toUpperCamelCase
|
||||
jtemplate.filters['toLowerCamelCase'] = toLowerCamelCase
|
||||
jtemplate.filters['toUnderCase'] = toUnderCase
|
||||
jtemplate.filters['matlabURL'] = matlabURL
|
||||
jtemplate.filters['stripTags'] = stripTags
|
||||
jtemplate.filters['filename'] = filename
|
||||
jtemplate.filters['comment'] = comment
|
||||
jtemplate.filters['inputs'] = inputs
|
||||
jtemplate.filters['ninputs'] = ninputs
|
||||
jtemplate.filters['outputs'] = outputs
|
||||
jtemplate.filters['noutputs'] = noutputs
|
||||
jtemplate.filters['qualify'] = qualify
|
||||
jtemplate.filters['slugify'] = slugify
|
||||
jtemplate.filters['only'] = only
|
||||
jtemplate.filters['void'] = void
|
||||
jtemplate.filters['not'] = flip
|
||||
|
||||
# load the templates
|
||||
tfunction = jtemplate.get_template('template_function_base.cpp')
|
||||
tclassm = jtemplate.get_template('template_class_base.m')
|
||||
tclassc = jtemplate.get_template('template_class_base.cpp')
|
||||
tconst = jtemplate.get_template('template_map_base.m')
|
||||
|
||||
# create the build directory
|
||||
output_source_dir = output_dir+'/src'
|
||||
output_private_dir = output_source_dir+'/private'
|
||||
output_class_dir = output_dir+'/+cv'
|
||||
output_map_dir = output_dir+'/map'
|
||||
if not os.path.isdir(output_source_dir):
|
||||
os.makedirs(output_source_dir)
|
||||
if not os.path.isdir(output_private_dir):
|
||||
os.makedirs(output_private_dir)
|
||||
if not os.path.isdir(output_class_dir):
|
||||
os.makedirs(output_class_dir)
|
||||
if not os.path.isdir(output_map_dir):
|
||||
os.makedirs(output_map_dir)
|
||||
|
||||
# populate templates
|
||||
for namespace in parse_tree.namespaces:
|
||||
# functions
|
||||
for method in namespace.methods:
|
||||
populated = tfunction.render(fun=method, time=time, includes=namespace.name)
|
||||
update_file(output_source_dir+'/'+method.name+'.cpp', populated.encode('utf-8'))
|
||||
# classes
|
||||
for clss in namespace.classes:
|
||||
# cpp converter
|
||||
populated = tclassc.render(clss=clss, time=time)
|
||||
update_file(output_private_dir+'/'+clss.name+'Bridge.cpp', populated.encode('utf-8'))
|
||||
# matlab classdef
|
||||
populated = tclassm.render(clss=clss, time=time)
|
||||
update_file(output_class_dir+'/'+clss.name+'.m', populated.encode('utf-8'))
|
||||
|
||||
# create a global constants lookup table
|
||||
const = dict(constants(todict(parse_tree.namespaces)))
|
||||
populated = tconst.render(constants=const, time=time)
|
||||
update_file(output_dir+'/cv.m', populated.encode('utf-8'))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""
|
||||
Usage: python gen_matlab.py
|
||||
--hdrparser /path/to/hdr_parser/dir
|
||||
--moduleroot [ /path/to/opencv/modules /path/to/opencv_contrib/modules etc ]
|
||||
--modules [core imgproc objdetect etc]
|
||||
--extra namespace=/path/to/extra/header.hpp
|
||||
--outdir /path/to/output/generated/srcs
|
||||
|
||||
gen_matlab.py is the main control script for generating matlab source
|
||||
files from given set of headers. Internally, gen_matlab:
|
||||
1. constructs the headers to parse from the module root and list of modules
|
||||
2. parses the headers using CppHeaderParser
|
||||
3. refactors the definitions using ParseTree
|
||||
4. populates the templates for classes, function, enums from the
|
||||
definitions
|
||||
|
||||
gen_matlab.py requires the following inputs:
|
||||
--hdrparser the path to the header parser directory
|
||||
(opencv/modules/python/src2)
|
||||
--moduleroot (optional) paths to the opencv directories containing the modules
|
||||
--modules (optional - required if --moduleroot specified) the modules
|
||||
to produce bindings for. The path to the include directories
|
||||
as well as the namespaces are constructed from the modules
|
||||
and the moduleroot
|
||||
--extra extra headers explicitly defined to parse. This must be in
|
||||
the format "namepsace=/path/to/extra/header.hpp". For example,
|
||||
the core module requires the extra header:
|
||||
"core=/opencv/modules/core/include/opencv2/core/core/base.hpp"
|
||||
--outdir the output directory to put the generated matlab sources. In
|
||||
the OpenCV build this is "${CMAKE_CURRENT_BUILD_DIR}/src"
|
||||
"""
|
||||
|
||||
# parse the input options
|
||||
from argparse import ArgumentParser
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('--hdrparser')
|
||||
parser.add_argument('--moduleroot', nargs='*', default=[], required=False)
|
||||
parser.add_argument('--modules', nargs='*', default=[], required=False)
|
||||
parser.add_argument('--extra', nargs='*', default=[], required=False)
|
||||
parser.add_argument('--outdir')
|
||||
args = parser.parse_args()
|
||||
|
||||
# add the hdr_parser module to the path
|
||||
sys.path.append(args.hdrparser)
|
||||
|
||||
# create the generator
|
||||
mwg = MatlabWrapperGenerator()
|
||||
mwg.gen(args.moduleroot, args.modules, args.extra, args.outdir)
|
||||
@@ -0,0 +1,386 @@
|
||||
import sys
|
||||
if sys.version_info >= (3, 10):
|
||||
import collections.abc
|
||||
IterableType = collections.abc.Iterable
|
||||
else:
|
||||
import collections
|
||||
IterableType = collections.Iterable
|
||||
from textwrap import fill
|
||||
from filters import *
|
||||
try:
|
||||
# Python 2.7+
|
||||
basestring
|
||||
except NameError:
|
||||
# Python 3.3+
|
||||
basestring = str
|
||||
|
||||
|
||||
valid_types = (
|
||||
'int', 'bool', 'float', 'double', 'size_t', 'char',
|
||||
'Mat', 'Scalar', 'String',
|
||||
'TermCriteria', 'Size', 'Point', 'Point2f', 'Point2d', 'Rect', 'RotatedRect',
|
||||
'RNG', 'DMatch', 'Moments',
|
||||
'vector_Mat', 'vector_Point', 'vector_int', 'vector_float', 'vector_double', 'vector_String', 'vector_uchar', 'vector_Rect', 'vector_DMatch', 'vector_KeyPoint',
|
||||
'vector_Point2f', 'vector_vector_char', 'vector_vector_DMatch', 'vector_vector_KeyPoint',
|
||||
'Ptr_StereoBM', 'Ptr_StereoSGBM', 'Ptr_FeatureDetector', 'Ptr_CLAHE', 'Ptr_LineSegmentDetector', 'Ptr_AlignMTB', 'Ptr_CalibrateDebevec',
|
||||
'Ptr_CalibrateRobertson', 'Ptr_DenseOpticalFlow', 'Ptr_DualTVL1OpticalFlow', 'Ptr_MergeDebevec', 'Ptr_MergeMertens', 'Ptr_MergeRobertson',
|
||||
'Ptr_Stitcher', 'Ptr_Tonemap', 'Ptr_TonemapDrago', 'Ptr_TonemapDurand', 'Ptr_TonemapMantiuk', 'Ptr_TonemapReinhard', 'Ptr_float',
|
||||
# Not supported:
|
||||
#vector_vector_KeyPoint
|
||||
)
|
||||
|
||||
class ParseTree(object):
|
||||
"""
|
||||
The ParseTree class produces a semantic tree of C++ definitions given
|
||||
the output of the CppHeaderParser (from opencv/modules/python/src2/hdr_parser.py)
|
||||
|
||||
The full hierarchy is as follows:
|
||||
|
||||
Namespaces
|
||||
|
|
||||
|- name
|
||||
|- Classes
|
||||
|
|
||||
|- name
|
||||
|- Methods
|
||||
|- Constants
|
||||
|- Methods
|
||||
|
|
||||
|- name
|
||||
|- static (T/F)
|
||||
|- return type
|
||||
|- required Arguments
|
||||
|
|
||||
|- name
|
||||
|- const (T/F)
|
||||
|- reference ('&'/'*')
|
||||
|- type
|
||||
|- input
|
||||
|- output (pass return by reference)
|
||||
|- default value
|
||||
|- optional Arguments
|
||||
|- Constants
|
||||
|
|
||||
|- name
|
||||
|- const (T/F)
|
||||
|- reference ('&'/'*')
|
||||
|- type
|
||||
|- value
|
||||
|
||||
The semantic tree contains substantial information for easily introspecting
|
||||
information about objects. How many methods does the 'core' namespace have?
|
||||
Does the 'randn' method have any return by reference (output) arguments?
|
||||
How many required and optional arguments does the 'add' method have? Is the
|
||||
variable passed by reference or raw pointer?
|
||||
|
||||
Individual definitions from the parse tree (Classes, Functions, Constants)
|
||||
are passed to the Jinja2 template engine where they are manipulated to
|
||||
produce Matlab mex sources.
|
||||
|
||||
A common call tree for constructing and using a ParseTree object is:
|
||||
|
||||
# parse a set of definitions into a dictionary of namespaces
|
||||
parser = CppHeaderParser()
|
||||
ns['core'] = parser.parse('path/to/opencv/core.hpp')
|
||||
|
||||
# refactor into a semantic tree
|
||||
parse_tree = ParseTree()
|
||||
parse_tree.build(ns)
|
||||
|
||||
# iterate over the tree
|
||||
for namespace in parse_tree.namespaces:
|
||||
for clss in namespace.classes:
|
||||
# do stuff
|
||||
for method in namespace.methods:
|
||||
# do stuff
|
||||
|
||||
Calling 'print' on a ParseTree object will reconstruct the definitions
|
||||
to produce an output resembling the original C++ code.
|
||||
"""
|
||||
def __init__(self, namespaces=None):
|
||||
self.namespaces = namespaces if namespaces else []
|
||||
|
||||
def __str__(self):
|
||||
return '\n\n\n'.join(ns.__str__() for ns in self.namespaces)
|
||||
|
||||
def build(self, namespaces):
|
||||
babel = Translator()
|
||||
for name, definitions in namespaces.items():
|
||||
class_tree = {}
|
||||
methods = []
|
||||
constants = []
|
||||
for defn in definitions:
|
||||
try:
|
||||
obj = babel.translate(defn)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
obj = None
|
||||
if obj is None:
|
||||
continue
|
||||
if type(obj) is Class or obj.clss:
|
||||
self.insertIntoClassTree(obj, class_tree)
|
||||
elif type(obj) is Method:
|
||||
methods.append(obj)
|
||||
elif type(obj) is Constant:
|
||||
constants.append(obj)
|
||||
else:
|
||||
raise TypeError('Unexpected object type: '+str(type(obj)))
|
||||
self.namespaces.append(Namespace(name, constants, list(class_tree.values()), methods))
|
||||
|
||||
def insertIntoClassTree(self, obj, class_tree):
|
||||
cname = obj.name if type(obj) is Class else obj.clss
|
||||
if not cname:
|
||||
return
|
||||
if not cname in class_tree:
|
||||
# add a new class to the tree
|
||||
class_tree[cname] = Class(cname)
|
||||
# insert the definition into the class
|
||||
val = class_tree[cname]
|
||||
if type(obj) is Method:
|
||||
val.methods.append(obj)
|
||||
elif type(obj) is Constant:
|
||||
val.constants.append(obj)
|
||||
else:
|
||||
raise TypeError('Unexpected object type: '+str(type(obj)))
|
||||
|
||||
|
||||
|
||||
class Translator(object):
|
||||
"""
|
||||
The Translator class does the heavy lifting of translating the nested
|
||||
list representation of the hdr_parser into individual definitions that
|
||||
are inserted into the ParseTree.
|
||||
Translator consists of a top-level method: translate()
|
||||
along with a number of helper methods: translateClass(), translateMethod(),
|
||||
translateArgument(), translateConstant(), translateName(), and
|
||||
translateClassName()
|
||||
"""
|
||||
def translate(self, defn):
|
||||
# --- class ---
|
||||
# classes have 'class' prefixed on their name
|
||||
if 'class' in defn[0].split(' ') or 'struct' in defn[0].split(' '):
|
||||
return self.translateClass(defn)
|
||||
# --- operators! ---
|
||||
#TODO: implement operators: http://www.mathworks.com.au/help/matlab/matlab_oop/implementing-operators-for-your-class.html
|
||||
if 'operator' in defn[0]:
|
||||
return
|
||||
# --- constant ---
|
||||
elif convertibleToInt(defn[1]):
|
||||
return self.translateConstant(defn)
|
||||
# --- function ---
|
||||
# functions either need to have input arguments, or not uppercase names
|
||||
elif defn[3] or not self.translateName(defn[0]).split('_')[0].isupper():
|
||||
return self.translateMethod(defn)
|
||||
# --- constant ---
|
||||
else:
|
||||
return self.translateConstant(defn)
|
||||
|
||||
def translateClass(self, defn):
|
||||
return Class()
|
||||
|
||||
def translateMethod(self, defn, class_tree=None):
|
||||
name = self.translateName(defn[0])
|
||||
clss = self.translateClassName(defn[0])
|
||||
rtp = defn[1]
|
||||
static = True if 'S' in ''.join(defn[2]) else False
|
||||
args = defn[3]
|
||||
req = []
|
||||
opt = []
|
||||
for arg in args:
|
||||
if arg:
|
||||
a = self.translateArgument(arg)
|
||||
opt.append(a) if a.default else req.append(a)
|
||||
return Method(name, clss, static, '', rtp, False, req, opt)
|
||||
|
||||
def translateConstant(self, defn):
|
||||
const = True if 'const' in defn[0] else False
|
||||
name = self.translateName(defn[0])
|
||||
clss = self.translateClassName(defn[0])
|
||||
tp = 'int'
|
||||
val = defn[1]
|
||||
return Constant(name, clss, tp, const, '', val)
|
||||
|
||||
def translateArgument(self, defn):
|
||||
modifiers = defn[3]
|
||||
ref = '*' if '*' in defn[0] else ''
|
||||
ref = '&' if '&' in defn[0] or '/Ref' in modifiers else ref
|
||||
const = '/C' in modifiers
|
||||
tp = " ".join([word for word in defn[0].replace(ref, '').split() if not ' const ' in ' '+word+' '])
|
||||
name = defn[1]
|
||||
default = defn[2] if defn[2] else ''
|
||||
I = True if '/I' in modifiers or not '/O' in modifiers else False
|
||||
O = True if '/O' in modifiers else False
|
||||
return Argument(name, tp, const, I, O, ref, default)
|
||||
|
||||
def translateName(self, name):
|
||||
return name.split(' ')[-1].split('.')[-1]
|
||||
|
||||
def translateClassName(self, name):
|
||||
name = name.split(' ')[-1]
|
||||
parts = name.split('.')
|
||||
return parts[-2] if len(parts) > 1 and not parts[-2] == 'cv' else ''
|
||||
|
||||
|
||||
|
||||
class Namespace(object):
|
||||
"""
|
||||
Namespace
|
||||
|
|
||||
|- name
|
||||
|- Constants
|
||||
|- Methods
|
||||
|- Constants
|
||||
"""
|
||||
def __init__(self, name='', constants=None, classes=None, methods=None):
|
||||
self.name = name
|
||||
self.constants = constants if constants else []
|
||||
self.classes = classes if classes else []
|
||||
self.methods = methods if methods else []
|
||||
|
||||
def __str__(self):
|
||||
return 'namespace '+self.name+' {\n\n'+\
|
||||
('\n'.join(c.__str__() for c in self.constants)+'\n\n' if self.constants else '')+\
|
||||
('\n'.join(f.__str__() for f in self.methods)+'\n\n' if self.methods else '')+\
|
||||
('\n\n'.join(o.__str__() for o in self.classes) if self.classes else '')+'\n};'
|
||||
|
||||
class Class(object):
|
||||
"""
|
||||
Class
|
||||
|
|
||||
|- name
|
||||
|- Methods
|
||||
|- Constants
|
||||
"""
|
||||
def __init__(self, name='', namespace='', constants=None, methods=None):
|
||||
self.name = name
|
||||
self.namespace = namespace
|
||||
self.constants = constants if constants else []
|
||||
self.methods = methods if methods else []
|
||||
|
||||
def __str__(self):
|
||||
return 'class '+self.name+' {\n\t'+\
|
||||
('\n\t'.join(c.__str__() for c in self.constants)+'\n\n\t' if self.constants else '')+\
|
||||
('\n\t'.join(f.__str__() for f in self.methods) if self.methods else '')+'\n};'
|
||||
|
||||
class Method(object):
|
||||
"""
|
||||
Method
|
||||
int VideoWriter::read( cv::Mat& frame, const cv::Mat& mask=cv::Mat() );
|
||||
--- ----- ---- -------- ----------------
|
||||
rtp class name required optional
|
||||
|
||||
name the method name
|
||||
clss the class the method belongs to ('' if free)
|
||||
static static?
|
||||
namespace the namespace the method belongs to ('' if free)
|
||||
rtp the return type
|
||||
const const?
|
||||
req list of required arguments
|
||||
opt list of optional arguments
|
||||
"""
|
||||
def __init__(self, name='', clss='', static=False, namespace='', rtp='', const=False, req=None, opt=None):
|
||||
self.name = name
|
||||
self.clss = clss
|
||||
self.constructor = True if name == clss else False
|
||||
self.static = static
|
||||
self.const = const
|
||||
self.namespace = namespace
|
||||
self.rtp = rtp
|
||||
self.req = req if req else []
|
||||
self.opt = opt if opt else []
|
||||
|
||||
def __str__(self):
|
||||
return (self.rtp+' ' if self.rtp else '')+self.name+'('+\
|
||||
', '.join(arg.__str__() for arg in self.req+self.opt)+\
|
||||
')'+(' const' if self.const else '')+';'
|
||||
|
||||
class Argument(object):
|
||||
"""
|
||||
Argument
|
||||
const cv::Mat& mask=cv::Mat()
|
||||
----- ---- --- ---- -------
|
||||
const tp ref name default
|
||||
|
||||
name the argument name
|
||||
tp the argument type
|
||||
const const?
|
||||
I is the argument treated as an input?
|
||||
O is the argument treated as an output (return by reference)
|
||||
ref is the argument passed by reference? ('*'/'&')
|
||||
default the default value of the argument ('' if required)
|
||||
"""
|
||||
def __init__(self, name='', tp='', const=False, I=True, O=False, ref='', default=''):
|
||||
self.name = name
|
||||
self.tp = tp
|
||||
self.ref = ref
|
||||
self.I = I
|
||||
self.O = O
|
||||
self.const = const
|
||||
self.default = default
|
||||
if not tp in valid_types:
|
||||
raise Exception("Non-supported argument type: {} (name: {})".format(tp, name))
|
||||
|
||||
def __str__(self):
|
||||
return ('const ' if self.const else '')+self.tp+self.ref+\
|
||||
' '+self.name+('='+self.default if self.default else '')
|
||||
|
||||
class Constant(object):
|
||||
"""
|
||||
Constant
|
||||
DFT_COMPLEX_OUTPUT = 12;
|
||||
---- -------
|
||||
name default
|
||||
|
||||
name the name of the constant
|
||||
clss the class that the constant belongs to ('' if free)
|
||||
tp the type of the constant ('' if int)
|
||||
const const?
|
||||
ref is the constant a reference? ('*'/'&')
|
||||
default default value, required for constants
|
||||
"""
|
||||
def __init__(self, name='', clss='', tp='', const=False, ref='', default=''):
|
||||
self.name = name
|
||||
self.clss = clss
|
||||
self.tp = tp
|
||||
self.ref = ref
|
||||
self.const = const
|
||||
self.default = default
|
||||
|
||||
def __str__(self):
|
||||
return ('const ' if self.const else '')+self.tp+self.ref+\
|
||||
' '+self.name+('='+self.default if self.default else '')+';'
|
||||
|
||||
def constants(tree):
|
||||
"""
|
||||
recursive generator to strip all Constant objects from the ParseTree
|
||||
and place them into a flat dictionary of { name, value (default) }
|
||||
"""
|
||||
if isinstance(tree, dict) and 'constants' in tree and isinstance(tree['constants'], list):
|
||||
for node in tree['constants']:
|
||||
yield (node['name'], node['default'])
|
||||
if isinstance(tree, dict):
|
||||
for key, val in tree.items():
|
||||
for gen in constants(val):
|
||||
yield gen
|
||||
if isinstance(tree, list):
|
||||
for val in tree:
|
||||
for gen in constants(val):
|
||||
yield gen
|
||||
|
||||
|
||||
def todict(obj):
|
||||
"""
|
||||
Recursively convert a Python object graph to sequences (lists)
|
||||
and mappings (dicts) of primitives (bool, int, float, string, ...)
|
||||
"""
|
||||
if isinstance(obj, basestring):
|
||||
return obj
|
||||
elif isinstance(obj, dict):
|
||||
return dict((key, todict(val)) for key, val in obj.items())
|
||||
elif isinstance(obj, IterableType):
|
||||
return [todict(val) for val in obj]
|
||||
elif hasattr(obj, '__dict__'):
|
||||
return todict(vars(obj))
|
||||
elif hasattr(obj, '__slots__'):
|
||||
return todict(dict((name, getattr(obj, name)) for name in getattr(obj, '__slots__')))
|
||||
return obj
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* compose
|
||||
* compose a function call
|
||||
* This macro takes as input a Method object and composes
|
||||
* a function call by inspecting the types and argument names
|
||||
*/
|
||||
{% macro compose(fun) %}
|
||||
{# ----------- Return type ------------- #}
|
||||
{%- if not fun.rtp|void and not fun.constructor -%} retval = {% endif -%}
|
||||
{%- if fun.constructor -%}{{fun.clss}} obj = {% endif -%}
|
||||
{%- if fun.clss and not fun.constructor -%}inst.{%- else -%} cv:: {%- endif -%}
|
||||
{{fun.name}}(
|
||||
{#- ----------- Required ------------- -#}
|
||||
{%- for arg in fun.req -%}
|
||||
{%- if arg.ref == '*' -%}&{%- endif -%}
|
||||
{{arg.name}}
|
||||
{%- if not loop.last %}, {% endif %}
|
||||
{% endfor %}
|
||||
{#- ----------- Optional ------------- -#}
|
||||
{% if fun.req and fun.opt %}, {% endif %}
|
||||
{%- for opt in fun.opt -%}
|
||||
{%- if opt.ref == '*' -%}&{%- endif -%}
|
||||
{{opt.name}}
|
||||
{%- if not loop.last -%}, {% endif %}
|
||||
{%- endfor -%}
|
||||
);
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
/*
|
||||
* composeMatlab
|
||||
* compose a Matlab function call
|
||||
* This macro takes as input a Method object and composes
|
||||
* a Matlab function call by inspecting the types and argument names
|
||||
*/
|
||||
{% macro composeMatlab(fun) %}
|
||||
{# ----------- Return type ------------- #}
|
||||
{%- if fun|noutputs > 1 -%}[{% endif -%}
|
||||
{%- if not fun.rtp|void -%}LVALUE{% endif -%}
|
||||
{%- if not fun.rtp|void and fun|noutputs > 1 -%},{% endif -%}
|
||||
{# ------------- Outputs ------------- -#}
|
||||
{%- for arg in fun.req|outputs + fun.opt|outputs -%}
|
||||
{{arg.name}}
|
||||
{%- if arg.I -%}_out{%- endif -%}
|
||||
{%- if not loop.last %}, {% endif %}
|
||||
{% endfor %}
|
||||
{%- if fun|noutputs > 1 -%}]{% endif -%}
|
||||
{%- if fun|noutputs %} = {% endif -%}
|
||||
cv.{{fun.name}}(
|
||||
{#- ------------ Inputs -------------- -#}
|
||||
{%- for arg in fun.req|inputs + fun.opt|inputs -%}
|
||||
{{arg.name}}
|
||||
{%- if arg.O -%}_in{%- endif -%}
|
||||
{%- if not loop.last %}, {% endif -%}
|
||||
{% endfor -%}
|
||||
);
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
/*
|
||||
* composeVariant
|
||||
* compose a variant call for the ArgumentParser
|
||||
*/
|
||||
{% macro composeVariant(fun) %}
|
||||
addVariant("{{ fun.name }}", {{ fun.req|inputs|length }}, {{ fun.opt|inputs|length }}
|
||||
{%- if fun.opt|inputs|length %}, {% endif -%}
|
||||
{%- for arg in fun.opt|inputs -%}
|
||||
"{{arg.name}}"
|
||||
{%- if not loop.last %}, {% endif -%}
|
||||
{% endfor -%}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
/*
|
||||
* composeWithExceptionHandler
|
||||
* compose a function call wrapped in exception traps
|
||||
* This macro takes an input a Method object and composes a function
|
||||
* call through the compose() macro, then wraps the return in traps
|
||||
* for cv::Exceptions, std::exceptions, and all generic exceptions
|
||||
* and returns a useful error message to the Matlab interpreter
|
||||
*/
|
||||
{%- macro composeWithExceptionHandler(fun) -%}
|
||||
// call the opencv function
|
||||
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
|
||||
try {
|
||||
{{ compose(fun) }}
|
||||
} catch(const cv::Exception& e) {
|
||||
error(std::string("cv::exception caught: ").append(e.what()).c_str());
|
||||
} catch(const std::exception& e) {
|
||||
error(std::string("std::exception caught: ").append(e.what()).c_str());
|
||||
} catch(...) {
|
||||
error("Uncaught exception occurred in {{fun.name}}");
|
||||
}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
/*
|
||||
* handleInputs
|
||||
* unpack input arguments from the Bridge
|
||||
* Given an input Bridge object, this unpacks the object from the Bridge and
|
||||
* casts them into the correct type
|
||||
*/
|
||||
{%- macro handleInputs(fun) %}
|
||||
|
||||
{% if fun|ninputs or (fun|noutputs and not fun.constructor) %}
|
||||
// - inputs
|
||||
{% for arg in fun.req|inputs %}
|
||||
{{arg.tp}} {{arg.name}} = inputs[{{ loop.index0 }}].to{{arg.tp|toUpperCamelCase}}();
|
||||
{% endfor %}
|
||||
// - inputs (opt)
|
||||
{% for opt in fun.opt|inputs %}
|
||||
{{opt.tp}} {{opt.name}} = inputs[{{loop.index0 + fun.req|inputs|length}}].empty() ? ({{opt.tp}}) {% if opt.ref == '*' -%} {{opt.tp}}() {%- else -%} {{opt.default}} {%- endif %} : inputs[{{loop.index0 + fun.req|inputs|length}}].to{{opt.tp|toUpperCamelCase}}();
|
||||
{% endfor %}
|
||||
// - outputs
|
||||
{% for arg in fun.req|only|outputs %}
|
||||
{{arg.tp}} {{arg.name}};
|
||||
{% endfor %}
|
||||
// - outputs (opt)
|
||||
{% for opt in fun.opt|only|outputs %}
|
||||
{{opt.tp}} {{opt.name}};
|
||||
{% endfor %}
|
||||
// - return
|
||||
{% if not fun.rtp|void and not fun.constructor %}
|
||||
{{fun.rtp}} retval;
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{%- endmacro %}
|
||||
|
||||
/*
|
||||
* handleOutputs
|
||||
* pack outputs into the bridge
|
||||
* Given a set of outputs, this methods assigns them into the bridge for
|
||||
* return to the calling method
|
||||
*/
|
||||
{%- macro handleOutputs(fun) %}
|
||||
|
||||
{% if fun|noutputs %}
|
||||
// assign the outputs into the bridge
|
||||
{% if not fun.rtp|void and not fun.constructor %}
|
||||
outputs[0] = retval;
|
||||
{% endif %}
|
||||
{% for arg in fun.req|outputs %}
|
||||
outputs[{{loop.index0 + fun.rtp|void|not}}] = {{arg.name}};
|
||||
{% endfor %}
|
||||
{% for opt in fun.opt|outputs %}
|
||||
outputs[{{loop.index0 + fun.rtp|void|not + fun.req|outputs|length}}] = {{opt.name}};
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,41 @@
|
||||
function buildInformation()
|
||||
%CV.BUILDINFORMATION display OpenCV Toolbox build information
|
||||
%
|
||||
% Call CV.BUILDINFORMATION() to get a printout of diagonstic information
|
||||
% pertaining to your particular build of the OpenCV Toolbox. If you ever
|
||||
% run into issues with the Toolbox, it is useful to submit this
|
||||
% information alongside a bug report to the OpenCV team.
|
||||
%
|
||||
% Copyright {{ time.strftime("%Y", time.localtime()) }} The OpenCV Foundation
|
||||
%
|
||||
info = {
|
||||
' ------------------------------------------------------------------------'
|
||||
' <strong>OpenCV Toolbox</strong>'
|
||||
' Build and diagnostic information'
|
||||
' ------------------------------------------------------------------------'
|
||||
''
|
||||
' <strong>Platform</strong>'
|
||||
' OS: {{ build.os }}'
|
||||
' Architecture: {{ build.arch[0] }}-bit {{ build.arch[1] }}'
|
||||
' Compiler: {{ build.compiler | csv(' ') }}'
|
||||
''
|
||||
' <strong>Matlab</strong>'
|
||||
[' Version: ' version()]
|
||||
[' Mex extension: ' mexext()]
|
||||
' Architecture: {{ build.mex_arch }}'
|
||||
' Mex path: {{ build.mex_script }}'
|
||||
' Mex flags: {{ build.mex_opts | csv(' ') }}'
|
||||
' CXX flags: {{ build.cxx_flags | csv(' ') | stripExtraSpaces | wordwrap(60, True, '\'\n\' ') }}'
|
||||
''
|
||||
' <strong>OpenCV</strong>'
|
||||
' Version: {{ build.opencv_version }}'
|
||||
' Commit: {{ build.commit }}'
|
||||
' Configuration: {{ build.configuration }}'
|
||||
' Modules: {{ build.modules | csv | wordwrap(60, True, '\'\n\' ') }}'
|
||||
''
|
||||
};
|
||||
|
||||
info = cellfun(@(x) [x '\n'], info, 'UniformOutput', false);
|
||||
info = horzcat(info{:});
|
||||
fprintf(info);
|
||||
end
|
||||
@@ -0,0 +1,97 @@
|
||||
{% import 'functional.cpp' as functional %}
|
||||
/*
|
||||
* file: {{clss.name}}Bridge.cpp
|
||||
* author: A trusty code generator
|
||||
*
|
||||
* This file was autogenerated, do not modify.
|
||||
* See LICENSE for full modification and redistribution details.
|
||||
* Copyright 2018 The OpenCV Foundation
|
||||
*/
|
||||
#include <mex.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <opencv2/matlab/map.hpp>
|
||||
#include <opencv2/matlab/bridge.hpp>
|
||||
#include <opencv2/core.hpp>
|
||||
using namespace cv;
|
||||
using namespace matlab;
|
||||
using namespace bridge;
|
||||
|
||||
namespace {
|
||||
|
||||
typedef std::vector<Bridge> (*)({{clss.name}}&, const std::vector<Bridge>&) MethodSignature;
|
||||
|
||||
{% for function in clss.methods %}
|
||||
|
||||
{% if function.constructor %}
|
||||
// wrapper for {{function.name}}() constructor
|
||||
{{ function.clss }} {{function.name}}(const std::vector<Bridge>& inputs) {
|
||||
{{ functional.handleInputs(function) }}
|
||||
{{ functional.compose(function) }}
|
||||
return obj;
|
||||
}
|
||||
{% else %}
|
||||
// wrapper for {{function.name}}() method
|
||||
std::vector<Bridge> {{function.name}}({{clss.name}}& inst, const std::vector<Bridge>& inputs) {
|
||||
std::vector<Bridge> outputs{% if function|noutputs %}({{function|noutputs}}){% endif %};
|
||||
{{ functional.handleInputs(function) }}
|
||||
{{ functional.composeWithExceptionHandler(function) }}
|
||||
{{ functional.handleOutputs(function) }}
|
||||
return outputs;
|
||||
}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
Map<std::string, MethodSignature> createMethodMap() {
|
||||
Map<std::string, MethodSignature> m;
|
||||
{% for function in clss.methods %}
|
||||
m["{{function.name}}"] = &{{function.name}};
|
||||
{% endfor %}
|
||||
|
||||
return m;
|
||||
}
|
||||
static const Map<std::string, MethodSignature> methods = createMethodMap();
|
||||
|
||||
// map of created {{clss.name}} instances. Don't trust the user to keep them safe...
|
||||
static Map<void *, {{clss.name}}> instances;
|
||||
|
||||
/*
|
||||
* {{ clss.name }}
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// parse the inputs
|
||||
Bridge method_name(prhs[0]);
|
||||
|
||||
Bridge handle(prhs[1]);
|
||||
std::vector<Bridge> brhs(prhs+2, prhs+nrhs);
|
||||
|
||||
// retrieve the instance of interest
|
||||
try {
|
||||
{{clss.name}}& inst = instances.at(handle.address());
|
||||
} catch (const std::out_of_range& e) {
|
||||
mexErrMsgTxt("Invalid object instance provided");
|
||||
}
|
||||
|
||||
// invoke the correct method on the data
|
||||
try {
|
||||
std::vector<Bridge> blhs = (*methods.at(method_name))(inst, brhs);
|
||||
} catch (const std::out_of_range& e) {
|
||||
mexErrMsgTxt("Unknown method specified");
|
||||
}
|
||||
|
||||
{% block postfun %}
|
||||
{% endblock %}
|
||||
|
||||
{% block cleanup %}
|
||||
{% endblock %}
|
||||
|
||||
}
|
||||
|
||||
} // end namespace
|
||||
@@ -0,0 +1,31 @@
|
||||
% {{clss.name | upper}}
|
||||
% Matlab handle class for OpenCV object classes
|
||||
%
|
||||
% This file was autogenerated, do not modify.
|
||||
% See LICENSE for full modification and redistribution details.
|
||||
% Copyright {{time.strftime("%Y", time.localtime())}} The OpenCV Foundation
|
||||
classdef {{clss.name}} < handle
|
||||
properties (SetAccess = private, Hidden = true)
|
||||
ptr_ = 0; % handle to the underlying c++ clss instance
|
||||
end
|
||||
|
||||
methods
|
||||
% constructor
|
||||
function this = {{clss.name}}(varargin)
|
||||
this.ptr_ = {{clss.name}}Bridge('new', varargin{:});
|
||||
end
|
||||
|
||||
% destructor
|
||||
function delete(this)
|
||||
{{clss.name}}Bridge(this.ptr_, 'delete');
|
||||
end
|
||||
|
||||
{% for function in clss.functions %}
|
||||
% {{function.__str__()}}
|
||||
function varargout = {{function.name}}(this, varargin)
|
||||
[varargout{1:nargout}] = {{clss.name}}Bridge('{{function.name}}', this.ptr_, varargin{:});
|
||||
end
|
||||
|
||||
{% endfor %}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
function mex(varargin)
|
||||
%CV.MEX compile MEX-function with OpenCV linkages
|
||||
%
|
||||
% Usage:
|
||||
% CV.MEX [options ...] file [file file ...]
|
||||
%
|
||||
% Description:
|
||||
% CV.MEX compiles one or more C/C++ source files into a shared-library
|
||||
% called a mex-file. This function is equivalent to the builtin MEX
|
||||
% routine, with the notable exception that it automatically resolves
|
||||
% OpenCV includes, and links in the OpenCV libraries where appropriate.
|
||||
% It also forwards the flags used to build OpenCV, so architecture-
|
||||
% specific optimizations can be used.
|
||||
%
|
||||
% CV.MEX is designed to be used in situations where the source(s) you
|
||||
% are compiling contain OpenCV definitions. In such cases, it streamlines
|
||||
% the finding and including of appropriate OpenCV libraries.
|
||||
%
|
||||
% See also: mex
|
||||
%
|
||||
% Copyright {{ time.strftime("%Y", time.localtime()) }} The OpenCV Foundation
|
||||
%
|
||||
|
||||
% forward the OpenCV build flags (C++ only)
|
||||
EXTRA_FLAGS = ['"CXXFLAGS="\$CXXFLAGS '...
|
||||
'{{ cv.flags | trim | wordwrap(60, false, '\'...\n \'') }}""'];
|
||||
|
||||
% add the OpenCV include dirs
|
||||
INCLUDE_DIRS = {{ cv.include_dirs | split | cellarray | wordwrap(60, false, '...\n ') }};
|
||||
|
||||
% add the lib dir (singular in both build tree and install tree)
|
||||
LIB_DIR = '{{ cv.lib_dir }}';
|
||||
|
||||
% add the OpenCV libs. Only the used libs will actually be linked
|
||||
LIBS = {{ cv.libs | split | cellarray | wordwrap(60, false, '...\n ') }};
|
||||
|
||||
% add the mex opts (usually at least -largeArrayDims)
|
||||
OPTS = {{ cv.opts | split | cellarray | wordwrap(60, false, '...\n ') }};
|
||||
|
||||
% merge all of the default options (EXTRA_FLAGS, LIBS, etc) and the options
|
||||
% and files passed by the user (varargin) into a single cell array
|
||||
merged = [ {EXTRA_FLAGS}, INCLUDE_DIRS, {LIB_DIR}, LIBS, OPTS, varargin ];
|
||||
|
||||
% expand the merged argument list into the builtin mex utility
|
||||
mex(merged{:});
|
||||
end
|
||||
@@ -0,0 +1,62 @@
|
||||
{% import 'functional.cpp' as functional %}
|
||||
{{ ('CV.' + fun.name | upper + ' ' + doc.brief | stripTags) | comment(75, '%') | matlabURL }}
|
||||
%
|
||||
% {{ functional.composeMatlab(fun) | upper }}
|
||||
{% if doc.long %}
|
||||
{{ doc.long | stripTags | qualify(fun.name) | comment(75, '% ') | matlabURL }}
|
||||
{% endif %}
|
||||
%
|
||||
{# ----------------------- Returns --------------------- #}
|
||||
{% if fun.rtp|void|not or fun.req|outputs|length or fun.opt|outputs|length %}
|
||||
% Returns:
|
||||
{% if fun.rtp|void|not %}
|
||||
% LVALUE
|
||||
{% endif %}
|
||||
{% for arg in fun.req|outputs + fun.opt|outputs %}
|
||||
{% set uname = arg.name | upper + ('_OUT' if arg.I else '') %}
|
||||
{% if arg.name in doc.params %}
|
||||
{{ (uname + ' ' + doc.params[arg.name]) | stripTags | comment(75, '% ') }}
|
||||
{% else %}
|
||||
{{ uname }}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
%
|
||||
{% endif %}
|
||||
{# ----------------- Required Inputs ------------------- #}
|
||||
{% if fun.req|inputs|length %}
|
||||
% Required Inputs:
|
||||
{% for arg in fun.req|inputs %}
|
||||
{% set uname = arg.name | upper + ('_IN' if arg.O else '') %}
|
||||
{% if arg.name in doc.params %}
|
||||
{{ (uname + ' ' + doc.params[arg.name]) | stripTags | comment(75, '% ') }}
|
||||
{% else %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
%
|
||||
{% endif %}
|
||||
{# ------------------ Optional Inputs ------------------- #}
|
||||
{% if fun.opt|inputs|length %}
|
||||
% Optional Inputs:
|
||||
{% for arg in fun.opt|inputs %}
|
||||
{% set uname = arg.name | upper + ('_IN' if arg.O else '') + ' (default: ' + arg.default + ')' %}
|
||||
{% if arg.name in doc.params %}
|
||||
{{ (uname + ' ' + doc.params[arg.name]) | stripTags | comment(75, '% ') }}
|
||||
{% else %}
|
||||
{{ uname }}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
%
|
||||
{% endif %}
|
||||
{# ---------------------- See also --------------------- #}
|
||||
{% if 'seealso' in doc %}
|
||||
% See also: {% for item in doc['seealso'] %}
|
||||
cv.{{ item }}{% if not loop.last %}, {% endif %}
|
||||
{% endfor %}
|
||||
|
||||
%
|
||||
{% endif %}
|
||||
{# ----------------------- Online ---------------------- #}
|
||||
{% set url = 'http://docs.opencv.org/modules/' + doc.module + '/doc/' + (doc.file|filename) + '.html#' + (fun.name|slugify) %}
|
||||
% Online docs: {{ url | matlabURL }}
|
||||
% Copyright {{ time.strftime("%Y", time.localtime()) }} The OpenCV Foundation
|
||||
%
|
||||
@@ -0,0 +1,59 @@
|
||||
{% import 'functional.cpp' as functional %}
|
||||
/*
|
||||
* file: {{fun.name}}.cpp
|
||||
* author: A trusty code generator
|
||||
*
|
||||
* This file was autogenerated, do not modify.
|
||||
* See LICENSE for full modification and redistribution details.
|
||||
* Copyright 2018 The OpenCV Foundation
|
||||
*/
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cassert>
|
||||
#include <exception>
|
||||
#include <opencv2/matlab/bridge.hpp>
|
||||
#include <opencv2/{{includes}}.hpp>
|
||||
using namespace cv;
|
||||
using namespace matlab;
|
||||
using namespace bridge;
|
||||
|
||||
/*
|
||||
* {{ fun.name }}
|
||||
* {{ fun }}
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray*{% if fun|noutputs %} plhs[]{% else %}*{% endif %},
|
||||
int nrhs, const mxArray*{% if fun|ninputs %} prhs[]{% else %}*{% endif %}) {
|
||||
|
||||
{% if fun|ninputs %}
|
||||
// parse the inputs
|
||||
ArgumentParser parser("{{fun.name}}");
|
||||
parser.{{ functional.composeVariant(fun) }};
|
||||
MxArrayVector sorted = parser.parse(MxArrayVector(prhs, prhs+nrhs));
|
||||
{% endif %}
|
||||
|
||||
{% if fun|ninputs or fun|noutputs %}
|
||||
// setup
|
||||
{% if fun|ninputs %}
|
||||
BridgeVector inputs(sorted.begin(), sorted.end());
|
||||
{% endif -%}
|
||||
{%- if fun|noutputs %}
|
||||
BridgeVector outputs({{fun|noutputs}});
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{{ functional.handleInputs(fun) }}
|
||||
{{ functional.composeWithExceptionHandler(fun) }}
|
||||
{{ functional.handleOutputs(fun) }}
|
||||
|
||||
{% if fun|noutputs %}
|
||||
// push the outputs back to matlab
|
||||
for (size_t n = 0; n < static_cast<size_t>(std::max(nlhs,1)); ++n) {
|
||||
plhs[n] = outputs[n].toMxArray().releaseOwnership();
|
||||
}
|
||||
{% endif %}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
% ------------------------------------------------------------------------
|
||||
% <strong>OpenCV Toolbox</strong>
|
||||
% Matlab bindings for the OpenCV library
|
||||
% ------------------------------------------------------------------------
|
||||
%
|
||||
% The OpenCV Toolbox allows you to make calls to native OpenCV methods
|
||||
% and classes directly from within Matlab.
|
||||
%
|
||||
% <strong>PATHS</strong>
|
||||
% To call OpenCV methods from anywhere in your workspace, add the
|
||||
% directory containing this file to the path:
|
||||
%
|
||||
% addpath(fileparts(which('cv')));
|
||||
%
|
||||
% The OpenCV Toolbox contains two important locations:
|
||||
% cv.m - This file, containing OpenCV enums
|
||||
% +cv/ - The directory containing the OpenCV methods and classes
|
||||
%
|
||||
% <strong>CALLING SYNTAX</strong>
|
||||
% To call an OpenCV method, class or enum, it must be prefixed with the
|
||||
% 'cv' qualifier. For example:
|
||||
%
|
||||
% % perform a Fourier transform
|
||||
% Xf = cv.dft(X, cv.DFT_COMPLEX_OUTPUT);
|
||||
%
|
||||
% % create a VideoCapture object, and open a file
|
||||
% camera = cv.VideoCapture();
|
||||
% camera.open('/path/to/file');
|
||||
%
|
||||
% You can specify optional arguments by name, similar to how python
|
||||
% and many builtin Matlab functions work. For example, the cv.dft
|
||||
% method used above has an optional 'nonzeroRows' argument. If
|
||||
% you want to specify that, but keep the default 'flags' behaviour,
|
||||
% simply call the method as:
|
||||
%
|
||||
% Xf = cv.dft(X, 'nonzeroRows', 7);
|
||||
%
|
||||
% <strong>HELP</strong>
|
||||
% Each method has its own help file containing information about the
|
||||
% arguments, return values, and what operation the method performs.
|
||||
% You can access this help information by typing:
|
||||
%
|
||||
% help cv.methodName
|
||||
%
|
||||
% The full list of methods can be found by inspecting the +cv/
|
||||
% directory. Note that the methods available to you will depend
|
||||
% on which modules you configured OpenCV to build.
|
||||
%
|
||||
% <strong>DIAGNOSTICS</strong>
|
||||
% If you are having problems with the OpenCV Toolbox and need to send a
|
||||
% bug report to the OpenCV team, you can get a printout of diagnostic
|
||||
% information to submit along with your report by typing:
|
||||
%
|
||||
% <a href="matlab: cv.buildInformation()">cv.buildInformation();</a>
|
||||
%
|
||||
% <strong>OTHER RESOURCES</strong>
|
||||
% OpenCV documentation online: <a href="matlab: web('http://docs.opencv.org', '-browser')">http://docs.opencv.org</a>
|
||||
% OpenCV issue tracker: <a href="matlab: web('http://code.opencv.org', '-browser')">http://code.opencv.org</a>
|
||||
% OpenCV Q&A: <a href="matlab: web('http://answers.opencv.org', '-browser')">http://answers.opencv.org</a>
|
||||
%
|
||||
% See also: cv.help, <a href="matlab: cv.buildInformation()">cv.buildInformation</a>
|
||||
%
|
||||
% Copyright {{ time.strftime("%Y", time.localtime()) }} The OpenCV Foundation
|
||||
%
|
||||
classdef cv
|
||||
properties (Constant = true)
|
||||
{% for key, val in constants.items() %}
|
||||
{{key}} = {{val|formatMatlabConstant(constants)}};
|
||||
{% endfor %}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,688 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this
|
||||
// license. If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of the copyright holders may not be used to endorse or promote
|
||||
// products derived from this software without specific prior written
|
||||
// permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is"
|
||||
// and any express or implied warranties, including, but not limited to, the
|
||||
// implied warranties of merchantability and fitness for a particular purpose
|
||||
// are disclaimed. In no event shall the Intel Corporation or contributors be
|
||||
// liable for any direct, indirect, incidental, special, exemplary, or
|
||||
// consequential damages (including, but not limited to, procurement of
|
||||
// substitute goods or services; loss of use, data, or profits; or business
|
||||
// interruption) however caused and on any theory of liability, whether in
|
||||
// contract, strict liability, or tort (including negligence or otherwise)
|
||||
// arising in any way out of the use of this software, even if advised of the
|
||||
// possibility of such damage.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
#ifndef OPENCV_BRIDGE_HPP_
|
||||
#define OPENCV_BRIDGE_HPP_
|
||||
|
||||
/** @defgroup matlab MATLAB Bridge
|
||||
*/
|
||||
|
||||
#include "mxarray.hpp"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/geometry.hpp>
|
||||
#include <opencv2/photo.hpp>
|
||||
#include <opencv2/stitching.hpp>
|
||||
#include <opencv2/video.hpp>
|
||||
#include <opencv2/optflow.hpp>
|
||||
#include <opencv2/xphoto.hpp>
|
||||
|
||||
/* This 'using' line was added in order to fix the following Error.
|
||||
* Failed to compile currentUIFramework:
|
||||
* modules/matlab/src/currentUIFramework.cpp:
|
||||
* In function void mexFunction(int, mxArray**, int, const mxArray**)
|
||||
* error: string was not declared in this scope
|
||||
* string retval; in line 41
|
||||
*
|
||||
* This error happens at the last stage of opencv build, when compiling the mex bindings
|
||||
* TODO: This is NOT the optimal fix, and needs to be addressed
|
||||
*/
|
||||
using std::string;
|
||||
|
||||
|
||||
namespace cv {
|
||||
namespace bridge {
|
||||
|
||||
//! @addtogroup matlab
|
||||
//! @{
|
||||
|
||||
/*
|
||||
* Custom typedefs
|
||||
* Parsed names from the hdr_parser
|
||||
*/
|
||||
typedef std::vector<cv::Mat> vector_Mat;
|
||||
typedef std::vector<cv::Point> vector_Point;
|
||||
typedef std::vector<int> vector_int;
|
||||
typedef std::vector<float> vector_float;
|
||||
typedef std::vector<cv::String> vector_String;
|
||||
typedef std::vector<unsigned char> vector_uchar;
|
||||
typedef std::vector<std::vector<char> > vector_vector_char;
|
||||
typedef std::vector<std::vector<cv::DMatch> > vector_vector_DMatch;
|
||||
typedef std::vector<cv::Rect> vector_Rect;
|
||||
typedef std::vector<cv::KeyPoint> vector_KeyPoint;
|
||||
typedef cv::Ptr<cv::StereoBM> Ptr_StereoBM;
|
||||
typedef cv::Ptr<cv::StereoSGBM> Ptr_StereoSGBM;
|
||||
typedef cv::Ptr<cv::FeatureDetector> Ptr_FeatureDetector;
|
||||
typedef cv::Ptr<CLAHE> Ptr_CLAHE;
|
||||
typedef cv::Ptr<LineSegmentDetector> Ptr_LineSegmentDetector;
|
||||
typedef cv::Ptr<AlignMTB> Ptr_AlignMTB;
|
||||
typedef cv::Ptr<CalibrateDebevec> Ptr_CalibrateDebevec;
|
||||
typedef cv::Ptr<CalibrateRobertson> Ptr_CalibrateRobertson;
|
||||
typedef cv::Ptr<DenseOpticalFlow> Ptr_DenseOpticalFlow;
|
||||
typedef cv::Ptr<cv::optflow::DualTVL1OpticalFlow> Ptr_DualTVL1OpticalFlow;
|
||||
typedef cv::Ptr<MergeDebevec> Ptr_MergeDebevec;
|
||||
typedef cv::Ptr<MergeMertens> Ptr_MergeMertens;
|
||||
typedef cv::Ptr<MergeRobertson> Ptr_MergeRobertson;
|
||||
typedef cv::Ptr<Stitcher> Ptr_Stitcher;
|
||||
typedef cv::Ptr<Tonemap> Ptr_Tonemap;
|
||||
typedef cv::Ptr<TonemapDrago> Ptr_TonemapDrago;
|
||||
typedef cv::Ptr<cv::xphoto::TonemapDurand> Ptr_TonemapDurand;
|
||||
typedef cv::Ptr<TonemapMantiuk> Ptr_TonemapMantiuk;
|
||||
typedef cv::Ptr<TonemapReinhard> Ptr_TonemapReinhard;
|
||||
typedef cv::Ptr<float> Ptr_float;
|
||||
typedef cv::Ptr<cv::GeneralizedHoughBallard> Ptr_GeneralizedHoughBallard;
|
||||
typedef cv::Ptr<cv::GeneralizedHoughGuil> Ptr_GeneralizedHoughGuil;
|
||||
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// PREDECLARATIONS
|
||||
// ----------------------------------------------------------------------------
|
||||
class Bridge;
|
||||
typedef std::vector<Bridge> BridgeVector;
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void deepCopyAndTranspose(const cv::Mat& src, matlab::MxArray& dst);
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void deepCopyAndTranspose(const matlab::MxArray& src, cv::Mat& dst);
|
||||
|
||||
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// BRIDGE
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/*!
|
||||
* @class Bridge
|
||||
* @brief Type conversion class for converting OpenCV and native C++ types
|
||||
*
|
||||
* Bridge provides an interface for converting between OpenCV/C++ types
|
||||
* to Matlab's mxArray format.
|
||||
*
|
||||
* Each type conversion requires three operators:
|
||||
* // conversion from ObjectType --> Bridge
|
||||
* Bridge& operator=(const ObjectType&);
|
||||
* // implicit conversion from Bridge --> ObjectType
|
||||
* operator ObjectType();
|
||||
* // explicit conversion from Bridge --> ObjectType
|
||||
* ObjectType toObjectType();
|
||||
*
|
||||
* The bridging class provides common conversions between OpenCV types,
|
||||
* std and stl types to Matlab's mxArray format. By inheriting Bridge,
|
||||
* you can add your own custom type conversions.
|
||||
*
|
||||
* Because Matlab uses a homogeneous storage type, all operations are provided
|
||||
* relative to Matlab's type. That is, Bridge always stores an matlab::MxArray object
|
||||
* and converts to and from other object types on demand.
|
||||
*
|
||||
* NOTE: for the explicit conversion function, the object name must be
|
||||
* in UpperCamelCase, for example:
|
||||
* int --> toInt
|
||||
* my_object --> MyObject
|
||||
* my_Object --> MyObject
|
||||
* myObject --> MyObject
|
||||
* this is because the binding generator standardises the calling syntax.
|
||||
*
|
||||
* Bridge attempts to make as few assumptions as possible, however in
|
||||
* some cases where 1-to-1 mappings don't exist, some assumptions are necessary.
|
||||
* In particular:
|
||||
* - conversion from of a 2-channel Mat to an mxArray will result in a complex
|
||||
* output
|
||||
* - conversion from multi-channel interleaved Mats will result in
|
||||
* multichannel planar mxArrays
|
||||
*
|
||||
*/
|
||||
class Bridge {
|
||||
private:
|
||||
matlab::MxArray ptr_;
|
||||
public:
|
||||
// bridges are default constructible
|
||||
Bridge() {}
|
||||
virtual ~Bridge() {}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Bridge Properties
|
||||
// --------------------------------------------------------------------------
|
||||
bool empty() const { return ptr_.empty(); }
|
||||
|
||||
/*! @brief unpack an object from Matlab into C++
|
||||
*
|
||||
* this function checks whether the given bridge is derived from an
|
||||
* object in Matlab. If so, it converts it to a (platform dependent)
|
||||
* pointer to the underlying C++ object.
|
||||
*
|
||||
* NOTE! This function assumes that the C++ pointer is stored in inst_
|
||||
*/
|
||||
template <typename Object>
|
||||
Object* getObjectByName(const std::string& name) {
|
||||
// check that the object is actually of correct type before unpacking
|
||||
// TODO: Traverse class hierarchy?
|
||||
if (!ptr_.isClass(name)) {
|
||||
matlab::error(std::string("Expected class ").append(std::string(name))
|
||||
.append(" but was given ").append(ptr_.className()));
|
||||
}
|
||||
// get the instance field
|
||||
matlab::MxArray inst = ptr_.field("inst_");
|
||||
Object* obj = NULL;
|
||||
// make sure the pointer is the correct size for the system
|
||||
if (sizeof(void *) == 8 && inst.ID() == mxUINT64_CLASS) {
|
||||
// 64-bit pointers
|
||||
// TODO: Do we REALLY REALLY need to reinterpret_cast?
|
||||
obj = reinterpret_cast<Object *>(inst.scalar<uint64_t>());
|
||||
} else if (sizeof(void *) == 4 && inst.ID() == mxUINT32_CLASS) {
|
||||
// 32-bit pointers
|
||||
obj = reinterpret_cast<Object *>(inst.scalar<uint32_t>());
|
||||
} else {
|
||||
matlab::error("Incorrect pointer type stored for architecture");
|
||||
}
|
||||
|
||||
// finally check if the object is NULL
|
||||
matlab::conditionalError(obj, std::string("Object ").append(std::string(name)).append(std::string(" is NULL")));
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// MATLAB TYPES
|
||||
// --------------------------------------------------------------------------
|
||||
Bridge& operator=(const mxArray* obj) { ptr_ = obj; return *this; }
|
||||
Bridge& operator=(const matlab::MxArray& obj) { ptr_ = obj; return *this; }
|
||||
Bridge(const matlab::MxArray& obj) : ptr_(obj) {}
|
||||
Bridge(const mxArray* obj) : ptr_(obj) {}
|
||||
matlab::MxArray toMxArray() { return ptr_; }
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// MATRIX CONVERSIONS
|
||||
// --------------------------------------------------------------------------
|
||||
Bridge& operator=(const cv::Mat& mat);
|
||||
cv::Mat toMat() const;
|
||||
operator cv::Mat() const { return toMat(); }
|
||||
|
||||
template <typename Scalar>
|
||||
static matlab::MxArray FromMat(const cv::Mat& mat) {
|
||||
matlab::MxArray arr(mat.rows, mat.cols, mat.channels(), matlab::Traits<Scalar>::ScalarType);
|
||||
switch (mat.depth()) {
|
||||
case CV_8U: deepCopyAndTranspose<uint8_t, Scalar>(mat, arr); break;
|
||||
case CV_8S: deepCopyAndTranspose<int8_t, Scalar>(mat, arr); break;
|
||||
case CV_16U: deepCopyAndTranspose<uint16_t, Scalar>(mat, arr); break;
|
||||
case CV_16S: deepCopyAndTranspose<int16_t, Scalar>(mat, arr); break;
|
||||
case CV_32S: deepCopyAndTranspose<int32_t, Scalar>(mat, arr); break;
|
||||
case CV_32F: deepCopyAndTranspose<float, Scalar>(mat, arr); break;
|
||||
case CV_64F: deepCopyAndTranspose<double, Scalar>(mat, arr); break;
|
||||
default: matlab::error("Attempted to convert from unknown class");
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
template <typename Scalar>
|
||||
cv::Mat toMat() const {
|
||||
cv::Mat mat(ptr_.rows(), ptr_.cols(), CV_MAKETYPE(cv::DataType<Scalar>::type, ptr_.channels()));
|
||||
switch (ptr_.ID()) {
|
||||
case mxINT8_CLASS: deepCopyAndTranspose<int8_t, Scalar>(ptr_, mat); break;
|
||||
case mxUINT8_CLASS: deepCopyAndTranspose<uint8_t, Scalar>(ptr_, mat); break;
|
||||
case mxINT16_CLASS: deepCopyAndTranspose<int16_t, Scalar>(ptr_, mat); break;
|
||||
case mxUINT16_CLASS: deepCopyAndTranspose<uint16_t, Scalar>(ptr_, mat); break;
|
||||
case mxINT32_CLASS: deepCopyAndTranspose<int32_t, Scalar>(ptr_, mat); break;
|
||||
case mxUINT32_CLASS: deepCopyAndTranspose<uint32_t, Scalar>(ptr_, mat); break;
|
||||
//case mxINT64_CLASS: deepCopyAndTranspose<int64_t, Scalar>(ptr_, mat); break;
|
||||
//case mxUINT64_CLASS: deepCopyAndTranspose<uint64_t, Scalar>(ptr_, mat); break;
|
||||
case mxSINGLE_CLASS: deepCopyAndTranspose<float, Scalar>(ptr_, mat); break;
|
||||
case mxDOUBLE_CLASS: deepCopyAndTranspose<double, Scalar>(ptr_, mat); break;
|
||||
case mxCHAR_CLASS: deepCopyAndTranspose<char, Scalar>(ptr_, mat); break;
|
||||
case mxLOGICAL_CLASS: deepCopyAndTranspose<int8_t, Scalar>(ptr_, mat); break;
|
||||
default: matlab::error("Attempted to convert from unknown/unsupported class");
|
||||
}
|
||||
return mat;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// INTEGRAL TYPES
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
// --------------------------- string --------------------------------------
|
||||
Bridge& operator=(const std::string& ) { return *this; }
|
||||
std::string toString() {
|
||||
return ptr_.toString();
|
||||
}
|
||||
operator std::string() { return toString(); }
|
||||
|
||||
// --------------------------- bool --------------------------------------
|
||||
Bridge& operator=(const bool& ) { return *this; }
|
||||
bool toBool() { return 0; }
|
||||
operator bool() { return toBool(); }
|
||||
|
||||
// --------------------------- double --------------------------------------
|
||||
Bridge& operator=(const double& ) { return *this; }
|
||||
double toDouble() { return ptr_.scalar<double>(); }
|
||||
operator double() { return toDouble(); }
|
||||
|
||||
// --------------------------- float ---------------------------------------
|
||||
Bridge& operator=(const float& ) { return *this; }
|
||||
float toFloat() { return ptr_.scalar<float>(); }
|
||||
operator float() { return toFloat(); }
|
||||
|
||||
// --------------------------- int --------------------------------------
|
||||
Bridge& operator=(const int& ) { return *this; }
|
||||
int toInt() { return ptr_.scalar<int>(); }
|
||||
operator int() { return toInt(); }
|
||||
|
||||
// --------------------------- size_t -----------------------------------------
|
||||
Bridge& operator=(const size_t&) { return *this; }
|
||||
size_t toSizeT() { return ptr_.scalar<size_t>(); }
|
||||
operator size_t() { return toSizeT(); }
|
||||
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// CORE OPENCV TYPES
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
// -------------------------- Point --------------------------------------
|
||||
Bridge& operator=(const cv::Point& ) { return *this; }
|
||||
cv::Point toPoint() const { return cv::Point(); }
|
||||
operator cv::Point() const { return toPoint(); }
|
||||
|
||||
// -------------------------- Point2f ------------------------------------
|
||||
Bridge& operator=(const cv::Point2f& ) { return *this; }
|
||||
cv::Point2f toPoint2f() const { return cv::Point2f(); }
|
||||
operator cv::Point2f() const { return toPoint2f(); }
|
||||
|
||||
// -------------------------- Point2d ------------------------------------
|
||||
Bridge& operator=(const cv::Point2d& ) { return *this; }
|
||||
cv::Point2d toPoint2d() const { return cv::Point2d(); }
|
||||
operator cv::Point2d() const { return toPoint2d(); }
|
||||
|
||||
// -------------------------- Size ---------------------------------------
|
||||
Bridge& operator=(const cv::Size& ) { return *this; }
|
||||
cv::Size toSize() const { return cv::Size(); }
|
||||
operator cv::Size() const { return toSize(); }
|
||||
|
||||
// -------------------------- Moments --------------------------------------
|
||||
Bridge& operator=(const cv::Moments& ) { return *this; }
|
||||
cv::Moments toMoments() const { return cv::Moments(); }
|
||||
operator cv::Moments() const { return toMoments(); }
|
||||
|
||||
// -------------------------- Scalar --------------------------------------
|
||||
Bridge& operator=(const cv::Scalar& ) { return *this; }
|
||||
cv::Scalar toScalar() { return cv::Scalar(); }
|
||||
operator cv::Scalar() { return toScalar(); }
|
||||
|
||||
// -------------------------- Rect -----------------------------------------
|
||||
Bridge& operator=(const cv::Rect& ) { return *this; }
|
||||
cv::Rect toRect() { return cv::Rect(); }
|
||||
operator cv::Rect() { return toRect(); }
|
||||
|
||||
// ---------------------- RotatedRect ---------------------------------------
|
||||
Bridge& operator=(const cv::RotatedRect& ) { return *this; }
|
||||
cv::RotatedRect toRotatedRect() { return cv::RotatedRect(); }
|
||||
operator cv::RotatedRect() { return toRotatedRect(); }
|
||||
|
||||
// ---------------------- TermCriteria --------------------------------------
|
||||
Bridge& operator=(const cv::TermCriteria& ) { return *this; }
|
||||
cv::TermCriteria toTermCriteria() { return cv::TermCriteria(); }
|
||||
operator cv::TermCriteria() { return toTermCriteria(); }
|
||||
|
||||
// ---------------------- RNG --------------------------------------
|
||||
Bridge& operator=(const cv::RNG& ) { return *this; }
|
||||
/*! @brief explicit conversion to cv::RNG()
|
||||
*
|
||||
* Converts a bridge object to a cv::RNG(). We explicitly assert that
|
||||
* the object is an RNG in matlab space before attempting to deference
|
||||
* its pointer
|
||||
*/
|
||||
cv::RNG toRNG() {
|
||||
return (*getObjectByName<cv::RNG>("RNG"));
|
||||
}
|
||||
operator cv::RNG() { return toRNG(); }
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OPENCV VECTOR TYPES
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
// -------------------- vector_Mat ------------------------------------------
|
||||
Bridge& operator=(const vector_Mat& ) { return *this; }
|
||||
vector_Mat toVectorMat() { return vector_Mat(); }
|
||||
operator vector_Mat() { return toVectorMat(); }
|
||||
|
||||
// --------------------------- vector_int ----------------------------------
|
||||
Bridge& operator=(const vector_int& ) { return *this; }
|
||||
vector_int toVectorInt() { return vector_int(); }
|
||||
operator vector_int() { return toVectorInt(); }
|
||||
|
||||
// --------------------------- vector_float --------------------------------
|
||||
Bridge& operator=(const vector_float& ) { return *this; }
|
||||
vector_float toVectorFloat() { return vector_float(); }
|
||||
operator vector_float() { return toVectorFloat(); }
|
||||
|
||||
// --------------------------- vector_Rect ---------------------------------
|
||||
Bridge& operator=(const vector_Rect& ) { return *this; }
|
||||
vector_Rect toVectorRect() { return vector_Rect(); }
|
||||
operator vector_Rect() { return toVectorRect(); }
|
||||
|
||||
// --------------------------- vector_KeyPoint -----------------------------
|
||||
Bridge& operator=(const vector_KeyPoint& ) { return *this; }
|
||||
vector_KeyPoint toVectorKeyPoint() { return vector_KeyPoint(); }
|
||||
operator vector_KeyPoint() { return toVectorKeyPoint(); }
|
||||
|
||||
// --------------------------- vector_String -------------------------------
|
||||
Bridge& operator=(const vector_String& ) { return *this; }
|
||||
vector_String toVectorString() { return vector_String(); }
|
||||
operator vector_String() { return toVectorString(); }
|
||||
|
||||
// ------------------------ vector_Point ------------------------------------
|
||||
Bridge& operator=(const vector_Point& ) { return *this; }
|
||||
vector_Point toVectorPoint() { return vector_Point(); }
|
||||
operator vector_Point() { return toVectorPoint(); }
|
||||
|
||||
// ------------------------ vector_uchar ------------------------------------
|
||||
Bridge& operator=(const vector_uchar& ) { return *this; }
|
||||
vector_uchar toVectorUchar() { return vector_uchar(); }
|
||||
operator vector_uchar() { return toVectorUchar(); }
|
||||
|
||||
// ------------------------ vector_vector_char ------------------------------
|
||||
Bridge& operator=(const vector_vector_char& ) { return *this; }
|
||||
vector_vector_char toVectorVectorChar() { return vector_vector_char(); }
|
||||
operator vector_vector_char() { return toVectorVectorChar(); }
|
||||
|
||||
// ------------------------ vector_vector_DMatch ---------------------------
|
||||
Bridge& operator=(const vector_vector_DMatch& ) { return *this; }
|
||||
vector_vector_DMatch toVectorVectorDMatch() { return vector_vector_DMatch(); }
|
||||
operator vector_vector_DMatch() { return toVectorVectorDMatch(); }
|
||||
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OPENCV COMPOUND TYPES
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
// --------------------------- Ptr_StereoBM -----------------------------
|
||||
Bridge& operator=(const Ptr_StereoBM& ) { return *this; }
|
||||
Ptr_StereoBM toPtrStereoBM() { return Ptr_StereoBM(); }
|
||||
operator Ptr_StereoBM() { return toPtrStereoBM(); }
|
||||
|
||||
// --------------------------- Ptr_StereoSGBM ---------------------------
|
||||
Bridge& operator=(const Ptr_StereoSGBM& ) { return *this; }
|
||||
Ptr_StereoSGBM toPtrStereoSGBM() { return Ptr_StereoSGBM(); }
|
||||
operator Ptr_StereoSGBM() { return toPtrStereoSGBM(); }
|
||||
|
||||
// --------------------------- Ptr_FeatureDetector ----------------------
|
||||
Bridge& operator=(const Ptr_FeatureDetector& ) { return *this; }
|
||||
Ptr_FeatureDetector toPtrFeatureDetector() { return Ptr_FeatureDetector(); }
|
||||
operator Ptr_FeatureDetector() { return toPtrFeatureDetector(); }
|
||||
|
||||
// --------------------------- Ptr_CLAHE --------------------------------
|
||||
Bridge& operator=(const Ptr_CLAHE& ) { return *this; }
|
||||
Ptr_CLAHE toPtrCLAHE() { return Ptr_CLAHE(); }
|
||||
operator Ptr_CLAHE() { return toPtrCLAHE(); }
|
||||
|
||||
// --------------------------- Ptr_LineSegmentDetector ------------------
|
||||
Bridge& operator=(const Ptr_LineSegmentDetector& ) { return *this; }
|
||||
Ptr_LineSegmentDetector toPtrLineSegmentDetector() { return Ptr_LineSegmentDetector(); }
|
||||
operator Ptr_LineSegmentDetector() { return toPtrLineSegmentDetector(); }
|
||||
|
||||
// --------------------------- Ptr_AlignMTB -----------------------------
|
||||
Bridge& operator=(const Ptr_AlignMTB& ) { return *this; }
|
||||
Ptr_AlignMTB toPtrAlignMTB() { return Ptr_AlignMTB(); }
|
||||
operator Ptr_AlignMTB() { return toPtrAlignMTB(); }
|
||||
|
||||
// --------------------------- Ptr_CalibrateDebevec -------------------
|
||||
Bridge& operator=(const Ptr_CalibrateDebevec& ) { return *this; }
|
||||
Ptr_CalibrateDebevec toPtrCalibrateDebevec() { return Ptr_CalibrateDebevec(); }
|
||||
operator Ptr_CalibrateDebevec() { return toPtrCalibrateDebevec(); }
|
||||
|
||||
// --------------------------- Ptr_CalibrateRobertson -------------------
|
||||
Bridge& operator=(const Ptr_CalibrateRobertson& ) { return *this; }
|
||||
Ptr_CalibrateRobertson toPtrCalibrateRobertson() { return Ptr_CalibrateRobertson(); }
|
||||
operator Ptr_CalibrateRobertson() { return toPtrCalibrateRobertson(); }
|
||||
|
||||
// --------------------------- Ptr_DenseOpticalFlow -------------------
|
||||
Bridge& operator=(const Ptr_DenseOpticalFlow& ) { return *this; }
|
||||
Ptr_DenseOpticalFlow toPtrDenseOpticalFlow() { return Ptr_DenseOpticalFlow(); }
|
||||
operator Ptr_DenseOpticalFlow() { return toPtrDenseOpticalFlow(); }
|
||||
|
||||
// --------------------------- Ptr_DualTVL1OpticalFlow -------------------
|
||||
Bridge& operator=(const Ptr_DualTVL1OpticalFlow& ) { return *this; }
|
||||
Ptr_DualTVL1OpticalFlow toPtrDualTVL1OpticalFlow() { return Ptr_DualTVL1OpticalFlow(); }
|
||||
operator Ptr_DualTVL1OpticalFlow() { return toPtrDualTVL1OpticalFlow(); }
|
||||
|
||||
// --------------------------- Ptr_MergeDebevec -----------------------
|
||||
Bridge& operator=(const Ptr_MergeDebevec& ) { return *this; }
|
||||
Ptr_MergeDebevec toPtrMergeDebevec() { return Ptr_MergeDebevec(); }
|
||||
operator Ptr_MergeDebevec() { return toPtrMergeDebevec(); }
|
||||
|
||||
// --------------------------- Ptr_MergeMertens -----------------------
|
||||
Bridge& operator=(const Ptr_MergeMertens& ) { return *this; }
|
||||
Ptr_MergeMertens toPtrMergeMertens() { return Ptr_MergeMertens(); }
|
||||
operator Ptr_MergeMertens() { return toPtrMergeMertens(); }
|
||||
|
||||
// --------------------------- Ptr_MergeRobertson -----------------------
|
||||
Bridge& operator=(const Ptr_MergeRobertson& ) { return *this; }
|
||||
Ptr_MergeRobertson toPtrMergeRobertson() { return Ptr_MergeRobertson(); }
|
||||
operator Ptr_MergeRobertson() { return toPtrMergeRobertson(); }
|
||||
|
||||
// --------------------------- Ptr_Stitcher ------------------------------
|
||||
Bridge& operator=(const Ptr_Stitcher& ) { return *this; }
|
||||
Ptr_Stitcher toPtrStitcher() { return Ptr_Stitcher(); }
|
||||
operator Ptr_Stitcher() { return toPtrStitcher(); }
|
||||
|
||||
// --------------------------- Ptr_Tonemap ------------------------------
|
||||
Bridge& operator=(const Ptr_Tonemap& ) { return *this; }
|
||||
Ptr_Tonemap toPtrTonemap() { return Ptr_Tonemap(); }
|
||||
operator Ptr_Tonemap() { return toPtrTonemap(); }
|
||||
|
||||
// --------------------------- Ptr_TonemapDrago -------------------------
|
||||
Bridge& operator=(const Ptr_TonemapDrago& ) { return *this; }
|
||||
Ptr_TonemapDrago toPtrTonemapDrago() { return Ptr_TonemapDrago(); }
|
||||
operator Ptr_TonemapDrago() { return toPtrTonemapDrago(); }
|
||||
|
||||
// --------------------------- Ptr_TonemapDurand ------------------------
|
||||
Bridge& operator=(const Ptr_TonemapDurand& ) { return *this; }
|
||||
Ptr_TonemapDurand toPtrTonemapDurand() { return Ptr_TonemapDurand(); }
|
||||
operator Ptr_TonemapDurand() { return toPtrTonemapDurand(); }
|
||||
|
||||
// --------------------------- Ptr_TonemapMantiuk -----------------------
|
||||
Bridge& operator=(const Ptr_TonemapMantiuk& ) { return *this; }
|
||||
Ptr_TonemapMantiuk toPtrTonemapMantiuk() { return Ptr_TonemapMantiuk(); }
|
||||
operator Ptr_TonemapMantiuk() { return toPtrTonemapMantiuk(); }
|
||||
|
||||
// --------------------------- Ptr_TonemapReinhard ----------------------
|
||||
Bridge& operator=(const Ptr_TonemapReinhard& ) { return *this; }
|
||||
Ptr_TonemapReinhard toPtrTonemapReinhard() { return Ptr_TonemapReinhard(); }
|
||||
operator Ptr_TonemapReinhard() { return toPtrTonemapReinhard(); }
|
||||
|
||||
// --------------------------- Ptr_float ----------------------
|
||||
Bridge& operator=(const Ptr_float& ) { return *this; }
|
||||
Ptr_float toPtrFloat() { return Ptr_float(); }
|
||||
operator Ptr_float() { return toPtrFloat(); }
|
||||
|
||||
// --------------------------- Ptr_GeneralizedHoughBallard --------------
|
||||
Bridge& operator=(const Ptr_GeneralizedHoughBallard& obj) { return *this; }
|
||||
operator Ptr_GeneralizedHoughBallard() { return Ptr_GeneralizedHoughBallard(); }
|
||||
|
||||
// --------------------------- Ptr_GeneralizedHoughGuil ----------------------
|
||||
Bridge& operator=(const Ptr_GeneralizedHoughGuil& obj) { return *this; }
|
||||
operator Ptr_GeneralizedHoughGuil() { return Ptr_GeneralizedHoughGuil(); }
|
||||
|
||||
}; // class Bridge
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// SPECIALIZATIONS
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
/*!
|
||||
* @brief template specialization for inheriting types
|
||||
*
|
||||
* This template specialization attempts to preserve the best mapping
|
||||
* between OpenCV and Matlab types. Matlab uses double types almost universally, so
|
||||
* all floating float types are converted to doubles.
|
||||
* Unfortunately OpenCV does not have a native logical type, so
|
||||
* that gets mapped to an unsigned 8-bit value
|
||||
*/
|
||||
template <>
|
||||
matlab::MxArray Bridge::FromMat<matlab::InheritType>(const cv::Mat& mat) {
|
||||
switch (mat.depth()) {
|
||||
case CV_8U: return FromMat<uint8_t>(mat);
|
||||
case CV_8S: return FromMat<int8_t>(mat);
|
||||
case CV_16U: return FromMat<uint16_t>(mat);
|
||||
case CV_16S: return FromMat<int16_t>(mat);
|
||||
case CV_32S: return FromMat<int32_t>(mat);
|
||||
case CV_32F: return FromMat<double>(mat); //NOTE: Matlab uses double as native type!
|
||||
case CV_64F: return FromMat<double>(mat);
|
||||
default: matlab::error("Attempted to convert from unknown class");
|
||||
}
|
||||
return matlab::MxArray();
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief template specialization for inheriting types
|
||||
*
|
||||
* This template specialization attempts to preserve the best mapping
|
||||
* between Matlab and OpenCV types. OpenCV has poor support for double precision
|
||||
* types, so all floating point types are cast to float. Logicals get cast
|
||||
* to unsignd 8-bit value.
|
||||
*/
|
||||
template <>
|
||||
cv::Mat Bridge::toMat<matlab::InheritType>() const {
|
||||
switch (ptr_.ID()) {
|
||||
case mxINT8_CLASS: return toMat<int8_t>();
|
||||
case mxUINT8_CLASS: return toMat<uint8_t>();
|
||||
case mxINT16_CLASS: return toMat<int16_t>();
|
||||
case mxUINT16_CLASS: return toMat<uint16_t>();
|
||||
case mxINT32_CLASS: return toMat<int32_t>();
|
||||
case mxUINT32_CLASS: return toMat<int32_t>();
|
||||
//case mxINT64_CLASS: return toMat<int64_t>();
|
||||
//case mxUINT64_CLASS: return toMat<int64_t>();
|
||||
case mxSINGLE_CLASS: return toMat<float>();
|
||||
case mxDOUBLE_CLASS: return toMat<float>(); //NOTE: OpenCV uses float as native type!
|
||||
case mxCHAR_CLASS: return toMat<int8_t>();
|
||||
case mxLOGICAL_CLASS: return toMat<int8_t>();
|
||||
default: matlab::error("Attempted to convert from unknown/unsuported class");
|
||||
}
|
||||
return cv::Mat();
|
||||
}
|
||||
|
||||
Bridge& Bridge::operator=(const cv::Mat& mat) { ptr_ = FromMat<matlab::InheritType>(mat); return *this; }
|
||||
cv::Mat Bridge::toMat() const { return toMat<matlab::InheritType>(); }
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// MATRIX TRANSPOSE
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void deepCopyAndTranspose(const cv::Mat& in, matlab::MxArray& out) {
|
||||
const int cols = out.cols();
|
||||
const int rows = out.rows();
|
||||
matlab::conditionalError(static_cast<size_t>(in.rows) == out.rows(), "Matrices must have the same number of rows");
|
||||
matlab::conditionalError(static_cast<size_t>(in.cols) == out.cols(), "Matrices must have the same number of cols");
|
||||
matlab::conditionalError(static_cast<size_t>(in.channels()) == out.channels(), "Matrices must have the same number of channels");
|
||||
std::vector<cv::Mat> channels;
|
||||
cv::split(in, channels);
|
||||
for (size_t c = 0; c < out.channels(); ++c) {
|
||||
cv::Mat_<InputScalar> m;
|
||||
cv::transpose(channels[c], m);
|
||||
OutputScalar* dst_plane = (OutputScalar*)out.real<InputScalar>() + cols*rows*c;
|
||||
for (int x = 0; x < cols; x++)
|
||||
{
|
||||
OutputScalar* dst_col = dst_plane + x * rows;
|
||||
for (int y = 0; y < rows; y++)
|
||||
{
|
||||
dst_col[y] = cv::saturate_cast<OutputScalar>(m(y, x));
|
||||
}
|
||||
}
|
||||
}
|
||||
//const InputScalar* inp = in.ptr<InputScalar>(0);
|
||||
//OutputScalar* outp = out.real<OutputScalar>();
|
||||
//gemt('R', out.rows(), out.cols(), inp, in.step1(), outp, out.rows());
|
||||
}
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void deepCopyAndTranspose(const matlab::MxArray& in, cv::Mat& out) {
|
||||
const int cols = in.cols();
|
||||
const int rows = in.rows();
|
||||
matlab::conditionalError(in.rows() == static_cast<size_t>(out.rows), "Matrices must have the same number of rows");
|
||||
matlab::conditionalError(in.cols() == static_cast<size_t>(out.cols), "Matrices must have the same number of cols");
|
||||
matlab::conditionalError(in.channels() == static_cast<size_t>(out.channels()), "Matrices must have the same number of channels");
|
||||
std::vector<cv::Mat> channels;
|
||||
for (size_t c = 0; c < in.channels(); ++c) {
|
||||
cv::Mat_<OutputScalar> m(cols, rows);
|
||||
const InputScalar* src_plane = in.real<InputScalar>() + cols*rows*c;
|
||||
for (int x = 0; x < cols; x++)
|
||||
{
|
||||
const InputScalar* src_col = src_plane + x * rows;
|
||||
for (int y = 0; y < rows; y++)
|
||||
{
|
||||
m(y, x) = cv::saturate_cast<InputScalar>(src_col[y]);
|
||||
}
|
||||
}
|
||||
cv::transpose(m, m);
|
||||
channels.push_back(m);
|
||||
}
|
||||
cv::merge(channels, out);
|
||||
|
||||
//const InputScalar* inp = in.real<InputScalar>();
|
||||
//OutputScalar* outp = out.ptr<OutputScalar>(0);
|
||||
//gemt('C', in.rows(), in.cols(), inp, in.rows(), outp, out.step1());
|
||||
}
|
||||
|
||||
//! @}
|
||||
|
||||
} // namespace bridge
|
||||
} // namespace cv
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,99 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this
|
||||
// license. If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of the copyright holders may not be used to endorse or promote
|
||||
// products derived from this software without specific prior written
|
||||
// permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is"
|
||||
// and any express or implied warranties, including, but not limited to, the
|
||||
// implied warranties of merchantability and fitness for a particular purpose
|
||||
// are disclaimed. In no event shall the Intel Corporation or contributors be
|
||||
// liable for any direct, indirect, incidental, special, exemplary, or
|
||||
// consequential damages (including, but not limited to, procurement of
|
||||
// substitute goods or services; loss of use, data, or profits; or business
|
||||
// interruption) however caused and on any theory of liability, whether in
|
||||
// contract, strict liability, or tort (including negligence or otherwise)
|
||||
// arising in any way out of the use of this software, even if advised of the
|
||||
// possibility of such damage.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
#ifndef OPENCV_MAP_HPP_
|
||||
#define OPENCV_MAP_HPP_
|
||||
|
||||
namespace matlab {
|
||||
#if __cplusplus >= 201103L
|
||||
|
||||
// If we have C++11 support, we just want to use unordered_map
|
||||
#include <unordered_map>
|
||||
template <typename KeyType, typename ValueType>
|
||||
using Map = std::unordered_map<KeyType, ValueType>;
|
||||
|
||||
#else
|
||||
|
||||
//! @addtogroup matlab
|
||||
//! @{
|
||||
|
||||
// If we don't have C++11 support, we wrap another map implementation
|
||||
// in the same public API as unordered_map
|
||||
|
||||
//! @cond IGNORED
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
//! @endcond
|
||||
|
||||
template <typename KeyType, typename ValueType>
|
||||
class Map {
|
||||
private:
|
||||
std::map<KeyType, ValueType> map_;
|
||||
public:
|
||||
// map[key] = val;
|
||||
ValueType& operator[] (const KeyType& k) {
|
||||
return map_[k];
|
||||
}
|
||||
|
||||
// map.at(key) = val (throws)
|
||||
ValueType& at(const KeyType& k) {
|
||||
typename std::map<KeyType, ValueType>::iterator it;
|
||||
it = map_.find(k);
|
||||
if (it == map_.end()) throw std::out_of_range("Key not found");
|
||||
return *it;
|
||||
}
|
||||
|
||||
// val = map.at(key) (throws, const)
|
||||
const ValueType& at(const KeyType& k) const {
|
||||
typename std::map<KeyType, ValueType>::const_iterator it;
|
||||
it = map_.find(k);
|
||||
if (it == map_.end()) throw std::out_of_range("Key not found");
|
||||
return *it;
|
||||
}
|
||||
};
|
||||
|
||||
//! @}
|
||||
|
||||
} // namespace matlab
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,690 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this
|
||||
// license. If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of the copyright holders may not be used to endorse or promote
|
||||
// products derived from this software without specific prior written
|
||||
// permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is"
|
||||
// and any express or implied warranties, including, but not limited to, the
|
||||
// implied warranties of merchantability and fitness for a particular purpose
|
||||
// are disclaimed. In no event shall the Intel Corporation or contributors be
|
||||
// liable for any direct, indirect, incidental, special, exemplary, or
|
||||
// consequential damages (including, but not limited to, procurement of
|
||||
// substitute goods or services; loss of use, data, or profits; or business
|
||||
// interruption) however caused and on any theory of liability, whether in
|
||||
// contract, strict liability, or tort (including negligence or otherwise)
|
||||
// arising in any way out of the use of this software, even if advised of the
|
||||
// possibility of such damage.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
#ifndef OPENCV_MXARRAY_HPP_
|
||||
#define OPENCV_MXARRAY_HPP_
|
||||
|
||||
#include <mex.h>
|
||||
#include <stdint.h>
|
||||
#include <cstdarg>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sstream>
|
||||
#if __cplusplus > 201103
|
||||
#include <unordered_set>
|
||||
typedef std::unordered_set<std::string> StringSet;
|
||||
#else
|
||||
#include <set>
|
||||
typedef std::set<std::string> StringSet;
|
||||
#endif
|
||||
|
||||
/*
|
||||
* All recent versions of Matlab ship with the MKL library which contains
|
||||
* a blas extension called mkl_?omatcopy(). This defines an out-of-place
|
||||
* copy and transpose operation.
|
||||
*
|
||||
* The mkl library is in ${MATLAB_ROOT}/bin/${MATLAB_MEXEXT}/libmkl...
|
||||
* Matlab does not ship headers for the mkl functions, so we define them
|
||||
* here.
|
||||
*
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace matlab {
|
||||
|
||||
//! @addtogroup matlab
|
||||
//! @{
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// PREDECLARATIONS
|
||||
// ----------------------------------------------------------------------------
|
||||
class MxArray;
|
||||
typedef std::vector<MxArray> MxArrayVector;
|
||||
|
||||
/*!
|
||||
* @brief raise error if condition fails
|
||||
*
|
||||
* This is a conditional wrapper for mexErrMsgTxt. If the conditional
|
||||
* expression fails, an error is raised and the mex function returns
|
||||
* to Matlab, otherwise this function does nothing
|
||||
*/
|
||||
static void conditionalError(bool expr, const std::string& str) {
|
||||
if (!expr) mexErrMsgTxt(std::string("condition failed: ").append(str).c_str());
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief raise an error
|
||||
*
|
||||
* This function is a wrapper around mexErrMsgTxt
|
||||
*/
|
||||
static void error(const std::string& str) {
|
||||
mexErrMsgTxt(str.c_str());
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// MATLAB TRAITS
|
||||
// ----------------------------------------------------------------------------
|
||||
class DefaultTraits {};
|
||||
class InheritType {};
|
||||
|
||||
template<typename _Tp = DefaultTraits> class Traits {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxUNKNOWN_CLASS;
|
||||
static const mxComplexity Complex = mxCOMPLEX;
|
||||
static const mxComplexity Real = mxREAL;
|
||||
static std::string ToString() { return "Unknown/Unsupported"; }
|
||||
};
|
||||
// bool
|
||||
template<> class Traits<bool> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxLOGICAL_CLASS;
|
||||
static std::string ToString() { return "boolean"; }
|
||||
};
|
||||
// uint8_t
|
||||
template<> class Traits<uint8_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxUINT8_CLASS;
|
||||
static std::string ToString() { return "uint8_t"; }
|
||||
};
|
||||
// int8_t
|
||||
template<> class Traits<int8_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxINT8_CLASS;
|
||||
static std::string ToString() { return "int8_t"; }
|
||||
};
|
||||
// uint16_t
|
||||
template<> class Traits<uint16_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxUINT16_CLASS;
|
||||
static std::string ToString() { return "uint16_t"; }
|
||||
};
|
||||
// int16_t
|
||||
template<> class Traits<int16_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxINT16_CLASS;
|
||||
static std::string ToString() { return "int16_t"; }
|
||||
};
|
||||
// uint32_t
|
||||
template<> class Traits<uint32_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxUINT32_CLASS;
|
||||
static std::string ToString() { return "uint32_t"; }
|
||||
};
|
||||
// int32_t
|
||||
template<> class Traits<int32_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxINT32_CLASS;
|
||||
static std::string ToString() { return "int32_t"; }
|
||||
};
|
||||
// uint64_t
|
||||
template<> class Traits<uint64_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxUINT64_CLASS;
|
||||
static std::string ToString() { return "uint64_t"; }
|
||||
};
|
||||
// int64_t
|
||||
template<> class Traits<int64_t> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxINT64_CLASS;
|
||||
static std::string ToString() { return "int64_t"; }
|
||||
};
|
||||
// float
|
||||
template<> class Traits<float> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxSINGLE_CLASS;
|
||||
static std::string ToString() { return "float"; }
|
||||
};
|
||||
// double
|
||||
template<> class Traits<double> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxDOUBLE_CLASS;
|
||||
static std::string ToString() { return "double"; }
|
||||
};
|
||||
// char
|
||||
template<> class Traits<char> {
|
||||
public:
|
||||
static const mxClassID ScalarType = mxCHAR_CLASS;
|
||||
static std::string ToString() { return "char"; }
|
||||
};
|
||||
// inherited type
|
||||
template<> class Traits<matlab::InheritType> {
|
||||
public:
|
||||
static std::string ToString() { return "Inherited type"; }
|
||||
};
|
||||
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// MXARRAY
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/*!
|
||||
* @class MxArray
|
||||
* @brief A thin wrapper around Matlab's mxArray types
|
||||
*
|
||||
* MxArray provides a thin object oriented wrapper around Matlab's
|
||||
* native mxArray type which exposes most of the functionality of the
|
||||
* Matlab interface, but in a more C++ manner. MxArray objects are scoped,
|
||||
* so you can freely create and destroy them without worrying about memory
|
||||
* management. If you wish to pass the underlying mxArray* representation
|
||||
* back to Matlab as an lvalue, see the releaseOwnership() method
|
||||
*
|
||||
* MxArrays can be directly converted into OpenCV mat objects and std::string
|
||||
* objects, since there is a natural mapping between these types. More
|
||||
* complex types are mapped through the Bridge which does custom conversions
|
||||
* such as MxArray --> cv::Keypoints, etc
|
||||
*/
|
||||
class MxArray {
|
||||
private:
|
||||
mxArray* ptr_;
|
||||
bool owns_;
|
||||
|
||||
/*!
|
||||
* @brief swap all members of this and other
|
||||
*
|
||||
* the swap method is used by the assignment and move constructors
|
||||
* to swap the members of two MxArrays, leaving both in destructible states
|
||||
*/
|
||||
friend void swap(MxArray& first, MxArray& second) {
|
||||
using std::swap;
|
||||
swap(first.ptr_, second.ptr_);
|
||||
swap(first.owns_, second.owns_);
|
||||
}
|
||||
|
||||
void dealloc() {
|
||||
if (owns_ && ptr_) { mxDestroyArray(ptr_); ptr_ = NULL; owns_ = false; }
|
||||
}
|
||||
public:
|
||||
// --------------------------------------------------------------------------
|
||||
// CONSTRUCTORS
|
||||
// --------------------------------------------------------------------------
|
||||
/*!
|
||||
* @brief default constructor
|
||||
*
|
||||
* Construct a valid 0x0 matrix (so all other methods do not need validity checks)
|
||||
*/
|
||||
MxArray() : ptr_(mxCreateDoubleMatrix(0, 0, matlab::Traits<>::Real)), owns_(true) {}
|
||||
|
||||
/*!
|
||||
* @brief destructor
|
||||
*
|
||||
* The destructor deallocates any data allocated by mxCreate* methods only
|
||||
* if the object is owned
|
||||
*/
|
||||
virtual ~MxArray() {
|
||||
dealloc();
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief inheriting constructor
|
||||
*
|
||||
* Inherit an mxArray from Matlab. Don't claim ownership of the array,
|
||||
* just encapsulate it
|
||||
*/
|
||||
MxArray(const mxArray* ptr) : ptr_(const_cast<mxArray *>(ptr)), owns_(false) {}
|
||||
MxArray& operator=(const mxArray* ptr) {
|
||||
dealloc();
|
||||
ptr_ = const_cast<mxArray *>(ptr);
|
||||
owns_ = false;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief explicit typed constructor
|
||||
*
|
||||
* This constructor explicitly creates an MxArray of the given size and type.
|
||||
*/
|
||||
MxArray(size_t m, size_t n, size_t k, mxClassID id, mxComplexity com = matlab::Traits<>::Real)
|
||||
: ptr_(NULL), owns_(true) {
|
||||
mwSize dims[] = { static_cast<mwSize>(m), static_cast<mwSize>(n), static_cast<mwSize>(k) };
|
||||
ptr_ = mxCreateNumericArray(3, dims, id, com);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief explicit tensor constructor
|
||||
*
|
||||
* Explicitly construct a tensor of given size and type. Since constructors cannot
|
||||
* be explicitly templated, this is a static factory method
|
||||
*/
|
||||
template <typename Scalar>
|
||||
static MxArray Tensor(size_t m, size_t n, size_t k=1) {
|
||||
return MxArray(m, n, k, matlab::Traits<Scalar>::ScalarType);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief explicit matrix constructor
|
||||
*
|
||||
* Explicitly construct a matrix of given size and type. Since constructors cannot
|
||||
* be explicitly templated, this is a static factory method
|
||||
*/
|
||||
template <typename Scalar>
|
||||
static MxArray Matrix(size_t m, size_t n) {
|
||||
return MxArray(m, n, 1, matlab::Traits<Scalar>::ScalarType);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief explicit vector constructor
|
||||
*
|
||||
* Explicitly construct a vector of given size and type. Since constructors cannot
|
||||
* be explicitly templated, this is a static factory method
|
||||
*/
|
||||
template <typename Scalar>
|
||||
static MxArray Vector(size_t m) {
|
||||
return MxArray(m, 1, 1, matlab::Traits<Scalar>::ScalarType);
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief explicit scalar constructor
|
||||
*
|
||||
* Explicitly construct a scalar of given type. Since constructors cannot
|
||||
* be explicitly templated, this is a static factory method
|
||||
*/
|
||||
template <typename ScalarType>
|
||||
static MxArray Scalar(ScalarType value = 0) {
|
||||
MxArray s(1, 1, 1, matlab::Traits<ScalarType>::ScalarType);
|
||||
s.real<ScalarType>()[0] = value;
|
||||
return s;
|
||||
}
|
||||
|
||||
/*!
|
||||
* @brief copy constructor
|
||||
*
|
||||
* All copies are deep copies. If you have a C++11 compatible compiler, prefer
|
||||
* move construction to copy construction
|
||||
*/
|
||||
MxArray(const MxArray& other) : ptr_(mxDuplicateArray(other.ptr_)), owns_(true) {}
|
||||
|
||||
/*!
|
||||
* @brief copy-and-swap assignment
|
||||
*
|
||||
* This assignment operator uses the copy and swap idiom to provide a strong
|
||||
* exception guarantee when swapping two objects.
|
||||
*
|
||||
* Note in particular that the other MxArray is passed by value, thus invoking
|
||||
* the copy constructor which performs a deep copy of the input. The members of
|
||||
* this and other are then swapped
|
||||
*/
|
||||
MxArray& operator=(MxArray other) {
|
||||
swap(*this, other);
|
||||
return *this;
|
||||
}
|
||||
#if __cplusplus >= 201103L
|
||||
/*
|
||||
* @brief C++11 move constructor
|
||||
*
|
||||
* When C++11 support is available, move construction is used to move returns
|
||||
* out of functions, etc. This is much fast than copy construction, since the
|
||||
* move constructed object replaced itself with a default constructed MxArray,
|
||||
* which is of size 0 x 0.
|
||||
*/
|
||||
MxArray(MxArray&& other) : MxArray() {
|
||||
swap(*this, other);
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* @brief release ownership to allow return into Matlab workspace
|
||||
*
|
||||
* MxArray is not directly convertible back to mxArray types through assignment
|
||||
* because the MxArray may have been allocated on the free store, making it impossible
|
||||
* to know whether the returned pointer will be released by someone else or not.
|
||||
*
|
||||
* Since Matlab requires mxArrays be passed back into the workspace, the only way
|
||||
* to achieve that is through this function, which explicitly releases ownership
|
||||
* of the object, assuming the Matlab interpreter receving the object will delete
|
||||
* it at a later time
|
||||
*
|
||||
* e.g.
|
||||
* {
|
||||
* MxArray A = MxArray::Matrix<double>(5, 5); // allocates memory
|
||||
* MxArray B = MxArray::Matrix<double>(5, 5); // ditto
|
||||
* plhs[0] = A; // not allowed!!
|
||||
* plhs[0] = A.releaseOwnership(); // makes explicit that ownership is being released
|
||||
* } // end of scope. B is released, A isn't
|
||||
*
|
||||
*/
|
||||
mxArray* releaseOwnership() {
|
||||
owns_ = false;
|
||||
return ptr_;
|
||||
}
|
||||
|
||||
MxArray field(const std::string& name) { return MxArray(mxGetField(ptr_, 0, name.c_str())); }
|
||||
|
||||
template <typename Scalar>
|
||||
Scalar* real() { return static_cast<Scalar *>(mxGetData(ptr_)); }
|
||||
|
||||
template <typename Scalar>
|
||||
Scalar* imag() { return static_cast<Scalar *>(mxGetImagData(ptr_)); }
|
||||
|
||||
template <typename Scalar>
|
||||
const Scalar* real() const { return static_cast<const Scalar *>(mxGetData(ptr_)); }
|
||||
|
||||
template <typename Scalar>
|
||||
const Scalar* imag() const { return static_cast<const Scalar *>(mxGetData(ptr_)); }
|
||||
|
||||
template <typename Scalar>
|
||||
Scalar scalar() const { return static_cast<Scalar *>(mxGetData(ptr_))[0]; }
|
||||
|
||||
std::string toString() const {
|
||||
conditionalError(isString(), "Attempted to convert non-string type to string");
|
||||
std::string str(size(), '\0');
|
||||
mxGetString(ptr_, const_cast<char *>(str.data()), str.size()+1);
|
||||
return str;
|
||||
}
|
||||
|
||||
size_t size() const { return mxGetNumberOfElements(ptr_); }
|
||||
bool empty() const { return size() == 0; }
|
||||
size_t rows() const { return mxGetDimensions(ptr_)[0]; }
|
||||
size_t cols() const { return mxGetDimensions(ptr_)[1]; }
|
||||
size_t channels() const { return (mxGetNumberOfDimensions(ptr_) > 2) ? mxGetDimensions(ptr_)[2] : 1; }
|
||||
bool isComplex() const { return mxIsComplex(ptr_); }
|
||||
bool isNumeric() const { return mxIsNumeric(ptr_); }
|
||||
bool isLogical() const { return mxIsLogical(ptr_); }
|
||||
bool isString() const { return mxIsChar(ptr_); }
|
||||
bool isCell() const { return mxIsCell(ptr_); }
|
||||
bool isStructure() const { return mxIsStruct(ptr_); }
|
||||
bool isClass(const std::string& name) const { return mxIsClass(ptr_, name.c_str()); }
|
||||
std::string className() const { return std::string(mxGetClassName(ptr_)); }
|
||||
mxClassID ID() const { return mxGetClassID(ptr_); }
|
||||
|
||||
};
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// ARGUMENT PARSER
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/*! @class ArgumentParser
|
||||
* @brief parses inputs to a method and resolves the argument names.
|
||||
*
|
||||
* The ArgumentParser resolves the inputs to a method. It checks that all
|
||||
* required arguments are specified and also allows named optional arguments.
|
||||
* For example, the C++ function:
|
||||
* void randn(Mat& mat, Mat& mean=Mat(), Mat& std=Mat());
|
||||
* could be called in Matlab using any of the following signatures:
|
||||
* \code
|
||||
* out = randn(in);
|
||||
* out = randn(in, 0, 1);
|
||||
* out = randn(in, 'mean', 0, 'std', 1);
|
||||
* \endcode
|
||||
*
|
||||
* ArgumentParser also enables function overloading by allowing users
|
||||
* to add variants to a method. For example, there may be two C++ sum() methods:
|
||||
* \code
|
||||
* double sum(Mat& mat); % sum elements of a matrix
|
||||
* Mat sum(Mat& A, Mat& B); % add two matrices
|
||||
* \endcode
|
||||
*
|
||||
* by adding two variants to ArgumentParser, the correct underlying sum
|
||||
* method can be called. If the function call is ambiguous, the
|
||||
* ArgumentParser will fail with an error message.
|
||||
*
|
||||
* The previous example could be parsed as:
|
||||
* \code
|
||||
* // set up the Argument parser
|
||||
* ArgumentParser arguments;
|
||||
* arguments.addVariant("elementwise", 1);
|
||||
* arguments.addVariant("matrix", 2);
|
||||
*
|
||||
* // parse the arguments
|
||||
* std::vector<MxArray> inputs;
|
||||
* inputs = arguments.parse(std::vector<MxArray>(prhs, prhs+nrhs));
|
||||
*
|
||||
* // if we get here, one unique variant is valid
|
||||
* if (arguments.variantIs("elementwise")) {
|
||||
* // call elementwise sum()
|
||||
* }
|
||||
* \endcode
|
||||
*/
|
||||
class ArgumentParser {
|
||||
private:
|
||||
struct Variant;
|
||||
typedef std::string String;
|
||||
typedef std::vector<std::string> StringVector;
|
||||
typedef std::vector<size_t> IndexVector;
|
||||
typedef std::vector<Variant> VariantVector;
|
||||
|
||||
/* @class Variant
|
||||
* @brief Describes a variant of arguments to a method
|
||||
*
|
||||
* When addVariant() is called on an instance to ArgumentParser, this class
|
||||
* holds the the information that decribes that variant. The parse() method
|
||||
* of ArgumentParser then attempts to match a Variant, given a set of
|
||||
* inputs for a method invocation.
|
||||
*/
|
||||
class Variant {
|
||||
private:
|
||||
String name_;
|
||||
size_t Nreq_;
|
||||
size_t Nopt_;
|
||||
StringVector keys_;
|
||||
IndexVector order_;
|
||||
bool valid_;
|
||||
size_t nparsed_;
|
||||
size_t nkeys_;
|
||||
size_t working_opt_;
|
||||
bool expecting_val_;
|
||||
bool using_named_;
|
||||
size_t find(const String& key) const {
|
||||
return std::find(keys_.begin(), keys_.end(), key) - keys_.begin();
|
||||
}
|
||||
public:
|
||||
/*! @brief default constructor */
|
||||
Variant() : Nreq_(0), Nopt_(0), valid_(false) {}
|
||||
/*! @brief construct a new variant spec */
|
||||
Variant(const String& name, size_t Nreq, size_t Nopt, const StringVector& keys)
|
||||
: name_(name), Nreq_(Nreq), Nopt_(Nopt), keys_(keys),
|
||||
order_(Nreq+Nopt, Nreq+2*Nopt), valid_(true), nparsed_(0), nkeys_(0),
|
||||
working_opt_(0), expecting_val_(false), using_named_(false) {}
|
||||
/*! @brief the name of the variant */
|
||||
String name() const { return name_; }
|
||||
/*! @brief return the total number of arguments the variant can take */
|
||||
size_t size() const { return Nreq_ + Nopt_; }
|
||||
/*! @brief has the variant been fulfilled? */
|
||||
bool fulfilled() const { return (valid_ && nparsed_ >= Nreq_ && !expecting_val_); }
|
||||
/*! @brief is the variant in a valid state (though not necessarily fulfilled) */
|
||||
bool valid() const { return valid_; }
|
||||
/*! @brief check if the named argument exists in the variant */
|
||||
bool exist(const String& key) const { return find(key) != keys_.size(); }
|
||||
/*! @brief retrieve the order mapping raw inputs to their position in the variant */
|
||||
const IndexVector& order() const { return order_; }
|
||||
size_t order(size_t n) const { return order_[n]; }
|
||||
/*! @brief attempt to parse the next argument as a value */
|
||||
bool parseNextAsValue() {
|
||||
if (!valid_) {}
|
||||
else if ((using_named_ && !expecting_val_) || (nparsed_-nkeys_ == Nreq_+Nopt_)) { valid_ = false; }
|
||||
else if (nparsed_ < Nreq_) { order_[nparsed_] = nparsed_; }
|
||||
else if (!using_named_) { order_[nparsed_] = nparsed_; }
|
||||
else if (using_named_ && expecting_val_) { order_[Nreq_ + working_opt_] = nparsed_; }
|
||||
nparsed_++;
|
||||
expecting_val_ = false;
|
||||
return valid_;
|
||||
}
|
||||
/*! @biref attempt to parse the next argument as a name (key) */
|
||||
bool parseNextAsKey(const String& key) {
|
||||
if (!valid_) {}
|
||||
else if ((nparsed_ < Nreq_) || (nparsed_-nkeys_ == Nreq_+Nopt_)) { valid_ = false; }
|
||||
else if (using_named_ && expecting_val_) { valid_ = false; }
|
||||
else if ((working_opt_ = find(key)) == keys_.size()) { valid_ = false; }
|
||||
else { using_named_ = true; expecting_val_ = true; nkeys_++; nparsed_++; }
|
||||
return valid_;
|
||||
}
|
||||
String toString(const String& method_name="f") const {
|
||||
int req_begin = 0, req_end = 0, opt_begin = 0, opt_end = 0;
|
||||
std::ostringstream s;
|
||||
// f(...)
|
||||
s << method_name << "(";
|
||||
// required arguments
|
||||
req_begin = s.str().size();
|
||||
for (size_t n = 0; n < Nreq_; ++n) { s << "src" << n+1 << (n != Nreq_-1 ? ", " : ""); }
|
||||
req_end = s.str().size();
|
||||
if (Nreq_ && Nopt_) s << ", ";
|
||||
// optional arguments
|
||||
opt_begin = s.str().size();
|
||||
for (size_t n = 0; n < keys_.size(); ++n) { s << "'" << keys_[n] << "', " << keys_[n] << (n != Nopt_-1 ? ", " : ""); }
|
||||
opt_end = s.str().size();
|
||||
s << ");";
|
||||
if (Nreq_ + Nopt_ == 0) return s.str();
|
||||
// underscores
|
||||
String under = String(req_begin, ' ') + String(req_end-req_begin, '-')
|
||||
+ String(std::max(opt_begin-req_end,0), ' ') + String(opt_end-opt_begin, '-');
|
||||
s << "\n" << under;
|
||||
// required and optional sets
|
||||
String req_set(req_end-req_begin, ' ');
|
||||
String opt_set(opt_end-opt_begin, ' ');
|
||||
if (!req_set.empty() && req_set.size() < 8) req_set.replace((req_set.size()-3)/2, 3, "req");
|
||||
if (req_set.size() > 7) req_set.replace((req_set.size()-8)/2, 8, "required");
|
||||
if (!opt_set.empty() && opt_set.size() < 8) opt_set.replace((opt_set.size()-3)/2, 3, "opt");
|
||||
if (opt_set.size() > 7) opt_set.replace((opt_set.size()-8)/2, 8, "optional");
|
||||
String set = String(req_begin, ' ') + req_set + String(std::max(opt_begin-req_end,0), ' ') + opt_set;
|
||||
s << "\n" << set;
|
||||
return s.str();
|
||||
}
|
||||
};
|
||||
/*! @brief given an input and output vector of arguments, and a variant spec, sort */
|
||||
void sortArguments(Variant& v, MxArrayVector& in, MxArrayVector& out) {
|
||||
// allocate the output array with ALL arguments
|
||||
out.resize(v.size());
|
||||
// reorder the inputs based on the variant ordering
|
||||
for (size_t n = 0; n < v.size(); ++n) {
|
||||
if (v.order(n) >= in.size()) continue;
|
||||
swap(in[v.order(n)], out[n]);
|
||||
}
|
||||
}
|
||||
VariantVector variants_;
|
||||
String valid_;
|
||||
String method_name_;
|
||||
public:
|
||||
ArgumentParser(const String& method_name) : method_name_(method_name) {}
|
||||
|
||||
/*! @brief add a function call variant to the parser
|
||||
*
|
||||
* Adds a function-call signature to the parser. The function call *must* be
|
||||
* unique either in its number of arguments, or in the named-syntax.
|
||||
* Currently this function does not check whether that invariant stands true.
|
||||
*
|
||||
* This function is variadic. If should be called as follows:
|
||||
* addVariant(2, 2, 'opt_1_name', 'opt_2_name');
|
||||
*/
|
||||
void addVariant(const String& name, size_t nreq, size_t nopt = 0, ...) {
|
||||
StringVector keys;
|
||||
va_list opt;
|
||||
va_start(opt, nopt);
|
||||
for (size_t n = 0; n < nopt; ++n) keys.push_back(va_arg(opt, const char*));
|
||||
addVariant(name, nreq, nopt, keys);
|
||||
}
|
||||
void addVariant(const String& name, size_t nreq, size_t nopt, StringVector keys) {
|
||||
variants_.push_back(Variant(name, nreq, nopt, keys));
|
||||
}
|
||||
|
||||
/*! @brief check if the valid variant is the key name */
|
||||
bool variantIs(const String& name) {
|
||||
return name.compare(valid_) == 0;
|
||||
}
|
||||
|
||||
/*! @brief parse a vector of input arguments
|
||||
*
|
||||
* This method parses a vector of input arguments, attempting to match them
|
||||
* to a Variant spec. For each input, the method attempts to cull any
|
||||
* Variants which don't match the given inputs so far.
|
||||
*
|
||||
* Once all inputs have been parsed, if there is one unique spec remaining,
|
||||
* the output MxArray vector gets populated with the arguments, with named
|
||||
* arguments removed. Any optional arguments that have not been encountered
|
||||
* are set to an empty array.
|
||||
*
|
||||
* If multiple variants or no variants match the given call, an error
|
||||
* message is emitted
|
||||
*/
|
||||
MxArrayVector parse(const MxArrayVector& inputs) {
|
||||
// allocate the outputs
|
||||
String variant_string;
|
||||
MxArrayVector outputs;
|
||||
VariantVector candidates = variants_;
|
||||
|
||||
// iterate over the inputs, attempting to match a variant
|
||||
for (MxArrayVector::const_iterator input = inputs.begin(); input != inputs.end(); ++input) {
|
||||
String name = input->isString() ? input->toString() : String();
|
||||
for (VariantVector::iterator candidate = candidates.begin(); candidate < candidates.end(); ++candidate) {
|
||||
candidate->exist(name) ? candidate->parseNextAsKey(name) : candidate->parseNextAsValue();
|
||||
}
|
||||
}
|
||||
|
||||
// make sure the candidates have been fulfilled
|
||||
for (VariantVector::iterator candidate = candidates.begin(); candidate < candidates.end(); ++candidate) {
|
||||
if (!candidate->fulfilled()) candidate = candidates.erase(candidate)--;
|
||||
}
|
||||
|
||||
// if there is not a unique candidate, throw an error
|
||||
for (VariantVector::iterator variant = variants_.begin(); variant != variants_.end(); ++variant) {
|
||||
variant_string += "\n" + variant->toString(method_name_);
|
||||
}
|
||||
|
||||
// if there is not a unique candidate, throw an error
|
||||
if (candidates.size() > 1) {
|
||||
error(String("Call to method is ambiguous. Valid variants are:")
|
||||
.append(variant_string).append("\nUse named arguments to disambiguate call"));
|
||||
}
|
||||
if (candidates.size() == 0) {
|
||||
error(String("No matching method signatures for given arguments. Valid variants are:").append(variant_string));
|
||||
}
|
||||
|
||||
// Unique candidate!
|
||||
valid_ = candidates[0].name();
|
||||
sortArguments(candidates[0], const_cast<MxArrayVector&>(inputs), outputs);
|
||||
return outputs;
|
||||
}
|
||||
};
|
||||
|
||||
//! @}
|
||||
|
||||
} // namespace matlab
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,147 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this
|
||||
// license. If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of the copyright holders may not be used to endorse or promote
|
||||
// products derived from this software without specific prior written
|
||||
// permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is"
|
||||
// and any express or implied warranties, including, but not limited to, the
|
||||
// implied warranties of merchantability and fitness for a particular purpose
|
||||
// are disclaimed. In no event shall the Intel Corporation or contributors be
|
||||
// liable for any direct, indirect, incidental, special, exemplary, or
|
||||
// consequential damages (including, but not limited to, procurement of
|
||||
// substitute goods or services; loss of use, data, or profits; or business
|
||||
// interruption) however caused and on any theory of liability, whether in
|
||||
// contract, strict liability, or tort (including negligence or otherwise)
|
||||
// arising in any way out of the use of this software, even if advised of the
|
||||
// possibility of such damage.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
#ifndef OPENCV_TRANSPOSE_HPP_
|
||||
#define OPENCV_TRANSPOSE_HPP_
|
||||
|
||||
//! @addtogroup matlab
|
||||
//! @{
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void transposeBlock(const size_t M, const size_t N, const InputScalar* src, size_t lda, OutputScalar* dst, size_t ldb) {
|
||||
InputScalar cache[16];
|
||||
// copy the source into the cache contiguously
|
||||
for (size_t n = 0; n < N; ++n)
|
||||
for (size_t m = 0; m < M; ++m)
|
||||
cache[m+n*4] = src[m+n*lda];
|
||||
// copy the destination out of the cache contiguously
|
||||
for (size_t m = 0; m < M; ++m)
|
||||
for (size_t n = 0; n < N; ++n)
|
||||
dst[n+m*ldb] = cache[m+n*4];
|
||||
}
|
||||
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void transpose4x4(const InputScalar* src, size_t lda, OutputScalar* dst, size_t ldb) {
|
||||
InputScalar cache[16];
|
||||
// copy the source into the cache contiguously
|
||||
cache[0] = src[0]; cache[1] = src[1]; cache[2] = src[2]; cache[3] = src[3]; src+=lda;
|
||||
cache[4] = src[0]; cache[5] = src[1]; cache[6] = src[2]; cache[7] = src[3]; src+=lda;
|
||||
cache[8] = src[0]; cache[9] = src[1]; cache[10] = src[2]; cache[11] = src[3]; src+=lda;
|
||||
cache[12] = src[0]; cache[13] = src[1]; cache[14] = src[2]; cache[15] = src[3]; src+=lda;
|
||||
// copy the destination out of the contiguously
|
||||
dst[0] = cache[0]; dst[1] = cache[4]; dst[2] = cache[8]; dst[3] = cache[12]; dst+=ldb;
|
||||
dst[0] = cache[1]; dst[1] = cache[5]; dst[2] = cache[9]; dst[3] = cache[13]; dst+=ldb;
|
||||
dst[0] = cache[2]; dst[1] = cache[6]; dst[2] = cache[10]; dst[3] = cache[14]; dst+=ldb;
|
||||
dst[0] = cache[3]; dst[1] = cache[7]; dst[2] = cache[11]; dst[3] = cache[15]; dst+=ldb;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Vanilla copy, transpose and cast
|
||||
*/
|
||||
template <typename InputScalar, typename OutputScalar>
|
||||
void gemt(const char major, const size_t M, const size_t N, const InputScalar* a, size_t lda, OutputScalar* b, size_t ldb) {
|
||||
|
||||
// 1x1 transpose is just copy
|
||||
if (M == 1 && N == 1) { *b = *a; return; }
|
||||
|
||||
// get the interior 4x4 blocks, and the extra skirting
|
||||
const size_t Fblock = (major == 'R') ? N/4 : M/4;
|
||||
const size_t Frem = (major == 'R') ? N%4 : M%4;
|
||||
const size_t Sblock = (major == 'R') ? M/4 : N/4;
|
||||
const size_t Srem = (major == 'R') ? M%4 : N%4;
|
||||
|
||||
// if less than 4x4, invoke the block transpose immediately
|
||||
if (M < 4 && N < 4) { transposeBlock(Frem, Srem, a, lda, b, ldb); return; }
|
||||
|
||||
// transpose 4x4 blocks
|
||||
const InputScalar* aptr = a;
|
||||
OutputScalar* bptr = b;
|
||||
for (size_t second = 0; second < Sblock; ++second) {
|
||||
aptr = a + second*lda;
|
||||
bptr = b + second;
|
||||
for (size_t first = 0; first < Fblock; ++first) {
|
||||
transposeBlock(4, 4, aptr, lda, bptr, ldb);
|
||||
//transpose4x4(aptr, lda, bptr, ldb);
|
||||
aptr+=4;
|
||||
bptr+=4*ldb;
|
||||
}
|
||||
// transpose trailing blocks on primary dimension
|
||||
transposeBlock(Frem, 4, aptr, lda, bptr, ldb);
|
||||
}
|
||||
// transpose trailing blocks on secondary dimension
|
||||
aptr = a + 4*Sblock*lda;
|
||||
bptr = b + 4*Sblock;
|
||||
for (size_t first = 0; first < Fblock; ++first) {
|
||||
transposeBlock(4, Srem, aptr, lda, bptr, ldb);
|
||||
aptr+=4;
|
||||
bptr+=4*ldb;
|
||||
}
|
||||
// transpose bottom right-hand corner
|
||||
transposeBlock(Frem, Srem, aptr, lda, bptr, ldb);
|
||||
}
|
||||
|
||||
#ifdef __SSE2__
|
||||
/*
|
||||
* SSE2 supported fast copy, transpose and cast
|
||||
*/
|
||||
#include <emmintrin.h>
|
||||
|
||||
template <>
|
||||
void transpose4x4<float, float>(const float* src, size_t lda, float* dst, size_t ldb) {
|
||||
__m128 row0, row1, row2, row3;
|
||||
row0 = _mm_loadu_ps(src);
|
||||
row1 = _mm_loadu_ps(src+lda);
|
||||
row2 = _mm_loadu_ps(src+2*lda);
|
||||
row3 = _mm_loadu_ps(src+3*lda);
|
||||
_MM_TRANSPOSE4_PS(row0, row1, row2, row3);
|
||||
_mm_storeu_ps(dst, row0);
|
||||
_mm_storeu_ps(dst+ldb, row1);
|
||||
_mm_storeu_ps(dst+2*ldb, row2);
|
||||
_mm_storeu_ps(dst+3*ldb, row3);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//! @}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,23 @@
|
||||
set(TEST_PROXY ${CMAKE_CURRENT_BINARY_DIR}/test.proxy)
|
||||
file(REMOVE ${TEST_PROXY})
|
||||
|
||||
# generate
|
||||
# call the python executable to generate the Matlab gateways
|
||||
add_custom_command(
|
||||
OUTPUT ${TEST_PROXY}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/OpenCVTest.m ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/testsuite.m ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMAND ${CMAKE_COMMAND} -E touch ${TEST_PROXY}
|
||||
COMMENT "Building Matlab tests"
|
||||
)
|
||||
|
||||
# targets
|
||||
# opencv_matlab_sources --> opencv_matlab
|
||||
add_custom_target(opencv_test_matlab ALL DEPENDS ${TEST_PROXY})
|
||||
add_dependencies(opencv_test_matlab ${the_module})
|
||||
|
||||
# run the matlab test suite
|
||||
add_test(opencv_test_matlab
|
||||
COMMAND ${MATLAB_BIN} "-nodisplay" "-r" "testsuite.m"
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
@@ -0,0 +1,166 @@
|
||||
% Matlab binding test cases
|
||||
% Uses Matlab's builtin testing framework
|
||||
classdef OpenCVTest < matlab.unittest.TestCase
|
||||
|
||||
methods(Test)
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% EXCEPTIONS
|
||||
% Check that errors and exceptions are thrown correctly
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% check that std exception is thrown
|
||||
function stdException(testcase)
|
||||
try
|
||||
std_exception();
|
||||
testcase.verifyFail();
|
||||
catch
|
||||
% TODO: Catch more specific exception
|
||||
testcase.verifyTrue(true);
|
||||
end
|
||||
end
|
||||
|
||||
% check that OpenCV exceptions are correctly caught
|
||||
function cvException(testcase)
|
||||
try
|
||||
cv_exception();
|
||||
testcase.verifyFail();
|
||||
catch
|
||||
% TODO: Catch more specific exception
|
||||
testcase.verifyTrue(true);
|
||||
end
|
||||
end
|
||||
|
||||
% check that all exceptions are caught
|
||||
function allException(testcase)
|
||||
try
|
||||
exception();
|
||||
testcase.verifyFail();
|
||||
catch
|
||||
% TODO: Catch more specific exception
|
||||
testcase.verifyTrue(true);
|
||||
end
|
||||
end
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% SIZES AND FILLS
|
||||
% Check that matrices are correctly filled and resized
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% check that a matrix is correctly filled with random numbers
|
||||
function randomFill(testcase)
|
||||
sz = [7 11];
|
||||
mat = zeros(sz);
|
||||
mat = cv.randn(mat, 0, 1);
|
||||
testcase.verifyEqual(size(mat), sz, 'Matrix should not change size');
|
||||
testcase.verifyNotEqual(mat, zeros(sz), 'Matrix should be nonzero');
|
||||
end
|
||||
|
||||
function transpose(testcase)
|
||||
m = randn(19, 81);
|
||||
mt1 = transpose(m);
|
||||
mt2 = cv.transpose(m);
|
||||
testcase.verifyEqual(size(mt1), size(mt2), 'Matrix transposed to incorrect dimensionality');
|
||||
testcase.verifyLessThan(norm(mt1 - mt2), 1e-8, 'Too much precision lost in tranposition');
|
||||
end
|
||||
|
||||
% multiple return
|
||||
function multipleReturn(testcase)
|
||||
A = randn(10);
|
||||
A = A'*A;
|
||||
[V1, D1] = eig(A); D1 = diag(D1);
|
||||
[~, D2, V2] = cv.eigen(A);
|
||||
testcase.verifyLessThan(norm(V1 - V2), 1e-6, 'Too much precision lost in eigenvectors');
|
||||
testcase.verifyLessThan(norm(D1 - D2), 1e-6, 'Too much precision lost in eigenvalues');
|
||||
end
|
||||
|
||||
% complex output from SVD
|
||||
function complexOutputSVD(testcase)
|
||||
A = randn(10);
|
||||
[V1, D1] = eig(A);
|
||||
[~, D2, V2] = cv.eigen(A);
|
||||
testcase.verifyTrue(~isreal(V2) && size(V2,3) == 1, 'Output should be complex');
|
||||
testcase.verifyLessThan(norm(V1 - V2), 1e-6, 'Too much precision lost in eigenvectors');
|
||||
end
|
||||
|
||||
% complex output from Fourier Transform
|
||||
function complexOutputFFT(testcase)
|
||||
A = randn(10);
|
||||
F1 = fft2(A);
|
||||
F2 = cv.dft(A, cv.DFT_COMPLEX_OUTPUT);
|
||||
testcase.verifyTrue(~isreal(F2) && size(F2,3) == 1, 'Output should be complex');
|
||||
testcase.verifyLessThan(norm(F1 - F2), 1e-6, 'Too much precision lost in eigenvectors');
|
||||
end
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% TYPE CASTS
|
||||
% Check that types are correctly cast
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% PRECISION
|
||||
% Check that basic operations are performed with sufficient precision
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% check that summing elements is within reasonable precision
|
||||
function sumElements(testcase)
|
||||
a = randn(5000);
|
||||
b = sum(a(:));
|
||||
c = cv.sum(a);
|
||||
testcase.verifyLessThan(norm(b - c), 1e-8, 'Matrix reduction with insufficient precision');
|
||||
end
|
||||
|
||||
|
||||
% check that adding two matrices is within reasonable precision
|
||||
function addPrecision(testcase)
|
||||
a = randn(50);
|
||||
b = randn(50);
|
||||
c = a+b;
|
||||
d = cv.add(a, b);
|
||||
testcase.verifyLessThan(norm(c - d), 1e-8, 'Matrices are added with insufficient precision');
|
||||
end
|
||||
|
||||
% check that performing gemm is within reasonable precision
|
||||
function gemmPrecision(testcase)
|
||||
a = randn(10, 50);
|
||||
b = randn(50, 10);
|
||||
c = randn(10, 10);
|
||||
alpha = 2.71828;
|
||||
gamma = 1.61803;
|
||||
d = alpha*a*b + gamma*c;
|
||||
e = cv.gemm(a, b, alpha, c, gamma);
|
||||
testcase.verifyLessThan(norm(d - e), 1e-8, 'Matrices are multiplied with insufficient precision');
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% MISCELLANEOUS
|
||||
% Miscellaneous tests
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% check that cv::waitKey waits for at least specified time
|
||||
function waitKey(testcase)
|
||||
tic();
|
||||
cv.waitKey(500);
|
||||
elapsed = toc();
|
||||
testcase.verifyGreaterThan(elapsed, 0.5, 'Elapsed time should be at least 0.5 seconds');
|
||||
end
|
||||
|
||||
% check that highgui window can be created and destroyed
|
||||
function createAndDestroyWindow(testcase)
|
||||
try
|
||||
cv.namedWindow('test window');
|
||||
catch
|
||||
testcase.verifyFail('could not create window');
|
||||
end
|
||||
|
||||
try
|
||||
cv.destroyWindow('test window');
|
||||
catch
|
||||
testcase.verifyFail('could not destroy window');
|
||||
end
|
||||
testcase.verifyTrue(true);
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* file: exception.cpp
|
||||
* author: Hilton Bristow
|
||||
* date: Wed, 19 Jun 2013 11:15:15
|
||||
*
|
||||
* See LICENCE for full modification and redistribution details.
|
||||
* Copyright 2013 The OpenCV Foundation
|
||||
*/
|
||||
#include <exception>
|
||||
#include <opencv2/core.hpp>
|
||||
#include "mex.h"
|
||||
|
||||
/*
|
||||
* exception
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// call the opencv function
|
||||
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
|
||||
try {
|
||||
throw cv::Exception(-1, "OpenCV exception thrown", __func__, __FILE__, __LINE__);
|
||||
} catch(const cv::Exception& e) {
|
||||
mexErrMsgTxt(e.what());
|
||||
} catch(...) {
|
||||
mexErrMsgTxt("Incorrect exception caught!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* file: exception.cpp
|
||||
* author: Hilton Bristow
|
||||
* date: Wed, 19 Jun 2013 11:15:15
|
||||
*
|
||||
* See LICENCE for full modification and redistribution details.
|
||||
* Copyright 2013 The OpenCV Foundation
|
||||
*/
|
||||
#include "mex.h"
|
||||
|
||||
/*
|
||||
* exception
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// call the opencv function
|
||||
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
|
||||
try {
|
||||
throw 1;
|
||||
} catch(...) {
|
||||
mexErrMsgTxt("Uncaught exception occurred!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
function help()
|
||||
%CV.HELP display help information for the OpenCV Toolbox
|
||||
%
|
||||
% Calling:
|
||||
% >> cv.help();
|
||||
%
|
||||
% is equivalent to calling:
|
||||
% >> help cv;
|
||||
%
|
||||
% It displays high-level usage information about the OpenCV toolbox
|
||||
% along with resources to find out more information.
|
||||
%
|
||||
% See also: cv.buildInformation
|
||||
help('cv');
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* file: exception.cpp
|
||||
* author: Hilton Bristow
|
||||
* date: Wed, 19 Jun 2013 11:15:15
|
||||
*
|
||||
* See LICENCE for full modification and redistribution details.
|
||||
* Copyright 2013 The OpenCV Foundation
|
||||
*/
|
||||
#include <exception>
|
||||
#include "mex.h"
|
||||
|
||||
/*
|
||||
* exception
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// call the opencv function
|
||||
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
|
||||
try {
|
||||
throw std::exception();
|
||||
} catch(const std::exception& e) {
|
||||
mexErrMsgTxt(e.what());
|
||||
} catch(...) {
|
||||
mexErrMsgTxt("Incorrect exception caught!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* file: rand.cpp
|
||||
* author: A trusty code generator
|
||||
* date: Wed, 19 Jun 2013 11:15:15
|
||||
*
|
||||
* This file was autogenerated, do not modify.
|
||||
* See LICENCE for full modification and redistribution details.
|
||||
* Copyright 2013 The OpenCV Foundation
|
||||
*/
|
||||
#include "mex.h"
|
||||
#include <vector>
|
||||
|
||||
/*
|
||||
* rand
|
||||
* Gateway routine
|
||||
* nlhs - number of return arguments
|
||||
* plhs - pointers to return arguments
|
||||
* nrhs - number of input arguments
|
||||
* prhs - pointers to input arguments
|
||||
*/
|
||||
void mexFunction(int nlhs, mxArray* plhs[],
|
||||
int nrhs, const mxArray* prhs[]) {
|
||||
|
||||
// call the opencv function
|
||||
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
|
||||
try {
|
||||
rand();
|
||||
} catch(...) {
|
||||
mexErrMsgTxt("Uncaught exception occurred in rand");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* a rather innocuous-looking function which is actually
|
||||
* part of <cstdlib>, so we can be reasonably sure its
|
||||
* definition will be found
|
||||
*/
|
||||
#ifndef __OPENCV_MATLAB_TEST_GENERATOR_HPP_
|
||||
#define __OPENCV_MATLAB_TEST_GENERATOR_HPP_
|
||||
|
||||
namespace cv {
|
||||
|
||||
CV_EXPORTS_W int rand( );
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
% add the opencv bindings folder
|
||||
addpath ..
|
||||
|
||||
%setup the tests
|
||||
opencv_tests = OpenCVTest();
|
||||
|
||||
%run the tests
|
||||
result = run(opencv_tests);
|
||||
|
||||
% shutdown
|
||||
exit();
|
||||
Reference in New Issue
Block a user