1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-30 15:53:03 +04:00

Merge pull request #9466 from huningxin:js

GSoC 2017: Improve and Extend the JavaScript Bindings for OpenCV (#9466)

* Initial support for build with emscripten

mkdir build_js
cd build_js
cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/emsdk/emsdk-portable/emscripten/master/cmake/Modules/Platform/Emscripten.cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..

* Add js module

The output is build/bin/opencv_js.js

* Fix opencv2/calib3d.hpp not found issue

* Add module name

Usage:
var cv = cv();

* Add total memory as 128MB and allow growth

* Add compilation flags for emscripten

* Use EMSCRIPTEN build target

* Disable js module for non emscripten build

* Bind the preload file path to root

Usage:
face_cascade.load('haarcascade_frontalface_default.xml');

* add test folder

* fix test files

* Copy js module test to bin

* Support to run tests on Node.js

Fix tests to import cv Module when runtime is node.
Add tests.js to use qunit to auto run tests.
Modify umd wrapper to support Module is not defined.

Usage:
node tests.js

* Support UMD and file system

Wrap the opencv_js.js to opencv.js by UMD wrapper

Use emscripten file system API to load files instead of generating data file or
embedding them. It supports both browser and node.js usages.

* Fix incorrect module name in tests

* Add package.json to add dependence of qunit

* Add js_tutorials folder and a intro page of opencv.js

Enable BUILD_DOCS in CMakeLists.txt.
Add new folder of js_tutorials in folder opencv/doc.
Imitate the tutorials of OpenCV-Python to create a intro page of opencv.js and a setup guide

* Import and use binding gen from opencvjs project

* Modify the embindgen.py to pass the build and test

* Add classes and functions white list

* Consolidate hdr_parser.py (#31)

Use hdr_parser.py of python module

Add js flag to support js binding generator.

* Use emscripten::vecFromJSArray for input vector param

Fix part of #23

* Fix test cases after #34

Fix #39

* Expose groupRectangles and CascadeClassifier.empty

* Add js highgui tutorials

add tutorials of imread&imshow and createTrackbar in doc/js_tutorials/js_gui folder
add interactive tutorial webpage for imread&imshow and createTrackbar in doc/js_tutorials/js_interactive_tutorials folder, and some images needed.
change doc/CMakeLists.txt to copy the interactive tutorial webpage and opencv.js to the tutorials' destination folder

* rm useless annotation in doc/CMakeLists.txt

* fix some nonstandard indentation and space

* add check if canvas is valid

* Expose BackgroundSubtractorMOG2

Fix #43

* Fix build of js doc

Limit copy_js_interactive_tutorials for doxygen build
Add dep to opencv.js

Fix #53

* Implement cv.imread & cv.imshow and insert interactive pages in tutorials (#55)

* add helper.js

* delete ALL in add target copy_js_interactive_tutorials to avoid dependence error

* Insert interactive pages in tutorials

insert the old interactive pages in markdown by using \htmlonly and \endhtmlonly command.
delete the useless interactive page
rename js_interactive_tutorials to js_assets to put some images needed in

* fix the depends of the target doxygen

add opencv.js to depends and delete the useless target of copy_js_assets

* change filename helper.js to helpers.js

* disable button or trankbar before opencv.js is ready

* Expose CV_64F

Fix #65

* improve cv.imshow to display different types as native imshow

* add utils.js to reuse functions and update tutorials

* Make doxygen depend on bin/opencv.js

* Fix memory issue of matFromArray

Fix #37

* Merge pull request from ganwenyao/tutorial_18

* Add notes for ganwenyao/tutorial_18

* Modifying for ganwenyao/tutorial_18

* Change Mat constructor with data to 5 parameters

* Mat supports constructor with Scalar

Fix #60

* update cv.imread cause the memory issue of matFromArray has been fixed

* fix canvas name and default input image

* Expose cv::Moments

Fix #85

* Add -Wno-missing-prototypes for emscripten build

* fix canvas name

* add tutorial of video input and output

* Expose enums as emscripten consts

Fix #72

* update the tutorial to use Mat constructor with Scalar and change lena.jpg

* Exclude cv::Mat for vecFromJSArray

Fix #82

* Add unit tests for cv.moments

* Fix the unit tests.

* add checkbox and stop button

* add adapter.js to make sure compatibility fo video tutorials

* Support default parameters with function overloading

* modify enums to constants

* Use https URL for MathJax.js

Fix #109

* Comment out the debug print in embindgen.py

* Expose RotatedRect

Fix #96

* replace enum with constants and improve onload function

* delete some useless paras cause #105 fixed this

* Modify const name

* Modify Contour Properties

* tutorials for imgprc2 and objdec

* Expose more functions for img proc tutorials

Fix #76

* Expose polylines for video analysis tutorial

Fix #121

* Expose constants for default parameters of img proc tutorials

Fix #122

* Fix wrong parameter types of Mat.copyTo

Fix #87

* Support default parameters of mat.convertTo

Fix #123

* Support default parameters for external constructors

Fix #131

* Revert "Expose polylines for video analysis tutorial"

This reverts commit 3ce7615652e510d30e3c0014706ac38c98883189.

Fix #121

* Support cv.minMaxLoc

Fix #127

* Expose cv.minEnclosingCircle

Fix #126

* Add video analysis tutorials

add three video tutorials, Meanshift and Camshift, Optical Flow Background Subtraction
add cup.mp4 and box.mp4 for demo in tutorials

* improve image processing tutorials

* repalce console.warn with throw to throw exception

* add try-catch to throw exception in code demo

* Change mat.size() return value to JS Array object

Fix #140

* add a note about different channels order between canvas and native opencv

* add a note about how to capture video from video files

* Binding cv.Scalar to JS array

Fix #147

* Add JS cv.Scalar object into helpers.js

* Update Install OpenCV-JavaScript tutorial page

Fix #44

* Update the OpenCV-JavaScript introduction page

Fix #44

* add cv.VideoCapture and read() function

* set the size of the hidden canvas same as the video

* Add Using OpenCV-JavaScript tutorial page

Fix #44

* fix some bad code style

* Update tutorials after 8/2 sync meeting

Changes include:
- Use OpenCV.js name instead of OpenCV-JavaScript
- Put using OpenCV.js ahead of build OpenCV.js
- Refine usage and introduction page
- Muted the video in tutorials

* Fix a typo in introduction page

* use cv.VideoCapture and its read() function to read video

* replace OpenCV-JavaScript with OpenCV.js

* Use onload of async script in js_usage tutorial

* add more info about mat.data

* Change Size to value_object

* Integrate Moh and Sajjad's editing into introduction page

* Change Point to value_object

* Change Rect to value_object with helper object

* Add helper objects for Point and Size

* Change RotatedRect to value_object with helpers

* Change MinMaxLoc and Circle to value_object

* Change TermCriteria to value_object

* Fix core_bindings.cpp for MinMaxLoc and Circle

* Remove unused types

* Change meanShift and CamShift to return Rect

* Change methods of RotatedRect to static

* Change mat.data from methods to property

Fix #75 and #77

* support img id and element in cv.imread

* Change mat.size to property and add mat.step

Fix #163

* Add matFromArray and matFromImageData as JS helpers

Fix #79, #78

* Lower camel case for Mat element getters

Fix #81

* Mat.getRoiRect and tests

Fix #86

* Support type for Mat.ptr

Fix #83

* Name changing of Mat element getters

'getUcharAt` -> 'ucharAt'

* fix code style and args names

* Fix helpers.js due to cv.Mat API update

* Fix opencv.js usage tutorial

* Fix a typo of js_setup

* Change Moments to value_object

* Add Range as value_object

Fix #171

* Support Mat.diag and Mat.isContinous

Fix #84 and #89

* Support Mat.setTo

Fix #88

* Apply edits to js_intro

* Apply edits to js_usage

* Apply edits to js_setup

* update tutorials to apply data type change

* Modify tutorials

* add core tutorials

* delete MatVector elements and delete useless set operation

* add tutorials_objdec_camera

* Add instructions for WebAssembly

* apply tech writer's feedbacks into tutorials

* Organize white list by modules

* Change size to method and bind to MatExpr.size()

Fix #177

* improve tutorials

* Modify core tutorials

* add params list and explanations for OpenCV.js functions

* remove face_profile from Face Detection in Video Capture

* Add demos link

* Change Gui to GUI

* Update js_intro based on Moh and Sajjad's edits

* Fixup for 3.3.0 rebase

* Update js_intro per Moh's suggestion

* Update contributors list per Moh's idea

* add adapter.js in video_display tutorial

* Change Mat.getRoiRect to Mat.roi

Fix #194

* Remove unnecessary files for test

Fix #192

* Licenses updated to UC BSD 3-Clause

* Apply OpenCV coding style for C++ files

* Add OpenCV license for python and js files

* Fix coding style issue in helpers.js

* Remove unused test_commons.js

* Fix coding style of test_imgproc.js

* Fix coding style of test_mat.js

* Fix space before semicolon

* Fix coding style of test_objdetect.js

* Fix coding style of tests.js

* Fix coding style of test_utils.js

* Fix coding style of test_video.js

* Fix failures of node.js tests

* Add eslint rule config and fix eslint errors

* Add eslint config for js/src and fix eslint errors

* Clean up the opencv.js dependencies

Fix #186

* Fix build issue for python generator

* Fix doxygen buildbot failure

* delete trailing whitespace, blank line at EOF and replace tab with space

* Fix tutorial_js_root reference issue for non opencv.js build

* replace the file with small size

* Initial commit of build_js.py

* Move the js build configurations to build script

* Add wasm build support

* Update OpenCV.js build tutorial by using script

* Fix global var issue in tests

* Add a README.md for build_js.py

* Copy the haar cascade files from data dir for tutorials

* Not use memory init file

* Disable debug print for modules/js/CMakeLists.txt

* Check files when build done

* Fix image name in js_gradients tutorial

* Fix image load issue in js_trackbar tutorial

* Find the opencv source directory via relative path by default

* Make the cmake args based on build_doc option

* Fix a typo in js_setup.markdown

* Fix make failure issue on config generated by build_js.py

* Eliminate js branch of hdr_parser.py

* Extract examples from js_basic_ops tutorial

* Fix coding style of utils.js

* Improve examples error handling

Handle:
1. opencv.js loading errors
2. script errors (Error)
3. cv::Exception

Fix #217

* Add enable_exception option into build_js.py

* Support print exception for exception catching disabled build

* Extract example from js_usage tutorial

* Avoid copying .eslintrc.json when building doc

Fix #223

* Revert to use onload as opencv.js ready event

* Use 4 spaces indention for js examples

* embed html in tutorials with iframe tag

* Revert to use onload as opencv.js ready event

* Extract examples from js_video_display tutorial

* Implement Utils object

* modify core imgprc and face_detection tutorials

* Fix examples of js_gui tutorials

* Fix coding style of utils.js

* Modify tutorials

* Extract example from js_face_detection_camera tutorial

* Disable new-cap check in eslint

* Extract examples from js_meanshift tutorial

* Extract examples from video tutorials

* Remove new-cap declaration and update grammer in comments

* Change textarea width to 100 to align with eslint config

* Fix printError issue when opencv.js loading fails

* Remove BUILD_opencv_js dependency for doc build

Fix #213

* Expose cv::getBuildInformation

* Dump opencv build info when opencv.js loaded for live examples

* Make the button to stand out in js live examples

Fix #235

* Style for disabled button

* Add js_imgproc_camera.html example

* Fix coding style of imgproc_camera example

* Add js_imgproc_camera tutorial

* Remove link to opencv.js demos

* doc: copy opencv.js on build, use absolute paths for assets

* doc: reuse existed file box.mp4
This commit is contained in:
Congxiang Pan
2017-09-25 21:52:07 +08:00
committed by Alexander Alekhin
parent b143f7100a
commit 89b6e68e1e
166 changed files with 15406 additions and 10 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ ocv_add_dispatched_file(stat SSE4_2 AVX2)
ocv_add_module(core
OPTIONAL opencv_cudev
WRAP java python)
WRAP java python js)
set(extra_libs "")
+1 -1
View File
@@ -1,3 +1,3 @@
set(the_description "Image Processing")
ocv_add_dispatched_file(accum SSE2 AVX NEON)
ocv_define_module(imgproc opencv_core WRAP java python)
ocv_define_module(imgproc opencv_core WRAP java python js)
+125
View File
@@ -0,0 +1,125 @@
# ----------------------------------------------------------------------------
# CMake file for js support
# ----------------------------------------------------------------------------
# message(STATUS "---------------- Start of JavaScript module ----------------------")
set(the_description "The js bindings")
set(MODULE_NAME js)
set(OPENCV_JS "opencv.js")
ocv_add_module(${MODULE_NAME} BINDINGS)
# TODO: add emscripten path
ocv_module_include_directories()
# get list of modules to wrap
# message(STATUS "Wrapped in ${MODULE_NAME}:")
set(OPENCV_JS_MODULES)
foreach(m ${OPENCV_MODULES_BUILD})
if (";${OPENCV_MODULE_${m}_WRAPPERS};" MATCHES ";${MODULE_NAME};" AND HAVE_${m})
list(APPEND OPENCV_JS_MODULES ${m})
# message(STATUS "\t${m}")
endif()
endforeach()
set(opencv_hdrs "")
foreach(m ${OPENCV_JS_MODULES})
list(APPEND opencv_hdrs ${OPENCV_MODULE_${m}_HEADERS})
endforeach(m)
# header blacklist
ocv_list_filterout(opencv_hdrs "modules/.*.h$")
ocv_list_filterout(opencv_hdrs "modules/core/.*/cuda")
ocv_list_filterout(opencv_hdrs "modules/core/include/opencv2/core/opengl.hpp")
ocv_list_filterout(opencv_hdrs "modules/core/include/opencv2/core/ocl.hpp")
ocv_list_filterout(opencv_hdrs "modules/cuda.*")
ocv_list_filterout(opencv_hdrs "modules/cudev")
ocv_list_filterout(opencv_hdrs "modules/core/.*/hal/")
ocv_list_filterout(opencv_hdrs "modules/.*/detection_based_tracker.hpp") # Conditional compilation
ocv_list_filterout(opencv_hdrs "modules/core/include/opencv2/core/utils/trace.*.hpp")
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/headers.txt" "${opencv_hdrs}")
set(bindings_cpp "${CMAKE_CURRENT_BINARY_DIR}/bindings.cpp")
set(scripts_hdr_parser "${CMAKE_CURRENT_SOURCE_DIR}/../python/src2/hdr_parser.py")
set(JS_HELPER "${CMAKE_CURRENT_SOURCE_DIR}/src/helpers.js")
add_custom_command(
OUTPUT ${bindings_cpp}
COMMAND ${PYTHON_DEFAULT_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src/embindgen.py" ${scripts_hdr_parser} ${bindings_cpp} "${CMAKE_CURRENT_BINARY_DIR}/headers.txt" "${CMAKE_CURRENT_SOURCE_DIR}/src/core_bindings.cpp"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/core_bindings.cpp
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/embindgen.py
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/templates.py
DEPENDS ${scripts_hdr_parser}
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/headers.txt
DEPENDS ${opencv_hdrs}
DEPENDS ${JS_HELPER})
add_definitions("-std=c++11")
link_libraries(${OPENCV_MODULE_${the_module}_DEPS})
ocv_add_executable(${the_module} ${bindings_cpp})
set_target_properties(${the_module} PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes")
set_target_properties(${the_module} PROPERTIES LINK_FLAGS "--memory-init-file 0 -s TOTAL_MEMORY=134217728 -s ALLOW_MEMORY_GROWTH=1 -s MODULARIZE=1 -s EXPORT_NAME=\"'cv'\" -s DEMANGLE_SUPPORT=1 -s FORCE_FILESYSTEM=1 --use-preload-plugins --bind --post-js ${JS_HELPER} -Wno-missing-prototypes")
# add UMD wrapper
set(MODULE_JS_PATH "${OpenCV_BINARY_DIR}/bin/${the_module}.js")
set(OCV_JS_PATH "${OpenCV_BINARY_DIR}/bin/${OPENCV_JS}")
add_custom_command(
OUTPUT ${OCV_JS_PATH}
COMMAND ${PYTHON_DEFAULT_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src/make_umd.py" ${MODULE_JS_PATH} "${OCV_JS_PATH}"
DEPENDS ${the_module}
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/make_umd.py")
add_custom_target(${OPENCV_JS} ALL
DEPENDS ${OCV_JS_PATH}
DEPENDS ${the_module})
# test
set(opencv_test_js_bin_dir "${EXECUTABLE_OUTPUT_PATH}")
set(test_dir ${CMAKE_CURRENT_SOURCE_DIR}/test)
set(opencv_test_js_file_deps "")
# message(STATUS "${opencv_test_js_bin_dir}")
# make sure the build directory exists
file(MAKE_DIRECTORY "${opencv_test_js_bin_dir}")
# gather and copy specific files for js test
file(GLOB_RECURSE test_files RELATIVE "${test_dir}" "${test_dir}/*")
foreach(f ${test_files})
# message(STATUS "copy ${test_dir}/${f} ${opencv_test_js_bin_dir}/${f}")
add_custom_command(OUTPUT "${opencv_test_js_bin_dir}/${f}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${test_dir}/${f}" "${opencv_test_js_bin_dir}/${f}"
DEPENDS "${test_dir}/${f}"
COMMENT "Copying ${f}"
)
list(APPEND opencv_test_js_file_deps "${test_dir}/${f}" "${opencv_test_js_bin_dir}/${f}")
endforeach()
# copy test data
set(test_data "haarcascade_frontalface_default.xml")
set(test_data_path "${PROJECT_SOURCE_DIR}/../../data/haarcascades/${test_data}")
add_custom_command(OUTPUT "${opencv_test_js_bin_dir}/${test_data}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${test_data_path}" "${opencv_test_js_bin_dir}/${test_data}"
DEPENDS "${test_data_path}"
COMMENT "Copying ${test_data}"
)
list(APPEND opencv_test_js_file_deps "${test_data_path}" "${opencv_test_js_bin_dir}/${test_data}")
add_custom_target(${PROJECT_NAME}_test ALL
DEPENDS ${OCV_JS_PATH} ${opencv_test_js_file_deps})
unset(MODULE_NAME)
# message(STATUS "---------------- End of JavaScript module ----------------------")
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "google",
"parserOptions": {
"ecmaVersion": 6
},
"rules": {
"max-len": ["error", 100, {"ignoreUrls": true}],
"quotes": ["error", "single"],
"indent": ["error", 4, {"ArrayExpression": "first",
"CallExpression": {"arguments": "first"},
"SwitchCase": 1}],
"no-var": "off",
"prefer-rest-params": "off",
"require-jsdoc": "off"
}
}
+587
View File
@@ -0,0 +1,587 @@
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
//M*/
/*M///////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//M*/
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/objdetect.hpp"
#include <emscripten/bind.h>
using namespace emscripten;
using namespace cv;
namespace binding_utils
{
template<typename T>
emscripten::val matData(const cv::Mat& mat)
{
return emscripten::val(emscripten::memory_view<T>((mat.total()*mat.elemSize())/sizeof(T),
(T*)mat.data));
}
template<typename T>
emscripten::val matPtr(const cv::Mat& mat, int i)
{
return emscripten::val(emscripten::memory_view<T>(mat.step1(0), mat.ptr<T>(i)));
}
template<typename T>
emscripten::val matPtr(const cv::Mat& mat, int i, int j)
{
return emscripten::val(emscripten::memory_view<T>(mat.step1(1), mat.ptr<T>(i,j)));
}
cv::Mat* createMat(int rows, int cols, int type, intptr_t data, size_t step)
{
return new cv::Mat(rows, cols, type, reinterpret_cast<void*>(data), step);
}
static emscripten::val getMatSize(const cv::Mat& mat)
{
emscripten::val size = emscripten::val::array();
for (int i = 0; i < mat.dims; i++) {
size.call<void>("push", mat.size[i]);
}
return size;
}
static emscripten::val getMatStep(const cv::Mat& mat)
{
emscripten::val step = emscripten::val::array();
for (int i = 0; i < mat.dims; i++) {
step.call<void>("push", mat.step[i]);
}
return step;
}
static Mat matEye(int rows, int cols, int type)
{
return Mat(cv::Mat::eye(rows, cols, type));
}
static Mat matEye(Size size, int type)
{
return Mat(cv::Mat::eye(size, type));
}
void convertTo(const Mat& obj, Mat& m, int rtype, double alpha, double beta)
{
obj.convertTo(m, rtype, alpha, beta);
}
void convertTo(const Mat& obj, Mat& m, int rtype)
{
obj.convertTo(m, rtype);
}
void convertTo(const Mat& obj, Mat& m, int rtype, double alpha)
{
obj.convertTo(m, rtype, alpha);
}
Size matSize(const cv::Mat& mat)
{
return mat.size();
}
cv::Mat matZeros(int arg0, int arg1, int arg2)
{
return cv::Mat::zeros(arg0, arg1, arg2);
}
cv::Mat matZeros(cv::Size arg0, int arg1)
{
return cv::Mat::zeros(arg0,arg1);
}
cv::Mat matOnes(int arg0, int arg1, int arg2)
{
return cv::Mat::ones(arg0, arg1, arg2);
}
cv::Mat matOnes(cv::Size arg0, int arg1)
{
return cv::Mat::ones(arg0, arg1);
}
double matDot(const cv::Mat& obj, const Mat& mat)
{
return obj.dot(mat);
}
Mat matMul(const cv::Mat& obj, const Mat& mat, double scale)
{
return Mat(obj.mul(mat, scale));
}
Mat matT(const cv::Mat& obj)
{
return Mat(obj.t());
}
Mat matInv(const cv::Mat& obj, int type)
{
return Mat(obj.inv(type));
}
void matCopyTo(const cv::Mat& obj, cv::Mat& mat)
{
return obj.copyTo(mat);
}
void matCopyTo(const cv::Mat& obj, cv::Mat& mat, const cv::Mat& mask)
{
return obj.copyTo(mat, mask);
}
Mat matDiag(const cv::Mat& obj, int d)
{
return obj.diag(d);
}
Mat matDiag(const cv::Mat& obj)
{
return obj.diag();
}
void matSetTo(cv::Mat& obj, const cv::Scalar& s)
{
obj.setTo(s);
}
void matSetTo(cv::Mat& obj, const cv::Scalar& s, const cv::Mat& mask)
{
obj.setTo(s, mask);
}
emscripten::val rotatedRectPoints(const cv::RotatedRect& obj)
{
cv::Point2f points[4];
obj.points(points);
emscripten::val pointsArray = emscripten::val::array();
for (int i = 0; i < 4; i++) {
pointsArray.call<void>("push", points[i]);
}
return pointsArray;
}
Rect rotatedRectBoundingRect(const cv::RotatedRect& obj)
{
return obj.boundingRect();
}
Rect2f rotatedRectBoundingRect2f(const cv::RotatedRect& obj)
{
return obj.boundingRect2f();
}
int cvMatDepth(int flags)
{
return CV_MAT_DEPTH(flags);
}
class MinMaxLoc
{
public:
double minVal;
double maxVal;
Point minLoc;
Point maxLoc;
};
MinMaxLoc minMaxLoc(const cv::Mat& src, const cv::Mat& mask)
{
MinMaxLoc result;
cv::minMaxLoc(src, &result.minVal, &result.maxVal, &result.minLoc, &result.maxLoc, mask);
return result;
}
MinMaxLoc minMaxLoc_1(const cv::Mat& src)
{
MinMaxLoc result;
cv::minMaxLoc(src, &result.minVal, &result.maxVal, &result.minLoc, &result.maxLoc);
return result;
}
class Circle
{
public:
Point2f center;
float radius;
};
Circle minEnclosingCircle(const cv::Mat& points)
{
Circle circle;
cv::minEnclosingCircle(points, circle.center, circle.radius);
return circle;
}
emscripten::val CamShiftWrapper(const cv::Mat& arg1, Rect& arg2, TermCriteria arg3)
{
RotatedRect rotatedRect = cv::CamShift(arg1, arg2, arg3);
emscripten::val result = emscripten::val::array();
result.call<void>("push", rotatedRect);
result.call<void>("push", arg2);
return result;
}
emscripten::val meanShiftWrapper(const cv::Mat& arg1, Rect& arg2, TermCriteria arg3)
{
int n = cv::meanShift(arg1, arg2, arg3);
emscripten::val result = emscripten::val::array();
result.call<void>("push", n);
result.call<void>("push", arg2);
return result;
}
std::string getExceptionMsg(const cv::Exception& e) {
return e.msg;
}
void setExceptionMsg(cv::Exception& e, std::string msg) {
e.msg = msg;
return;
}
cv::Exception exceptionFromPtr(intptr_t ptr) {
return *reinterpret_cast<cv::Exception*>(ptr);
}
std::string getBuildInformation() {
return cv::getBuildInformation();
}
}
EMSCRIPTEN_BINDINGS(binding_utils)
{
register_vector<int>("IntVector");
register_vector<float>("FloatVector");
register_vector<double>("DoubleVector");
register_vector<cv::Point>("PointVector");
register_vector<cv::Mat>("MatVector");
register_vector<cv::Rect>("RectVector");
emscripten::class_<cv::Mat>("Mat")
.constructor<>()
.constructor<const Mat&>()
.constructor<Size, int>()
.constructor<int, int, int>()
.constructor<int, int, int, const Scalar&>()
.constructor(&binding_utils::createMat, allow_raw_pointers())
.class_function("eye", select_overload<Mat(int, int, int)>(&binding_utils::matEye))
.class_function("eye", select_overload<Mat(Size, int)>(&binding_utils::matEye))
.class_function("ones", select_overload<Mat(int, int, int)>(&binding_utils::matOnes))
.class_function("ones", select_overload<Mat(Size, int)>(&binding_utils::matOnes))
.class_function("zeros", select_overload<Mat(int, int, int)>(&binding_utils::matZeros))
.class_function("zeros", select_overload<Mat(Size, int)>(&binding_utils::matZeros))
.property("rows", &cv::Mat::rows)
.property("cols", &cv::Mat::cols)
.property("matSize", &binding_utils::getMatSize)
.property("step", &binding_utils::getMatStep)
.property("data", &binding_utils::matData<unsigned char>)
.property("data8S", &binding_utils::matData<char>)
.property("data16U", &binding_utils::matData<unsigned short>)
.property("data16S", &binding_utils::matData<short>)
.property("data32S", &binding_utils::matData<int>)
.property("data32F", &binding_utils::matData<float>)
.property("data64F", &binding_utils::matData<double>)
.function("elemSize", select_overload<size_t()const>(&cv::Mat::elemSize))
.function("elemSize1", select_overload<size_t()const>(&cv::Mat::elemSize1))
.function("channels", select_overload<int()const>(&cv::Mat::channels))
.function("convertTo", select_overload<void(const Mat&, Mat&, int, double, double)>(&binding_utils::convertTo))
.function("convertTo", select_overload<void(const Mat&, Mat&, int)>(&binding_utils::convertTo))
.function("convertTo", select_overload<void(const Mat&, Mat&, int, double)>(&binding_utils::convertTo))
.function("total", select_overload<size_t()const>(&cv::Mat::total))
.function("row", select_overload<Mat(int)const>(&cv::Mat::row))
.function("create", select_overload<void(int, int, int)>(&cv::Mat::create))
.function("create", select_overload<void(Size, int)>(&cv::Mat::create))
.function("rowRange", select_overload<Mat(int, int)const>(&cv::Mat::rowRange))
.function("rowRange", select_overload<Mat(const Range&)const>(&cv::Mat::rowRange))
.function("copyTo", select_overload<void(const Mat&, Mat&)>(&binding_utils::matCopyTo))
.function("copyTo", select_overload<void(const Mat&, Mat&, const Mat&)>(&binding_utils::matCopyTo))
.function("type", select_overload<int()const>(&cv::Mat::type))
.function("empty", select_overload<bool()const>(&cv::Mat::empty))
.function("colRange", select_overload<Mat(int, int)const>(&cv::Mat::colRange))
.function("colRange", select_overload<Mat(const Range&)const>(&cv::Mat::colRange))
.function("step1", select_overload<size_t(int)const>(&cv::Mat::step1))
.function("clone", select_overload<Mat()const>(&cv::Mat::clone))
.function("depth", select_overload<int()const>(&cv::Mat::depth))
.function("col", select_overload<Mat(int)const>(&cv::Mat::col))
.function("dot", select_overload<double(const Mat&, const Mat&)>(&binding_utils::matDot))
.function("mul", select_overload<Mat(const Mat&, const Mat&, double)>(&binding_utils::matMul))
.function("inv", select_overload<Mat(const Mat&, int)>(&binding_utils::matInv))
.function("t", select_overload<Mat(const Mat&)>(&binding_utils::matT))
.function("roi", select_overload<Mat(const Rect&)const>(&cv::Mat::operator()))
.function("diag", select_overload<Mat(const Mat&, int)>(&binding_utils::matDiag))
.function("diag", select_overload<Mat(const Mat&)>(&binding_utils::matDiag))
.function("isContinuous", select_overload<bool()const>(&cv::Mat::isContinuous))
.function("setTo", select_overload<void(Mat&, const Scalar&)>(&binding_utils::matSetTo))
.function("setTo", select_overload<void(Mat&, const Scalar&, const Mat&)>(&binding_utils::matSetTo))
.function("size", select_overload<Size(const Mat&)>(&binding_utils::matSize))
.function("ptr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<unsigned char>))
.function("ptr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<unsigned char>))
.function("ucharPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<unsigned char>))
.function("ucharPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<unsigned char>))
.function("charPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<char>))
.function("charPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<char>))
.function("shortPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<short>))
.function("shortPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<short>))
.function("ushortPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<unsigned short>))
.function("ushortPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<unsigned short>))
.function("intPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<int>))
.function("intPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<int>))
.function("floatPtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<float>))
.function("floatPtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<float>))
.function("doublePtr", select_overload<val(const Mat&, int)>(&binding_utils::matPtr<double>))
.function("doublePtr", select_overload<val(const Mat&, int, int)>(&binding_utils::matPtr<double>))
.function("charAt", select_overload<char&(int)>(&cv::Mat::at<char>))
.function("charAt", select_overload<char&(int, int)>(&cv::Mat::at<char>))
.function("charAt", select_overload<char&(int, int, int)>(&cv::Mat::at<char>))
.function("ucharAt", select_overload<unsigned char&(int)>(&cv::Mat::at<unsigned char>))
.function("ucharAt", select_overload<unsigned char&(int, int)>(&cv::Mat::at<unsigned char>))
.function("ucharAt", select_overload<unsigned char&(int, int, int)>(&cv::Mat::at<unsigned char>))
.function("shortAt", select_overload<short&(int)>(&cv::Mat::at<short>))
.function("shortAt", select_overload<short&(int, int)>(&cv::Mat::at<short>))
.function("shortAt", select_overload<short&(int, int, int)>(&cv::Mat::at<short>))
.function("ushortAt", select_overload<unsigned short&(int)>(&cv::Mat::at<unsigned short>))
.function("ushortAt", select_overload<unsigned short&(int, int)>(&cv::Mat::at<unsigned short>))
.function("ushortAt", select_overload<unsigned short&(int, int, int)>(&cv::Mat::at<unsigned short>))
.function("intAt", select_overload<int&(int)>(&cv::Mat::at<int>) )
.function("intAt", select_overload<int&(int, int)>(&cv::Mat::at<int>) )
.function("intAt", select_overload<int&(int, int, int)>(&cv::Mat::at<int>) )
.function("floatAt", select_overload<float&(int)>(&cv::Mat::at<float>))
.function("floatAt", select_overload<float&(int, int)>(&cv::Mat::at<float>))
.function("floatAt", select_overload<float&(int, int, int)>(&cv::Mat::at<float>))
.function("doubleAt", select_overload<double&(int, int, int)>(&cv::Mat::at<double>))
.function("doubleAt", select_overload<double&(int)>(&cv::Mat::at<double>))
.function("doubleAt", select_overload<double&(int, int)>(&cv::Mat::at<double>));
emscripten::value_object<cv::Range>("Range")
.field("start", &cv::Range::start)
.field("end", &cv::Range::end);
emscripten::value_object<cv::TermCriteria>("TermCriteria")
.field("type", &cv::TermCriteria::type)
.field("maxCount", &cv::TermCriteria::maxCount)
.field("epsilon", &cv::TermCriteria::epsilon);
#define EMSCRIPTEN_CV_SIZE(type) \
emscripten::value_object<type>("#type") \
.field("width", &type::width) \
.field("height", &type::height);
EMSCRIPTEN_CV_SIZE(Size)
EMSCRIPTEN_CV_SIZE(Size2f)
#define EMSCRIPTEN_CV_POINT(type) \
emscripten::value_object<type>("#type") \
.field("x", &type::x) \
.field("y", &type::y); \
EMSCRIPTEN_CV_POINT(Point)
EMSCRIPTEN_CV_POINT(Point2f)
#define EMSCRIPTEN_CV_RECT(type, name) \
emscripten::value_object<cv::Rect_<type>> (name) \
.field("x", &cv::Rect_<type>::x) \
.field("y", &cv::Rect_<type>::y) \
.field("width", &cv::Rect_<type>::width) \
.field("height", &cv::Rect_<type>::height);
EMSCRIPTEN_CV_RECT(int, "Rect")
EMSCRIPTEN_CV_RECT(float, "Rect2f")
emscripten::value_object<cv::RotatedRect>("RotatedRect")
.field("center", &cv::RotatedRect::center)
.field("size", &cv::RotatedRect::size)
.field("angle", &cv::RotatedRect::angle);
function("rotatedRectPoints", select_overload<emscripten::val(const cv::RotatedRect&)>(&binding_utils::rotatedRectPoints));
function("rotatedRectBoundingRect", select_overload<Rect(const cv::RotatedRect&)>(&binding_utils::rotatedRectBoundingRect));
function("rotatedRectBoundingRect2f", select_overload<Rect2f(const cv::RotatedRect&)>(&binding_utils::rotatedRectBoundingRect2f));
emscripten::value_array<cv::Scalar_<double>> ("Scalar")
.element(index<0>())
.element(index<1>())
.element(index<2>())
.element(index<3>());
emscripten::value_object<binding_utils::MinMaxLoc>("MinMaxLoc")
.field("minVal", &binding_utils::MinMaxLoc::minVal)
.field("maxVal", &binding_utils::MinMaxLoc::maxVal)
.field("minLoc", &binding_utils::MinMaxLoc::minLoc)
.field("maxLoc", &binding_utils::MinMaxLoc::maxLoc);
emscripten::value_object<binding_utils::Circle>("Circle")
.field("center", &binding_utils::Circle::center)
.field("radius", &binding_utils::Circle::radius);
emscripten::value_object<cv::Moments >("Moments")
.field("m00", &cv::Moments::m00)
.field("m10", &cv::Moments::m10)
.field("m01", &cv::Moments::m01)
.field("m20", &cv::Moments::m20)
.field("m11", &cv::Moments::m11)
.field("m02", &cv::Moments::m02)
.field("m30", &cv::Moments::m30)
.field("m21", &cv::Moments::m21)
.field("m12", &cv::Moments::m12)
.field("m03", &cv::Moments::m03)
.field("mu20", &cv::Moments::mu20)
.field("mu11", &cv::Moments::mu11)
.field("mu02", &cv::Moments::mu02)
.field("mu30", &cv::Moments::mu30)
.field("mu21", &cv::Moments::mu21)
.field("mu12", &cv::Moments::mu12)
.field("mu03", &cv::Moments::mu03)
.field("nu20", &cv::Moments::nu20)
.field("nu11", &cv::Moments::nu11)
.field("nu02", &cv::Moments::nu02)
.field("nu30", &cv::Moments::nu30)
.field("nu21", &cv::Moments::nu21)
.field("nu12", &cv::Moments::nu12)
.field("nu03", &cv::Moments::nu03);
emscripten::value_object<cv::Exception>("Exception")
.field("code", &cv::Exception::code)
.field("msg", &binding_utils::getExceptionMsg, &binding_utils::setExceptionMsg);
function("exceptionFromPtr", &binding_utils::exceptionFromPtr, allow_raw_pointers());
function("minEnclosingCircle", select_overload<binding_utils::Circle(const cv::Mat&)>(&binding_utils::minEnclosingCircle));
function("minMaxLoc", select_overload<binding_utils::MinMaxLoc(const cv::Mat&, const cv::Mat&)>(&binding_utils::minMaxLoc));
function("minMaxLoc", select_overload<binding_utils::MinMaxLoc(const cv::Mat&)>(&binding_utils::minMaxLoc_1));
function("morphologyDefaultBorderValue", &cv::morphologyDefaultBorderValue);
function("CV_MAT_DEPTH", &binding_utils::cvMatDepth);
function("CamShift", select_overload<emscripten::val(const cv::Mat&, Rect&, TermCriteria)>(&binding_utils::CamShiftWrapper));
function("meanShift", select_overload<emscripten::val(const cv::Mat&, Rect&, TermCriteria)>(&binding_utils::meanShiftWrapper));
function("getBuildInformation", &binding_utils::getBuildInformation);
constant("CV_8UC1", CV_8UC1);
constant("CV_8UC2", CV_8UC2);
constant("CV_8UC3", CV_8UC3);
constant("CV_8UC4", CV_8UC4);
constant("CV_8SC1", CV_8SC1);
constant("CV_8SC2", CV_8SC2);
constant("CV_8SC3", CV_8SC3);
constant("CV_8SC4", CV_8SC4);
constant("CV_16UC1", CV_16UC1);
constant("CV_16UC2", CV_16UC2);
constant("CV_16UC3", CV_16UC3);
constant("CV_16UC4", CV_16UC4);
constant("CV_16SC1", CV_16SC1);
constant("CV_16SC2", CV_16SC2);
constant("CV_16SC3", CV_16SC3);
constant("CV_16SC4", CV_16SC4);
constant("CV_32SC1", CV_32SC1);
constant("CV_32SC2", CV_32SC2);
constant("CV_32SC3", CV_32SC3);
constant("CV_32SC4", CV_32SC4);
constant("CV_32FC1", CV_32FC1);
constant("CV_32FC2", CV_32FC2);
constant("CV_32FC3", CV_32FC3);
constant("CV_32FC4", CV_32FC4);
constant("CV_64FC1", CV_64FC1);
constant("CV_64FC2", CV_64FC2);
constant("CV_64FC3", CV_64FC3);
constant("CV_64FC4", CV_64FC4);
constant("CV_8U", CV_8U);
constant("CV_8S", CV_8S);
constant("CV_16U", CV_16U);
constant("CV_16S", CV_16S);
constant("CV_32S", CV_32S);
constant("CV_32F", CV_32F);
constant("CV_64F", CV_64F);
constant("INT_MIN", INT_MIN);
constant("INT_MAX", INT_MAX);
}
+920
View File
@@ -0,0 +1,920 @@
###############################################################################
#
# 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.
#
###############################################################################
# AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
#
# LICENSE AGREEMENT
# Copyright (c) 2015, 2015 The Regents of the University of California (Regents)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions 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.
# 3. Neither the name of the University nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY 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 COPYRIGHT OWNER 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.
###############################################################################
from __future__ import print_function
import sys, re, os
from templates import *
from sets import Set
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
func_table = {}
# Ignore these functions due to Embind limitations for now
ignore_list = ['locate', #int&
'minEnclosingCircle', #float&
'checkRange',
'minMaxLoc', #double*
'floodFill',
'phaseCorrelate',
'randShuffle',
'calibrationMatrixValues', #double&
'undistortPoints', # global redefinition
'CamShift', #Rect&
'meanShift' #Rect&
]
# Classes and methods whitelist
core = {'': ['absdiff', 'add', 'addWeighted', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'cartToPolar',\
'compare', 'convertScaleAbs', 'copyMakeBorder', 'countNonZero', 'determinant', 'dft', 'divide', 'eigen', \
'exp', 'flip', 'getOptimalDFTSize','gemm', 'hconcat', 'inRange', 'invert', 'kmeans', 'log', 'magnitude', \
'max', 'mean', 'meanStdDev', 'merge', 'min', 'minMaxLoc', 'mixChannels', 'multiply', 'norm', 'normalize', \
'perspectiveTransform', 'polarToCart', 'pow', 'randn', 'randu', 'reduce', 'repeat', 'setIdentity', 'setRNGSeed', \
'solve', 'solvePoly', 'split', 'sqrt', 'subtract', 'trace', 'transform', 'transpose', 'vconcat'],
'Algorithm': []}
imgproc = {'': ['Canny', 'GaussianBlur', 'Laplacian', 'HoughLines', 'HoughLinesP', 'HoughCircles', 'Scharr','Sobel', \
'adaptiveThreshold','approxPolyDP','arcLength','bilateralFilter','blur','boundingRect','boxFilter',\
'calcBackProject','calcHist','circle','compareHist','connectedComponents','connectedComponentsWithStats', \
'contourArea', 'convexHull', 'convexityDefects', 'cornerHarris','cornerMinEigenVal','createCLAHE', \
'createLineSegmentDetector','cvtColor','demosaicing','dilate', 'distanceTransform','distanceTransformWithLabels', \
'drawContours','ellipse','ellipse2Poly','equalizeHist','erode', 'filter2D', 'findContours','fitEllipse', \
'fitLine', 'floodFill','getAffineTransform', 'getPerspectiveTransform', 'getRotationMatrix2D', 'getStructuringElement', \
'goodFeaturesToTrack','grabCut','initUndistortRectifyMap', 'integral','integral2', 'isContourConvex', 'line', \
'matchShapes', 'matchTemplate','medianBlur', 'minAreaRect', 'minEnclosingCircle', 'moments', 'morphologyEx', \
'pointPolygonTest', 'putText','pyrDown','pyrUp','rectangle','remap', 'resize','sepFilter2D','threshold', \
'undistort','warpAffine','warpPerspective','watershed'],
'CLAHE': ['apply', 'collectGarbage', 'getClipLimit', 'getTilesGridSize', 'setClipLimit', 'setTilesGridSize']}
objdetect = {'': ['groupRectangles'],
'HOGDescriptor': ['load', 'HOGDescriptor', 'getDefaultPeopleDetector', 'getDaimlerPeopleDetector', 'setSVMDetector', 'detectMultiScale'],
'CascadeClassifier': ['load', 'detectMultiScale2', 'CascadeClassifier', 'detectMultiScale3', 'empty', 'detectMultiScale']}
video = {'': ['CamShift', 'calcOpticalFlowFarneback', 'calcOpticalFlowPyrLK', 'createBackgroundSubtractorMOG2', 'estimateRigidTransform',\
'findTransformECC', 'meanShift'],
'BackgroundSubtractorMOG2': ['BackgroundSubtractorMOG2', 'apply'],
'BackgroundSubtractor': ['apply', 'getBackgroundImage']}
def makeWhiteList(module_list):
wl = {}
for m in module_list:
for k in m.keys():
if k in wl:
wl[k] += m[k]
else:
wl[k] = m[k]
return wl
white_list = makeWhiteList([core, imgproc, objdetect, video])
# Features to be exported
export_enums = False
export_consts = True
with_wrapped_functions = True
with_default_params = True
with_vec_from_js_array = True
wrapper_namespace = "Wrappers"
type_dict = {
'InputArray': 'const cv::Mat&',
'OutputArray': 'cv::Mat&',
'InputOutputArray': 'cv::Mat&',
'InputArrayOfArrays': 'const std::vector<cv::Mat>&',
'OutputArrayOfArrays': 'std::vector<cv::Mat>&',
'String': 'std::string',
'const String&':'const std::string&'
}
def normalize_class_name(name):
return re.sub(r"^cv\.", "", name).replace(".", "_")
class ClassProp(object):
def __init__(self, decl):
self.tp = decl[0].replace("*", "_ptr").strip()
self.name = decl[1]
self.readonly = True
if "/RW" in decl[3]:
self.readonly = False
class ClassInfo(object):
def __init__(self, name, decl=None):
self.cname = name.replace(".", "::")
self.name = self.wname = normalize_class_name(name)
self.ismap = False
self.issimple = False
self.isalgorithm = False
self.methods = {}
self.ext_constructors = {}
self.props = []
self.consts = {}
customname = False
self.jsfuncs = {}
self.constructor_arg_num = Set()
self.has_smart_ptr = False
if decl:
self.bases = decl[1].split()[1:]
if len(self.bases) > 1:
self.bases = [self.bases[0].strip(",")]
# return sys.exit(-1)
if self.bases and self.bases[0].startswith("cv::"):
self.bases[0] = self.bases[0][4:]
if self.bases and self.bases[0] == "Algorithm":
self.isalgorithm = True
for m in decl[2]:
if m.startswith("="):
self.wname = m[1:]
customname = True
elif m == "/Map":
self.ismap = True
elif m == "/Simple":
self.issimple = True
self.props = [ClassProp(p) for p in decl[3]]
if not customname and self.wname.startswith("Cv"):
self.wname = self.wname[2:]
def handle_ptr(tp):
if tp.startswith('Ptr_'):
tp = 'Ptr<' + "::".join(tp.split('_')[1:]) + '>'
return tp
def handle_vector(tp):
if tp.startswith('vector_'):
tp = 'std::vector<' + "::".join(tp.split('_')[1:]) + '>'
return tp
class ArgInfo(object):
def __init__(self, arg_tuple):
self.tp = handle_ptr(arg_tuple[0]).strip()
self.name = arg_tuple[1]
self.defval = arg_tuple[2]
self.isarray = False
self.arraylen = 0
self.arraycvt = None
self.inputarg = True
self.outputarg = False
self.returnarg = False
self.const = False
self.reference = False
for m in arg_tuple[3]:
if m == "/O":
self.inputarg = False
self.outputarg = True
self.returnarg = True
elif m == "/IO":
self.inputarg = True
self.outputarg = True
self.returnarg = True
elif m.startswith("/A"):
self.isarray = True
self.arraylen = m[2:].strip()
elif m.startswith("/CA"):
self.isarray = True
self.arraycvt = m[2:].strip()
elif m == "/C":
self.const = True
elif m == "/Ref":
self.reference = True
if self.tp == "Mat":
if self.outputarg:
self.tp = "cv::Mat&"
elif self.inputarg:
self.tp = "const cv::Mat&"
if self.tp == "vector_Mat":
if self.outputarg:
self.tp = "std::vector<cv::Mat>&"
elif self.inputarg:
self.tp = "const std::vector<cv::Mat>&"
self.tp = handle_vector(self.tp).strip()
if self.const:
self.tp = "const " + self.tp
if self.reference:
self.tp = self.tp + "&"
self.py_inputarg = False
self.py_outputarg = False
class FuncVariant(object):
def __init__(self, class_name, name, decl, is_constructor, is_class_method, is_const, is_virtual, is_pure_virtual, ref_return, const_return):
self.class_name = class_name
self.name = self.wname = name
self.is_constructor = is_constructor
self.is_class_method = is_class_method
self.is_const = is_const
self.is_virtual = is_virtual
self.is_pure_virtual = is_pure_virtual
self.refret = ref_return
self.constret = const_return
self.rettype = handle_vector(handle_ptr(decl[1]).strip()).strip()
if self.rettype == "void":
self.rettype = ""
self.args = []
self.array_counters = {}
for a in decl[3]:
ainfo = ArgInfo(a)
if ainfo.isarray and not ainfo.arraycvt:
c = ainfo.arraylen
c_arrlist = self.array_counters.get(c, [])
if c_arrlist:
c_arrlist.append(ainfo.name)
else:
self.array_counters[c] = [ainfo.name]
self.args.append(ainfo)
class FuncInfo(object):
def __init__(self, class_name, name, cname, namespace, isconstructor):
self.class_name = class_name
self.name = name
self.cname = cname
self.namespace = namespace
self.variants = []
self.is_constructor = isconstructor
def add_variant(self, variant):
self.variants.append(variant)
class Namespace(object):
def __init__(self):
self.funcs = {}
self.enums = {}
self.consts = {}
class JSWrapperGenerator(object):
def __init__(self):
self.bindings = []
self.wrapper_funcs = []
self.classes = {}
self.namespaces = {}
self.enums = {}
self.parser = hdr_parser.CppHeaderParser()
self.class_idx = 0
def add_class(self, stype, name, decl):
class_info = ClassInfo(name, decl)
class_info.decl_idx = self.class_idx
self.class_idx += 1
if class_info.name in self.classes:
print("Generator error: class %s (cpp_name=%s) already exists" \
% (class_info.name, class_info.cname))
sys.exit(-1)
self.classes[class_info.name] = class_info
if class_info.bases:
chunks = class_info.bases[0].split('::')
base = '_'.join(chunks)
while base not in self.classes and len(chunks) > 1:
del chunks[-2]
base = '_'.join(chunks)
if base not in self.classes:
print("Generator error: unable to resolve base %s for %s"
% (class_info.bases[0], class_info.name))
sys.exit(-1)
else:
class_info.bases[0] = "::".join(chunks)
class_info.isalgorithm |= self.classes[base].isalgorithm
def split_decl_name(self, name):
chunks = name.split('.')
namespace = chunks[:-1]
classes = []
while namespace and '.'.join(namespace) not in self.parser.namespaces:
classes.insert(0, namespace.pop())
return namespace, classes, chunks[-1]
def add_enum(self, decl):
name = decl[1]
namespace, classes, val = self.split_decl_name(name)
namespace = '.'.join(namespace)
val = '_'.join(classes + [name])
cname = name.replace('.', '::')
ns = self.namespaces.setdefault(namespace, Namespace())
if name in ns.enums:
print("Generator warning: constant %s (cname=%s) already exists" \
% (name, cname))
# sys.exit(-1)
else:
ns.enums[name] = []
for item in decl[3]:
ns.enums[name].append(item)
def add_const(self, name, decl):
cname = name.replace('.','::')
namespace, classes, name = self.split_decl_name(name)
namespace = '.'.join(namespace)
name = '_'.join(classes+[name])
ns = self.namespaces.setdefault(namespace, Namespace())
if name in ns.consts:
print("Generator error: constant %s (cname=%s) already exists" \
% (name, cname))
sys.exit(-1)
ns.consts[name] = cname
def add_func(self, decl):
namespace, classes, barename = self.split_decl_name(decl[0])
cpp_name = "::".join(namespace + classes + [barename])
name = barename
class_name = ''
bare_class_name = ''
if classes:
class_name = normalize_class_name('.'.join(namespace + classes))
bare_class_name = classes[-1]
namespace = '.'.join(namespace)
is_constructor = name == bare_class_name
is_class_method = False
is_const_method = False
is_virtual_method = False
is_pure_virtual_method = False
const_return = False
ref_return = False
for m in decl[2]:
if m == "/S":
is_class_method = True
elif m == "/C":
is_const_method = True
elif m == "/V":
is_virtual_method = True
elif m == "/PV":
is_pure_virtual_method = True
elif m == "/Ref":
ref_return = True
elif m == "/CRet":
const_return = True
elif m.startswith("="):
name = m[1:]
if class_name:
cpp_name = barename
func_map = self.classes[class_name].methods
else:
func_map = self.namespaces.setdefault(namespace, Namespace()).funcs
func = func_map.setdefault(name, FuncInfo(class_name, name, cpp_name, namespace, is_constructor))
variant = FuncVariant(class_name, name, decl, is_constructor, is_class_method, is_const_method,
is_virtual_method, is_pure_virtual_method, ref_return, const_return)
func.add_variant(variant)
def save(self, path, name, buf):
f = open(path + "/" + name, "wt")
f.write(buf.getvalue())
f.close()
def gen_function_binding_with_wrapper(self, func, class_info):
binding_text = None
wrapper_func_text = None
bindings = []
wrappers = []
for index, variant in enumerate(func.variants):
factory = False
if class_info and 'Ptr<' in variant.rettype:
factory = True
base_class_name = variant.rettype
base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
if base_class_name in self.classes:
self.classes[base_class_name].has_smart_ptr = True
else:
print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead')
self.classes[class_info.name].has_smart_ptr = True
def_args = []
has_def_param = False
# Return type
ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype
if ret_type.startswith('Ptr'): #smart pointer
ptr_type = ret_type.replace('Ptr<', '').replace('>', '')
if ptr_type in type_dict:
ret_type = type_dict[ptr_type]
for key in type_dict:
if key in ret_type:
ret_type = ret_type.replace(key, type_dict[key])
arg_types = []
unwrapped_arg_types = []
for arg in variant.args:
arg_type = None
if arg.tp in type_dict:
arg_type = type_dict[arg.tp]
else:
arg_type = arg.tp
# Add default value
if with_default_params and arg.defval != '':
def_args.append(arg.defval);
arg_types.append(arg_type)
unwrapped_arg_types.append(arg_type)
# Function attribure
func_attribs = ''
if '*' in ''.join(arg_types):
func_attribs += ', allow_raw_pointers()'
if variant.is_pure_virtual:
func_attribs += ', pure_virtual()'
# Wrapper function
wrap_func_name = (func.class_name+"_" if class_info != None else "") + func.name.split("::")[-1] + "_wrapper"
js_func_name = func.name
# TODO: Name functions based wrap directives or based on arguments list
if index > 0:
wrap_func_name += str(index)
js_func_name += str(index)
c_func_name = 'Wrappers::' + wrap_func_name
# Binding template-
raw_arg_names = ['arg' + str(i + 1) for i in range(0, len(variant.args))]
arg_names = []
w_signature = []
casted_arg_types = []
for arg_type, arg_name in zip(arg_types, raw_arg_names):
casted_arg_name = arg_name
if with_vec_from_js_array:
# Only support const vector reference as input parameter
match = re.search(r'const std::vector<(.*)>&', arg_type)
if match:
type_in_vect = match.group(1)
if type_in_vect != 'cv::Mat':
casted_arg_name = 'emscripten::vecFromJSArray<' + type_in_vect + '>(' + arg_name + ')'
arg_type = re.sub(r'std::vector<(.*)>', 'emscripten::val', arg_type)
w_signature.append(arg_type + ' ' + arg_name)
arg_names.append(casted_arg_name)
casted_arg_types.append(arg_type)
arg_types = casted_arg_types
# Argument list, signature
arg_names_casted = [c if a == b else c + '.as<' + a + '>()' for a, b, c in
zip(unwrapped_arg_types, arg_types, arg_names)]
# Add self object to the parameters
if class_info and not factory:
arg_types = [class_info.cname + '&'] + arg_types
w_signature = [class_info.cname + '& arg0 '] + w_signature
for j in range(0, len(def_args) + 1):
postfix = ''
if j > 0:
postfix = '_' + str(j);
###################################
# Wrapper
if factory: # TODO or static
name = class_info.cname+'::' if variant.class_name else ""
cpp_call_text = static_class_call_template.substitute(scope=name,
func=func.cname,
args=', '.join(arg_names[:len(arg_names)-j]))
elif class_info:
cpp_call_text = class_call_template.substitute(obj='arg0',
func=func.cname,
args=', '.join(arg_names[:len(arg_names)-j]))
else:
cpp_call_text = call_template.substitute(func=func.cname,
args=', '.join(arg_names[:len(arg_names)-j]))
wrapper_func_text = wrapper_function_template.substitute(ret_val=ret_type,
func=wrap_func_name+postfix,
signature=', '.join(w_signature[:len(w_signature)-j]),
cpp_call=cpp_call_text,
const='' if variant.is_const else '')
###################################
# Binding
if class_info:
if factory:
# print("Factory Function: ", c_func_name, len(variant.args) - j, class_info.name)
if variant.is_pure_virtual:
# FIXME: workaround for pure virtual in constructor
# e.g. DescriptorMatcher_clone_wrapper
continue
# consider the default parameter variants
args_num = len(variant.args) - j
if args_num in class_info.constructor_arg_num:
# FIXME: workaournd for constructor overload with same args number
# e.g. DescriptorMatcher
continue
class_info.constructor_arg_num.add(args_num)
binding_text = ctr_template.substitute(const='const' if variant.is_const else '',
cpp_name=c_func_name+postfix,
ret=ret_type,
args=','.join(arg_types[:len(arg_types)-j]),
optional=func_attribs)
else:
binding_template = overload_class_static_function_template if variant.is_class_method else \
overload_class_function_template
binding_text = binding_template.substitute(js_name=js_func_name,
const='' if variant.is_const else '',
cpp_name=c_func_name+postfix,
ret=ret_type,
args=','.join(arg_types[:len(arg_types)-j]),
optional=func_attribs)
else:
binding_text = overload_function_template.substitute(js_name=js_func_name,
cpp_name=c_func_name+postfix,
const='const' if variant.is_const else '',
ret=ret_type,
args=', '.join(arg_types[:len(arg_types)-j]),
optional=func_attribs)
bindings.append(binding_text)
wrappers.append(wrapper_func_text)
return [bindings, wrappers]
def gen_function_binding(self, func, class_info):
if not class_info == None :
func_name = class_info.cname+'::'+func.cname
else :
func_name = func.cname
binding_text = None
binding_text_list = []
for index, variant in enumerate(func.variants):
factory = False
#TODO if variant.is_class_method and variant.rettype == ('Ptr<' + class_info.name + '>'):
if (not class_info == None) and variant.rettype == ('Ptr<' + class_info.name + '>') or (func.name.startswith("create") and variant.rettype):
factory = True
base_class_name = variant.rettype
base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
if base_class_name in self.classes:
self.classes[base_class_name].has_smart_ptr = True
else:
print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead')
self.classes[class_info.name].has_smart_ptr = True
# Return type
ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype
ret_type = ret_type.strip()
if ret_type.startswith('Ptr'): #smart pointer
ptr_type = ret_type.replace('Ptr<', '').replace('>', '')
if ptr_type in type_dict:
ret_type = type_dict[ptr_type]
for key in type_dict:
if key in ret_type:
ret_type = ret_type.replace(key, type_dict[key])
if variant.constret and ret_type.startswith('const') == False:
ret_type = 'const ' + ret_type
if variant.refret and ret_type.endswith('&') == False:
ret_type += '&'
arg_types = []
orig_arg_types = []
def_args = []
for arg in variant.args:
if arg.tp in type_dict:
arg_type = type_dict[arg.tp]
else:
arg_type = arg.tp
#if arg.outputarg:
# arg_type += '&'
orig_arg_types.append(arg_type)
if with_default_params and arg.defval != '':
def_args.append(arg.defval)
arg_types.append(orig_arg_types[-1])
# Function attribure
func_attribs = ''
if '*' in ''.join(orig_arg_types):
func_attribs += ', allow_raw_pointers()'
if variant.is_pure_virtual:
func_attribs += ', pure_virtual()'
#TODO better naming
#if variant.name in self.jsfunctions:
#else
js_func_name = variant.name
c_func_name = func.cname if (factory and variant.is_class_method == False) else func_name
################################### Binding
for j in range(0, len(def_args) + 1):
postfix = ''
if j > 0:
postfix = '_' + str(j);
if factory:
binding_text = ctr_template.substitute(const='const' if variant.is_const else '',
cpp_name=c_func_name+postfix,
ret=ret_type,
args=','.join(arg_types[:len(arg_types)-j]),
optional=func_attribs)
else:
binding_template = overload_class_static_function_template if variant.is_class_method else \
overload_function_template if class_info == None else overload_class_function_template
binding_text = binding_template.substitute(js_name=js_func_name,
const='const' if variant.is_const else '',
cpp_name=c_func_name+postfix,
ret=ret_type,
args=','.join(arg_types[:len(arg_types)-1]),
optional=func_attribs)
binding_text_list.append(binding_text)
return binding_text_list
def print_decls(self, decls):
"""
Prints the list of declarations, retrieived by the parse() method
"""
for d in decls:
print(d[0], d[1], ";".join(d[2]))
for a in d[3]:
print(" ", a[0], a[1], a[2], end="")
if a[3]:
print("; ".join(a[3]))
else:
print()
def gen(self, dst_file, src_files, core_bindings):
# step 1: scan the headers and extract classes, enums and functions
for hdr in src_files:
decls = self.parser.parse(hdr)
# print(hdr);
# self.print_decls(decls);
if len(decls) == 0:
continue
for decl in decls:
name = decl[0]
type = name[:name.find(" ")]
if type == "struct" or type == "class": # class/structure case
name = name[name.find(" ") + 1:].strip()
self.add_class(type, name, decl)
elif name.startswith("enum"): # enumerations
self.add_enum(decl)
elif name.startswith("const"):
# constant
self.add_const(name.replace("const ", "").strip(), decl)
else: # class/global function
self.add_func(decl)
# step 2: generate bindings
# Global functions
for ns_name, ns in sorted(self.namespaces.items()):
if ns_name.split('.')[0] != 'cv':
continue
for name, func in sorted(ns.funcs.items()):
if name in ignore_list:
continue
if not name in white_list['']:
continue
ext_cnst = False
# Check if the method is an external constructor
for variant in func.variants:
if "Ptr<" in variant.rettype:
# Register the smart pointer
base_class_name = variant.rettype
base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
self.classes[base_class_name].has_smart_ptr = True
# Adds the external constructor
class_name = func.name.replace("create", "")
if not class_name in self.classes:
self.classes[base_class_name].methods[func.cname] = func
else:
self.classes[class_name].methods[func.cname] = func
ext_cnst = True
if ext_cnst:
continue
if with_wrapped_functions:
binding, wrapper = self.gen_function_binding_with_wrapper(func, class_info=None)
self.bindings += binding
self.wrapper_funcs += wrapper
else:
binding = self.gen_function_binding(func, class_info=None)
self.bindings+=binding
# generate code for the classes and their methods
class_list = list(self.classes.items())
for name, class_info in class_list:
class_bindings = []
if not name in white_list:
continue
# Generate bindings for methods
for method_name, method in class_info.methods.iteritems():
if method.cname in ignore_list:
continue
if not method.name in white_list[method.class_name]:
continue
if method.is_constructor:
for variant in method.variants:
args = []
for arg in variant.args:
args.append(arg.tp)
# print('Constructor: ', class_info.name, len(variant.args))
args_num = len(variant.args)
if args_num in class_info.constructor_arg_num:
continue
class_info.constructor_arg_num.add(args_num)
class_bindings.append(constructor_template.substitute(signature=', '.join(args)))
else:
if with_wrapped_functions and (len(method.variants) > 1 or len(method.variants[0].args)>0 or "String" in method.variants[0].rettype):
binding, wrapper = self.gen_function_binding_with_wrapper(method, class_info=class_info)
self.wrapper_funcs = self.wrapper_funcs + wrapper
class_bindings = class_bindings + binding
else:
binding = self.gen_function_binding(method, class_info=class_info)
class_bindings = class_bindings + binding
# Regiseter Smart pointer
if class_info.has_smart_ptr:
class_bindings.append(smart_ptr_reg_template.substitute(cname=class_info.cname, name=class_info.name))
# Attach external constructors
# for method_name, method in class_info.ext_constructors.iteritems():
# print("ext constructor", method_name)
#if class_info.ext_constructors:
# Generate bindings for properties
for property in class_info.props:
class_bindings.append(class_property_template.substitute(js_name=property.name, cpp_name='::'.join(
[class_info.cname, property.name])))
dv = ''
base = Template("""base<$base$isPoly>""")
assert len(class_info.bases) <= 1 , "multiple inheritance not supported"
if len(class_info.bases) == 1:
dv = "," + base.substitute(base=', '.join(class_info.bases),
isPoly = " ,true" if class_info.name=="Feature2D" else "")
self.bindings.append(class_template.substitute(cpp_name=class_info.cname,
js_name=name,
class_templates=''.join(class_bindings),
derivation=dv))
if export_enums:
# step 4: generate bindings for enums
# TODO anonymous enums are ignored for now.
for ns_name, ns in sorted(self.namespaces.items()):
if ns_name.split('.')[0] != 'cv':
continue
for name, enum in sorted(ns.enums.items()):
if not name.endswith('.anonymous'):
name = name.replace("cv.", "")
enum_values = []
for enum_val in enum:
value = enum_val[0][enum_val[0].rfind(".")+1:]
enum_values.append(enum_item_template.substitute(val=value,
cpp_val=name.replace('.', '::')+'::'+value))
self.bindings.append(enum_template.substitute(cpp_name=name.replace(".", "::"),
js_name=name.replace(".", "_"),
enum_items=''.join(enum_values)))
else:
print(name)
#TODO: represent anonymous enums with constants
if export_consts:
# step 5: generate bindings for consts
for ns_name, ns in sorted(self.namespaces.items()):
if ns_name.split('.')[0] != 'cv':
continue
for name, const in sorted(ns.consts.items()):
# print("Gen consts: ", name, const)
self.bindings.append(const_template.substitute(js_name=name, value=const))
with open(core_bindings) as f:
ret = f.read()
defis = '\n'.join(self.wrapper_funcs)
ret += wrapper_codes_template.substitute(ns=wrapper_namespace, defs=defis)
ret += emscripten_binding_template.substitute(binding_name='testBinding', bindings=''.join(self.bindings))
# print(ret)
text_file = open(dst_file, "w")
text_file.write(ret)
text_file.close()
if __name__ == "__main__":
if len(sys.argv) < 4:
print("Usage:\n", \
os.path.basename(sys.argv[0]), \
"<full path to hdr_parser.py> <bindings.cpp> <headers.txt> <core_bindings.cpp>")
print("Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv]))
exit(0)
dstdir = "."
hdr_parser_path = os.path.abspath(sys.argv[1])
if hdr_parser_path.endswith(".py"):
hdr_parser_path = os.path.dirname(hdr_parser_path)
sys.path.append(hdr_parser_path)
import hdr_parser
bindingsCpp = sys.argv[2]
headers = open(sys.argv[3], 'r').read().split(';')
coreBindings = sys.argv[4]
generator = JSWrapperGenerator()
generator.gen(bindingsCpp, headers, coreBindings)
+399
View File
@@ -0,0 +1,399 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
Module['imread'] = function(imageSource) {
var img = null;
if (typeof imageSource === 'string') {
img = document.getElementById(imageSource);
} else {
img = imageSource;
}
var canvas = null;
var ctx = null;
if (img instanceof HTMLImageElement) {
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
} else if (img instanceof HTMLCanvasElement) {
canvas = img;
ctx = canvas.getContext('2d');
} else {
throw new Error('Please input the valid canvas or img id.');
return;
}
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return cv.matFromImageData(imgData);
};
Module['imshow'] = function(canvasSource, mat) {
var canvas = null;
if (typeof canvasSource === 'string') {
canvas = document.getElementById(canvasSource);
} else {
canvas = canvasSource;
}
if (!(canvas instanceof HTMLCanvasElement)) {
throw new Error('Please input the valid canvas element or id.');
return;
}
if (!(mat instanceof cv.Mat)) {
throw new Error('Please input the valid cv.Mat instance.');
return;
}
// convert the mat type to cv.CV_8U
var img = new cv.Mat();
var depth = mat.type()%8;
var scale = depth <= cv.CV_8S? 1.0 : (depth <= cv.CV_32S? 1.0/256.0 : 255.0);
var shift = (depth === cv.CV_8S || depth === cv.CV_16S)? 128.0 : 0.0;
mat.convertTo(img, cv.CV_8U, scale, shift);
// convert the img type to cv.CV_8UC4
switch (img.type()) {
case cv.CV_8UC1:
cv.cvtColor(img, img, cv.COLOR_GRAY2RGBA);
break;
case cv.CV_8UC3:
cv.cvtColor(img, img, cv.COLOR_RGB2RGBA);
break;
case cv.CV_8UC4:
break;
default:
throw new Error('Bad number of channels (Source image must have 1, 3 or 4 channels)');
return;
}
var imgData = new ImageData(new Uint8ClampedArray(img.data), img.cols, img.rows);
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = imgData.width;
canvas.height = imgData.height;
ctx.putImageData(imgData, 0, 0);
img.delete();
};
Module['VideoCapture'] = function(videoSource) {
var video = null;
if (typeof videoSource === 'string') {
video = document.getElementById(videoSource);
} else {
video = videoSource;
}
if (!(video instanceof HTMLVideoElement)) {
throw new Error('Please input the valid video element or id.');
return;
}
var canvas = document.createElement('canvas');
canvas.width = video.width;
canvas.height = video.height;
var ctx = canvas.getContext('2d');
this.video = video;
this.read = function(frame) {
if (!(frame instanceof cv.Mat)) {
throw new Error('Please input the valid cv.Mat instance.');
return;
}
if (frame.type() !== cv.CV_8UC4) {
throw new Error('Bad type of input mat: the type should be cv.CV_8UC4.');
return;
}
if (frame.cols !== video.width || frame.rows !== video.height) {
throw new Error('Bad size of input mat: the size should be same as the video.');
return;
}
ctx.drawImage(video, 0, 0, video.width, video.height);
frame.data.set(ctx.getImageData(0, 0, video.width, video.height).data);
};
};
function Range(start, end) {
this.start = typeof(start) === 'undefined' ? 0 : start;
this.end = typeof(end) === 'undefined' ? 0 : end;
}
Module['Range'] = Range;
function Point(x, y) {
this.x = typeof(x) === 'undefined' ? 0 : x;
this.y = typeof(y) === 'undefined' ? 0 : y;
}
Module['Point'] = Point;
function Size(width, height) {
this.width = typeof(width) === 'undefined' ? 0 : width;
this.height = typeof(height) === 'undefined' ? 0 : height;
}
Module['Size'] = Size;
function Rect() {
switch (arguments.length) {
case 0: {
// new cv.Rect()
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
break;
}
case 1: {
// new cv.Rect(rect)
var rect = arguments[0];
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
break;
}
case 2: {
// new cv.Rect(point, size)
var point = arguments[0];
var size = arguments[1];
this.x = point.x;
this.y = point.y;
this.width = size.width;
this.height = size.height;
break;
}
case 4: {
// new cv.Rect(x, y, width, height)
this.x = arguments[0];
this.y = arguments[1];
this.width = arguments[2];
this.height = arguments[3];
break;
}
default: {
throw new Error('Invalid arguments');
}
}
}
Module['Rect'] = Rect;
function RotatedRect() {
switch (arguments.length) {
case 0: {
this.center = {x: 0, y: 0};
this.size = {width: 0, height: 0};
this.angle = 0;
break;
}
case 3: {
this.center = arguments[0];
this.size = arguments[1];
this.angle = arguments[2];
break;
}
default: {
throw new Error('Invalid arguments');
}
}
}
RotatedRect.points = function(obj) {
return Module.rotatedRectPoints(obj);
};
RotatedRect.boundingRect = function(obj) {
return Module.rotatedRectBoundingRect(obj);
};
RotatedRect.boundingRect2f = function(obj) {
return Module.rotatedRectBoundingRect2f(obj);
};
Module['RotatedRect'] = RotatedRect;
function Scalar(v0, v1, v2, v3) {
this.push(typeof(v0) === 'undefined' ? 0 : v0);
this.push(typeof(v1) === 'undefined' ? 0 : v1);
this.push(typeof(v2) === 'undefined' ? 0 : v2);
this.push(typeof(v3) === 'undefined' ? 0 : v3);
}
Scalar.prototype = new Array; // eslint-disable-line no-array-constructor
Scalar.all = function(v) {
return new Scalar(v, v, v, v);
};
Module['Scalar'] = Scalar;
function MinMaxLoc() {
switch (arguments.length) {
case 0: {
this.minVal = 0;
this.maxVal = 0;
this.minLoc = new Point();
this.maxLoc = new Point();
break;
}
case 4: {
this.minVal = arguments[0];
this.maxVal = arguments[1];
this.minLoc = arguments[2];
this.maxLoc = arguments[3];
break;
}
default: {
throw new Error('Invalid arguments');
}
}
}
Module['MinMaxLoc'] = MinMaxLoc;
function Circle() {
switch (arguments.length) {
case 0: {
this.center = new Point();
this.radius = 0;
break;
}
case 2: {
this.center = arguments[0];
this.radius = arguments[1];
break;
}
default: {
throw new Error('Invalid arguments');
}
}
}
Module['Circle'] = Circle;
function TermCriteria() {
switch (arguments.length) {
case 0: {
this.type = 0;
this.maxCount = 0;
this.epsilon = 0;
break;
}
case 3: {
this.type = arguments[0];
this.maxCount = arguments[1];
this.epsilon = arguments[2];
break;
}
default: {
throw new Error('Invalid arguments');
}
}
}
Module['TermCriteria'] = TermCriteria;
Module['matFromArray'] = function(rows, cols, type, array) {
var mat = new cv.Mat(rows, cols, type);
switch (type) {
case cv.CV_8U:
case cv.CV_8UC1:
case cv.CV_8UC2:
case cv.CV_8UC3:
case cv.CV_8UC4: {
mat.data.set(array);
break;
}
case cv.CV_8S:
case cv.CV_8SC1:
case cv.CV_8SC2:
case cv.CV_8SC3:
case cv.CV_8SC4: {
mat.data8S.set(array);
break;
}
case cv.CV_16U:
case cv.CV_16UC1:
case cv.CV_16UC2:
case cv.CV_16UC3:
case cv.CV_16UC4: {
mat.data16U.set(array);
break;
}
case cv.CV_16S:
case cv.CV_16SC1:
case cv.CV_16SC2:
case cv.CV_16SC3:
case cv.CV_16SC4: {
mat.data16S.set(array);
break;
}
case cv.CV_32S:
case cv.CV_32SC1:
case cv.CV_32SC2:
case cv.CV_32SC3:
case cv.CV_32SC4: {
mat.data32S.set(array);
break;
}
case cv.CV_32F:
case cv.CV_32FC1:
case cv.CV_32FC2:
case cv.CV_32FC3:
case cv.CV_32FC4: {
mat.data32F.set(array);
break;
}
case cv.CV_64F:
case cv.CV_64FC1:
case cv.CV_64FC2:
case cv.CV_64FC3:
case cv.CV_64FC4: {
mat.data64F.set(array);
break;
}
default: {
throw new Error('Type is unsupported');
}
}
return mat;
};
Module['matFromImageData'] = function(imageData) {
var mat = new cv.Mat(imageData.height, imageData.width, cv.CV_8UC4);
mat.data.set(imageData.data);
return mat;
};
+106
View File
@@ -0,0 +1,106 @@
###############################################################################
#
# 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.
#
###############################################################################
# AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
#
# LICENSE AGREEMENT
# Copyright (c) 2015, 2015 The Regents of the University of California (Regents)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions 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.
# 3. Neither the name of the University nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY 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 COPYRIGHT OWNER 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.
###############################################################################
import os, sys, re, json, shutil
from subprocess import Popen, PIPE, STDOUT
def make_umd(opencvjs, cvjs):
src = open(opencvjs, 'r+b')
dst = open(cvjs, 'w+b')
content = src.read()
dst.seek(0)
# inspired by https://github.com/umdjs/umd/blob/95563fd6b46f06bda0af143ff67292e7f6ede6b7/templates/returnExportsGlobal.js
dst.write(("""
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function () {
return (root.cv = factory());
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals
root.cv = factory();
}
}(this, function () {
%s
if (typeof Module === 'undefined')
Module = {};
return cv(Module);
}));
""" % (content)).lstrip())
if __name__ == "__main__":
if len(sys.argv) > 2:
opencvjs = sys.argv[1]
cvjs = sys.argv[2]
make_umd(opencvjs, cvjs);
+192
View File
@@ -0,0 +1,192 @@
###############################################################################
#
# 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.
#
###############################################################################
# AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
#
# LICENSE AGREEMENT
# Copyright (c) 2015, 2015 The Regents of the University of California (Regents)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions 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.
# 3. Neither the name of the University nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY 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 COPYRIGHT OWNER 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.
##############################################################################
from string import Template
wrapper_codes_template = Template("namespace $ns {\n$defs\n}")
call_template = Template("""$func($args)""")
class_call_template = Template("""$obj.$func($args)""")
static_class_call_template = Template("""$scope$func($args)""")
wrapper_function_template = Template(""" $ret_val $func($signature)$const {
return $cpp_call;
}
""")
wrapper_function_with_def_args_template = Template(""" $ret_val $func($signature)$const {
$check_args
}
""")
wrapper_overload_def_values = [
Template("""return $cpp_call;"""), Template("""if ($arg0.isUndefined())
return $cpp_call;
else
$next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined() && $arg5.isUndefined() )
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined() && $arg5.isUndefined() && $arg6.isUndefined() )
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined() &&
$arg8.isUndefined())
return $cpp_call;
else $next"""),
Template("""if ($arg0.isUndefined() && $arg1.isUndefined() && $arg2.isUndefined() && $arg3.isUndefined() &&
$arg4.isUndefined() && $arg5.isUndefined()&& $arg6.isUndefined() && $arg7.isUndefined()&&
$arg8.isUndefined() && $arg9.isUndefined())
return $cpp_call;
else $next""")]
emscripten_binding_template = Template("""
EMSCRIPTEN_BINDINGS($binding_name) {$bindings
}
""")
simple_function_template = Template("""
emscripten::function("$js_name", &$cpp_name);
""")
smart_ptr_reg_template = Template("""
.smart_ptr<Ptr<$cname>>("Ptr<$name>")
""")
overload_function_template = Template("""
function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional);
""")
overload_class_function_template = Template("""
.function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional)""")
overload_class_static_function_template = Template("""
.class_function("$js_name", select_overload<$ret($args)$const>(&$cpp_name)$optional)""")
class_property_template = Template("""
.property("$js_name", &$cpp_name)""")
ctr_template = Template("""
.constructor(select_overload<$ret($args)$const>(&$cpp_name)$optional)""")
smart_ptr_ctr_overload_template = Template("""
.smart_ptr_constructor("$ptr_type", select_overload<$ret($args)$const>(&$cpp_name)$optional)""")
function_template = Template("""
.function("$js_name", &$cpp_name)""")
static_function_template = Template("""
.class_function("$js_name", &$cpp_name)""")
constructor_template = Template("""
.constructor<$signature>()""")
enum_item_template = Template("""
.value("$val", $cpp_val)""")
enum_template = Template("""
emscripten::enum_<$cpp_name>("$js_name")$enum_items;
""")
const_template = Template("""
constant("$js_name", +$value);
""")
vector_template = Template("""
emscripten::register_vector<$cType>("$js_name");
""")
map_template = Template("""
emscripten::register_map<cpp_type_key,$cpp_type_val>("$js_name");
""")
class_template = Template("""
emscripten::class_<$cpp_name $derivation>("$js_name")$class_templates;
""")
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "google",
"parserOptions": {
"ecmaVersion": 6
},
"rules": {
"max-len": ["error", 100, {"ignoreUrls": true}],
"quotes": ["error", "single"],
"indent": ["error", 4, {"ArrayExpression": "first",
"CallExpression": {"arguments": "first"}}]
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "opencv_js_tests",
"description": "Tests for opencv js bindings",
"version": "1.0.0",
"dependencies" : {
"qunit" : "latest"
},
"devDependencies": {
"eslint" : "latest",
"eslint-config-google" : "latest"
},
"scripts": {
"test": "node tests.js"
},
"repository": {
"type": "git",
"url": "https://github.com/opencv/opencv.git"
},
"keywords": [],
"author": "",
"license": "BSD-4-Clause",
"bugs": {
"url": "https://github.com/opencv/opencv/issues"
},
"homepage": "https://github.com/opencv/opencv"
}
+807
View File
@@ -0,0 +1,807 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
//
// //////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//
if (typeof module !== 'undefined' && module.exports) {
// The envrionment is Node.js
var cv = require('./opencv.js'); // eslint-disable-line no-var
}
QUnit.module('Image Processing', {});
QUnit.test('test_imgProc', function(assert) {
// calcHist
{
let vec1 = new cv.Mat.ones(new cv.Size(20, 20), cv.CV_8UC1); // eslint-disable-line new-cap
let source = new cv.MatVector();
source.push_back(vec1);
let channels = [0];
let histSize = [256];
let ranges =[0, 256];
let hist = new cv.Mat();
let mask = new cv.Mat();
let binSize = cv._malloc(4);
let binView = new Int32Array(cv.HEAP8.buffer, binSize);
binView[0] = 10;
cv.calcHist(source, channels, mask, hist, histSize, ranges, false);
// hist should contains a N X 1 arrary.
let size = hist.size();
assert.equal(size.height, 256);
assert.equal(size.width, 1);
// default parameters
cv.calcHist(source, channels, mask, hist, histSize, ranges);
size = hist.size();
assert.equal(size.height, 256);
assert.equal(size.width, 1);
// Do we need to verify data in histogram?
// let dataView = hist.data;
// Free resource
cv._free(binSize);
mask.delete();
hist.delete();
}
// cvtColor
{
let source = new cv.Mat(10, 10, cv.CV_8UC3);
let dest = new cv.Mat();
cv.cvtColor(source, dest, cv.COLOR_BGR2GRAY, 0);
assert.equal(dest.channels(), 1);
cv.cvtColor(source, dest, cv.COLOR_BGR2GRAY);
assert.equal(dest.channels(), 1);
cv.cvtColor(source, dest, cv.COLOR_BGR2BGRA, 0);
assert.equal(dest.channels(), 4);
cv.cvtColor(source, dest, cv.COLOR_BGR2BGRA);
assert.equal(dest.channels(), 4);
dest.delete();
source.delete();
}
// equalizeHist
{
let source = new cv.Mat(10, 10, cv.CV_8UC1);
let dest = new cv.Mat();
cv.equalizeHist(source, dest);
// eualizeHist changes the content of a image, but does not alter meta data
// of it.
assert.equal(source.channels(), dest.channels());
assert.equal(source.type(), dest.type());
dest.delete();
source.delete();
}
});
QUnit.test('test_segmentation', function(assert) {
const THRESHOLD = 127.0;
const THRESHOLD_MAX = 210.0;
// threshold
{
let source = new cv.Mat(1, 5, cv.CV_8UC1);
let sourceView = source.data;
sourceView[0] = 0; // < threshold
sourceView[1] = 100; // < threshold
sourceView[2] = 200; // > threshold
let dest = new cv.Mat();
cv.threshold(source, dest, THRESHOLD, THRESHOLD_MAX, cv.THRESH_BINARY);
let destView = dest.data;
assert.equal(destView[0], 0);
assert.equal(destView[1], 0);
assert.equal(destView[2], THRESHOLD_MAX);
}
// adaptiveThreshold
{
let source = cv.Mat.zeros(1, 5, cv.CV_8UC1);
let sourceView = source.data;
sourceView[0] = 50;
sourceView[1] = 150;
sourceView[2] = 200;
let dest = new cv.Mat();
const C = 0;
const blockSize = 3;
cv.adaptiveThreshold(source, dest, THRESHOLD_MAX,
cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, blockSize, C);
let destView = dest.data;
assert.equal(destView[0], 0);
assert.equal(destView[1], THRESHOLD_MAX);
assert.equal(destView[2], THRESHOLD_MAX);
}
});
QUnit.test('test_shape', function(assert) {
// moments
{
let points = new cv.Mat(1, 4, cv.CV_32SC2);
let data32S = points.data32S;
data32S[0]=50;
data32S[1]=56;
data32S[2]=53;
data32S[3]=53;
data32S[4]=46;
data32S[5]=54;
data32S[6]=49;
data32S[7]=51;
let m = cv.moments(points, false);
let area = cv.contourArea(points, false);
assert.equal(m.m00, 0);
assert.equal(m.m01, 0);
assert.equal(m.m10, 0);
assert.equal(area, 0);
// default parameters
m = cv.moments(points);
area = cv.contourArea(points);
assert.equal(m.m00, 0);
assert.equal(m.m01, 0);
assert.equal(m.m10, 0);
assert.equal(area, 0);
points.delete();
}
});
QUnit.test('test_min_enclosing', function(assert) {
{
let points = new cv.Mat(4, 1, cv.CV_32FC2);
points.data32F[0] = 0;
points.data32F[1] = 0;
points.data32F[2] = 1;
points.data32F[3] = 0;
points.data32F[4] = 1;
points.data32F[5] = 1;
points.data32F[6] = 0;
points.data32F[7] = 1;
let circle = cv.minEnclosingCircle(points);
assert.deepEqual(circle.center, {x: 0.5, y: 0.5});
assert.ok(Math.abs(circle.radius - Math.sqrt(2) / 2) < 0.001);
points.delete();
}
});
QUnit.test('test_filter', function(assert) {
// blur
{
let mat1 = cv.Mat.ones(5, 5, cv.CV_8UC3);
let mat2 = new cv.Mat();
cv.blur(mat1, mat2, {height: 3, width: 3}, {x: -1, y: -1}, cv.BORDER_DEFAULT);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 5);
assert.equal(size.width, 5);
cv.blur(mat1, mat2, {height: 3, width: 3}, {x: -1, y: -1});
// Verify result.
size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 5);
assert.equal(size.width, 5);
cv.blur(mat1, mat2, {height: 3, width: 3});
// Verify result.
size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 5);
assert.equal(size.width, 5);
mat1.delete();
mat2.delete();
}
// GaussianBlur
{
let mat1 = cv.Mat.ones(7, 7, cv.CV_8UC1);
let mat2 = new cv.Mat();
cv.GaussianBlur(mat1, mat2, new cv.Size(3, 3), 0, 0, // eslint-disable-line new-cap
cv.BORDER_DEFAULT);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 1);
assert.equal(size.height, 7);
assert.equal(size.width, 7);
}
// medianBlur
{
let mat1 = cv.Mat.ones(9, 9, cv.CV_8UC3);
let mat2 = new cv.Mat();
cv.medianBlur(mat1, mat2, 3);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 9);
assert.equal(size.width, 9);
}
// Transpose
{
let mat1 = cv.Mat.eye(9, 9, cv.CV_8UC3);
let mat2 = new cv.Mat();
cv.transpose(mat1, mat2);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 9);
assert.equal(size.width, 9);
}
// bilateralFilter
{
let mat1 = cv.Mat.ones(11, 11, cv.CV_8UC3);
let mat2 = new cv.Mat();
cv.bilateralFilter(mat1, mat2, 3, 6, 1.5, cv.BORDER_DEFAULT);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
// default parameters
cv.bilateralFilter(mat1, mat2, 3, 6, 1.5);
// Verify result.
size = mat2.size();
assert.equal(mat2.channels(), 3);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
mat1.delete();
mat2.delete();
}
// Watershed
{
let mat = cv.Mat.ones(11, 11, cv.CV_8UC3);
let out = new cv.Mat(11, 11, cv.CV_32SC1);
cv.watershed(mat, out);
// Verify result.
let size = out.size();
assert.equal(out.channels(), 1);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
assert.equal(out.elemSize1(), 4);
mat.delete();
out.delete();
}
// Concat
{
let mat = cv.Mat.ones({height: 10, width: 5}, cv.CV_8UC3);
let mat2 = cv.Mat.eye({height: 10, width: 5}, cv.CV_8UC3);
let mat3 = cv.Mat.eye({height: 10, width: 5}, cv.CV_8UC3);
let out = new cv.Mat();
let input = new cv.MatVector();
input.push_back(mat);
input.push_back(mat2);
input.push_back(mat3);
cv.vconcat(input, out);
// Verify result.
let size = out.size();
assert.equal(out.channels(), 3);
assert.equal(size.height, 30);
assert.equal(size.width, 5);
assert.equal(out.elemSize1(), 1);
cv.hconcat(input, out);
// Verify result.
size = out.size();
assert.equal(out.channels(), 3);
assert.equal(size.height, 10);
assert.equal(size.width, 15);
assert.equal(out.elemSize1(), 1);
input.delete();
out.delete();
}
// distanceTransform letiants
{
let mat = cv.Mat.ones(11, 11, cv.CV_8UC1);
let out = new cv.Mat(11, 11, cv.CV_32FC1);
let labels = new cv.Mat(11, 11, cv.CV_32FC1);
const maskSize = 3;
cv.distanceTransform(mat, out, cv.DIST_L2, maskSize, cv.CV_32F);
// Verify result.
let size = out.size();
assert.equal(out.channels(), 1);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
assert.equal(out.elemSize1(), 4);
cv.distanceTransformWithLabels(mat, out, labels, cv.DIST_L2, maskSize,
cv.DIST_LABEL_CCOMP);
// Verify result.
size = out.size();
assert.equal(out.channels(), 1);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
assert.equal(out.elemSize1(), 4);
size = labels.size();
assert.equal(labels.channels(), 1);
assert.equal(size.height, 11);
assert.equal(size.width, 11);
assert.equal(labels.elemSize1(), 4);
mat.delete();
out.delete();
labels.delete();
}
// Min, Max
{
let data1 = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]);
let data2 = new Uint8Array([0, 4, 0, 8, 0, 12, 0, 16, 0]);
let expectedMin = new Uint8Array([0, 2, 0, 4, 0, 6, 0, 8, 0]);
let expectedMax = new Uint8Array([1, 4, 3, 8, 5, 12, 7, 16, 9]);
let dataPtr = cv._malloc(3*3*1);
let dataPtr2 = cv._malloc(3*3*1);
let dataHeap = new Uint8Array(cv.HEAPU8.buffer, dataPtr, 3*3*1);
dataHeap.set(new Uint8Array(data1.buffer));
let dataHeap2 = new Uint8Array(cv.HEAPU8.buffer, dataPtr2, 3*3*1);
dataHeap2.set(new Uint8Array(data2.buffer));
let mat1 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr, 0);
let mat2 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr2, 0);
let mat3 = new cv.Mat();
cv.min(mat1, mat2, mat3);
// Verify result.
let size = mat2.size();
assert.equal(mat2.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedMin);
cv.max(mat1, mat2, mat3);
// Verify result.
size = mat2.size();
assert.equal(mat2.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedMax);
cv._free(dataPtr);
cv._free(dataPtr2);
}
// Bitwise operations
{
let data1 = new Uint8Array([0, 1, 2, 4, 8, 16, 32, 64, 128]);
let data2 = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255, 255]);
let expectedAnd = new Uint8Array([0, 1, 2, 4, 8, 16, 32, 64, 128]);
let expectedOr = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255, 255]);
let expectedXor = new Uint8Array([255, 254, 253, 251, 247, 239, 223, 191, 127]);
let expectedNot = new Uint8Array([255, 254, 253, 251, 247, 239, 223, 191, 127]);
let dataPtr = cv._malloc(3*3*1);
let dataPtr2 = cv._malloc(3*3*1);
let dataHeap = new Uint8Array(cv.HEAPU8.buffer, dataPtr, 3*3*1);
dataHeap.set(new Uint8Array(data1.buffer));
let dataHeap2 = new Uint8Array(cv.HEAPU8.buffer, dataPtr2, 3*3*1);
dataHeap2.set(new Uint8Array(data2.buffer));
let mat1 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr, 0);
let mat2 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr2, 0);
let mat3 = new cv.Mat();
let none = new cv.Mat();
cv.bitwise_not(mat1, mat3, none);
// Verify result.
let size = mat3.size();
assert.equal(mat3.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedNot);
cv.bitwise_and(mat1, mat2, mat3, none);
// Verify result.
size = mat3.size();
assert.equal(mat3.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedAnd);
cv.bitwise_or(mat1, mat2, mat3, none);
// Verify result.
size = mat3.size();
assert.equal(mat3.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedOr);
cv.bitwise_xor(mat1, mat2, mat3, none);
// Verify result.
size = mat3.size();
assert.equal(mat3.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(mat3.data, expectedXor);
cv._free(dataPtr);
cv._free(dataPtr2);
}
// Arithmatic operations
{
let data1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8]);
let data2 = new Uint8Array([0, 2, 4, 6, 8, 10, 12, 14, 16]);
let data3 = new Uint8Array([0, 1, 0, 1, 0, 1, 0, 1, 0]);
// |data1 - data2|
let expectedAbsDiff = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8]);
let expectedAdd = new Uint8Array([0, 3, 6, 9, 12, 15, 18, 21, 24]);
const alpha = 4;
const beta = -1;
const gamma = 3;
// 4*data1 - data2 + 3
let expectedWeightedAdd = new Uint8Array([3, 5, 7, 9, 11, 13, 15, 17, 19]);
let dataPtr = cv._malloc(3*3*1);
let dataPtr2 = cv._malloc(3*3*1);
let dataPtr3 = cv._malloc(3*3*1);
let dataHeap = new Uint8Array(cv.HEAPU8.buffer, dataPtr, 3*3*1);
dataHeap.set(new Uint8Array(data1.buffer));
let dataHeap2 = new Uint8Array(cv.HEAPU8.buffer, dataPtr2, 3*3*1);
dataHeap2.set(new Uint8Array(data2.buffer));
let dataHeap3 = new Uint8Array(cv.HEAPU8.buffer, dataPtr3, 3*3*1);
dataHeap3.set(new Uint8Array(data3.buffer));
let mat1 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr, 0);
let mat2 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr2, 0);
let mat3 = new cv.Mat(3, 3, cv.CV_8UC1, dataPtr3, 0);
let dst = new cv.Mat();
let none = new cv.Mat();
cv.absdiff(mat1, mat2, dst);
// Verify result.
let size = dst.size();
assert.equal(dst.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(dst.data, expectedAbsDiff);
cv.add(mat1, mat2, dst, none, -1);
// Verify result.
size = dst.size();
assert.equal(dst.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(dst.data, expectedAdd);
cv.addWeighted(mat1, alpha, mat2, beta, gamma, dst, -1);
// Verify result.
size = dst.size();
assert.equal(dst.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(dst.data, expectedWeightedAdd);
// default parameter
cv.addWeighted(mat1, alpha, mat2, beta, gamma, dst);
// Verify result.
size = dst.size();
assert.equal(dst.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqual(dst.data, expectedWeightedAdd);
mat1.delete();
mat2.delete();
mat3.delete();
dst.delete();
none.delete();
}
// Integral letiants
{
let mat = cv.Mat.eye({height: 100, width: 100}, cv.CV_8UC3);
let sum = new cv.Mat();
let sqSum = new cv.Mat();
let title = new cv.Mat();
cv.integral(mat, sum, -1);
// Verify result.
let size = sum.size();
assert.equal(sum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
cv.integral2(mat, sum, sqSum, -1, -1);
// Verify result.
size = sum.size();
assert.equal(sum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
size = sqSum.size();
assert.equal(sqSum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
mat.delete();
sum.delete();
sqSum.delete();
title.delete();
}
// Mean, meanSTDev
{
let mat = cv.Mat.eye({height: 100, width: 100}, cv.CV_8UC3);
let sum = new cv.Mat();
let sqSum = new cv.Mat();
let title = new cv.Mat();
cv.integral(mat, sum, -1);
// Verify result.
let size = sum.size();
assert.equal(sum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
cv.integral2(mat, sum, sqSum, -1, -1);
// Verify result.
size = sum.size();
assert.equal(sum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
size = sqSum.size();
assert.equal(sqSum.channels(), 3);
assert.equal(size.height, 100+1);
assert.equal(size.width, 100+1);
mat.delete();
sum.delete();
sqSum.delete();
title.delete();
}
// Invert
{
let inv1 = new cv.Mat();
let inv2 = new cv.Mat();
let inv3 = new cv.Mat();
let inv4 = new cv.Mat();
let data1 = new Float32Array([1, 0, 0,
0, 1, 0,
0, 0, 1]);
let data2 = new Float32Array([0, 0, 0,
0, 5, 0,
0, 0, 0]);
let data3 = new Float32Array([1, 1, 1, 0,
0, 3, 1, 2,
2, 3, 1, 0,
1, 0, 2, 1]);
let data4 = new Float32Array([1, 4, 5,
4, 2, 2,
5, 2, 2]);
let expected1 = new Float32Array([1, 0, 0,
0, 1, 0,
0, 0, 1]);
// Inverse does not exist!
let expected3 = new Float32Array([-3, -1/2, 3/2, 1,
1, 1/4, -1/4, -1/2,
3, 1/4, -5/4, -1/2,
-3, 0, 1, 1]);
let expected4 = new Float32Array([0, -1, 1,
-1, 23/2, -9,
1, -9, 7]);
let dataPtr1 = cv._malloc(3*3*4);
let dataPtr2 = cv._malloc(3*3*4);
let dataPtr3 = cv._malloc(4*4*4);
let dataPtr4 = cv._malloc(3*3*4);
let dataHeap = new Float32Array(cv.HEAP32.buffer, dataPtr1, 3*3);
dataHeap.set(new Float32Array(data1.buffer));
let dataHeap2 = new Float32Array(cv.HEAP32.buffer, dataPtr2, 3*3);
dataHeap2.set(new Float32Array(data2.buffer));
let dataHeap3 = new Float32Array(cv.HEAP32.buffer, dataPtr3, 4*4);
dataHeap3.set(new Float32Array(data3.buffer));
let dataHeap4 = new Float32Array(cv.HEAP32.buffer, dataPtr4, 3*3);
dataHeap4.set(new Float32Array(data4.buffer));
let mat1 = new cv.Mat(3, 3, cv.CV_32FC1, dataPtr1, 0);
let mat2 = new cv.Mat(3, 3, cv.CV_32FC1, dataPtr2, 0);
let mat3 = new cv.Mat(4, 4, cv.CV_32FC1, dataPtr3, 0);
let mat4 = new cv.Mat(3, 3, cv.CV_32FC1, dataPtr4, 0);
QUnit.assert.deepEqualWithTolerance = function( value, expected, tolerance ) {
for (let i = 0; i < value.length; i= i+1) {
this.pushResult( {
result: Math.abs(value[i]-expected[i]) < tolerance,
actual: value[i],
expected: expected[i],
} );
}
};
cv.invert(mat1, inv1, 0);
// Verify result.
let size = inv1.size();
assert.equal(inv1.channels(), 1);
assert.equal(size.height, 3);
assert.equal(size.width, 3);
assert.deepEqualWithTolerance(inv1.data32F, expected1, 0.0001);
cv.invert(mat2, inv2, 0);
// Verify result.
assert.deepEqualWithTolerance(inv3.data32F, expected3, 0.0001);
cv.invert(mat3, inv3, 0);
// Verify result.
size = inv3.size();
assert.equal(inv3.channels(), 1);
assert.equal(size.height, 4);
assert.equal(size.width, 4);
assert.deepEqualWithTolerance(inv3.data32F, expected3, 0.0001);
cv.invert(mat3, inv3, 1);
// Verify result.
assert.deepEqualWithTolerance(inv3.data32F, expected3, 0.0001);
cv.invert(mat4, inv4, 2);
// Verify result.
assert.deepEqualWithTolerance(inv4.data32F, expected4, 0.0001);
cv.invert(mat4, inv4, 3);
// Verify result.
assert.deepEqualWithTolerance(inv4.data32F, expected4, 0.0001);
mat1.delete();
mat2.delete();
mat3.delete();
mat4.delete();
inv1.delete();
inv2.delete();
inv3.delete();
inv4.delete();
}
});
+987
View File
@@ -0,0 +1,987 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
//
// //////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//
if (typeof module !== 'undefined' && module.exports) {
// The envrionment is Node.js
var cv = require('./opencv.js'); // eslint-disable-line no-var
}
QUnit.module('Core', {});
QUnit.test('test_mat_creation', function(assert) {
// Mat constructors.
// Mat::Mat(int rows, int cols, int type)
{
let mat = new cv.Mat(10, 20, cv.CV_8UC3);
assert.equal(mat.type(), cv.CV_8UC3);
assert.equal(mat.depth(), cv.CV_8U);
assert.equal(mat.channels(), 3);
assert.ok(mat.empty() === false);
let size = mat.size();
assert.equal(size.height, 10);
assert.equal(size.width, 20);
mat.delete();
}
// Mat::Mat(const Mat &)
{
// Copy from another Mat
let mat1 = new cv.Mat(10, 20, cv.CV_8UC3);
let mat2 = new cv.Mat(mat1);
assert.equal(mat2.type(), mat1.type());
assert.equal(mat2.depth(), mat1.depth());
assert.equal(mat2.channels(), mat1.channels());
assert.equal(mat2.empty(), mat1.empty());
let size1 = mat1.size;
let size2 = mat2.size();
assert.ok(size1[0] === size2[0]);
assert.ok(size1[1] === size2[1]);
mat1.delete();
mat2.delete();
}
// Mat::Mat(int rows, int cols, int type, void *data, size_t step=AUTO_STEP)
{
// 10 * 10 and one channel
let data = cv._malloc(10 * 10 * 1);
let mat = new cv.Mat(10, 10, cv.CV_8UC1, data, 0);
assert.equal(mat.type(), cv.CV_8UC1);
assert.equal(mat.depth(), cv.CV_8U);
assert.equal(mat.channels(), 1);
assert.ok(mat.empty() === false);
let size = mat.size();
assert.ok(size.height === 10);
assert.ok(size.width === 10);
mat.delete();
}
// Mat::Mat(int rows, int cols, int type, const Scalar& scalar)
{
// 2 * 2 8UC4 mat
let mat = new cv.Mat(2, 2, cv.CV_8UC4, [0, 1, 2, 3]);
for (let r = 0; r < mat.rows; r++) {
for (let c = 0; c < mat.cols; c++) {
let element = mat.ptr(r, c);
assert.equal(element[0], 0);
assert.equal(element[1], 1);
assert.equal(element[2], 2);
assert.equal(element[3], 3);
}
}
mat.delete();
}
// Mat::create(int, int, int)
{
let mat = new cv.Mat();
mat.create(10, 5, cv.CV_8UC3);
let size = mat.size();
assert.ok(mat.type() === cv.CV_8UC3);
assert.ok(size.height === 10);
assert.ok(size.width === 5);
assert.ok(mat.channels() === 3);
mat.delete();
}
// Mat::create(Size, int)
{
let mat = new cv.Mat();
mat.create({height: 10, width: 5}, cv.CV_8UC4);
let size = mat.size();
assert.ok(mat.type() === cv.CV_8UC4);
assert.ok(size.height === 10);
assert.ok(size.width === 5);
assert.ok(mat.channels() === 4);
mat.delete();
}
// clone
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC1);
let mat2 = mat.clone();
assert.equal(mat.channels, mat2.channels);
assert.equal(mat.size().height, mat2.size().height);
assert.equal(mat.size().width, mat2.size().width);
assert.deepEqual(mat.data, mat2.data);
mat.delete();
mat2.delete();
}
// copyTo
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC1);
let mat2 = new cv.Mat();
mat.copyTo(mat2);
assert.equal(mat.channels, mat2.channels);
assert.equal(mat.size().height, mat2.size().height);
assert.equal(mat.size().width, mat2.size().width);
assert.deepEqual(mat.data, mat2.data);
mat.delete();
mat2.delete();
}
// copyTo1
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC1);
let mat2 = new cv.Mat();
let mask = new cv.Mat(5, 5, cv.CV_8UC1, new cv.Scalar(1));
mat.copyTo(mat2, mask);
assert.equal(mat.channels, mat2.channels);
assert.equal(mat.size().height, mat2.size().height);
assert.equal(mat.size().width, mat2.size().width);
assert.deepEqual(mat.data, mat2.data);
mat.delete();
mat2.delete();
mask.delete();
}
// matFromArray
{
let arrayC1 = [0, -1, 2, -3];
let arrayC2 = [0, -1, 2, -3, 4, -5, 6, -7];
let arrayC3 = [0, -1, 2, -3, 4, -5, 6, -7, 9, -9, 10, -11];
let arrayC4 = [0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, 13, 14, 15];
let mat8UC1 = cv.matFromArray(2, 2, cv.CV_8UC1, arrayC1);
let mat8UC2 = cv.matFromArray(2, 2, cv.CV_8UC2, arrayC2);
let mat8UC3 = cv.matFromArray(2, 2, cv.CV_8UC3, arrayC3);
let mat8UC4 = cv.matFromArray(2, 2, cv.CV_8UC4, arrayC4);
let mat8SC1 = cv.matFromArray(2, 2, cv.CV_8SC1, arrayC1);
let mat8SC2 = cv.matFromArray(2, 2, cv.CV_8SC2, arrayC2);
let mat8SC3 = cv.matFromArray(2, 2, cv.CV_8SC3, arrayC3);
let mat8SC4 = cv.matFromArray(2, 2, cv.CV_8SC4, arrayC4);
let mat16UC1 = cv.matFromArray(2, 2, cv.CV_16UC1, arrayC1);
let mat16UC2 = cv.matFromArray(2, 2, cv.CV_16UC2, arrayC2);
let mat16UC3 = cv.matFromArray(2, 2, cv.CV_16UC3, arrayC3);
let mat16UC4 = cv.matFromArray(2, 2, cv.CV_16UC4, arrayC4);
let mat16SC1 = cv.matFromArray(2, 2, cv.CV_16SC1, arrayC1);
let mat16SC2 = cv.matFromArray(2, 2, cv.CV_16SC2, arrayC2);
let mat16SC3 = cv.matFromArray(2, 2, cv.CV_16SC3, arrayC3);
let mat16SC4 = cv.matFromArray(2, 2, cv.CV_16SC4, arrayC4);
let mat32SC1 = cv.matFromArray(2, 2, cv.CV_32SC1, arrayC1);
let mat32SC2 = cv.matFromArray(2, 2, cv.CV_32SC2, arrayC2);
let mat32SC3 = cv.matFromArray(2, 2, cv.CV_32SC3, arrayC3);
let mat32SC4 = cv.matFromArray(2, 2, cv.CV_32SC4, arrayC4);
let mat32FC1 = cv.matFromArray(2, 2, cv.CV_32FC1, arrayC1);
let mat32FC2 = cv.matFromArray(2, 2, cv.CV_32FC2, arrayC2);
let mat32FC3 = cv.matFromArray(2, 2, cv.CV_32FC3, arrayC3);
let mat32FC4 = cv.matFromArray(2, 2, cv.CV_32FC4, arrayC4);
let mat64FC1 = cv.matFromArray(2, 2, cv.CV_64FC1, arrayC1);
let mat64FC2 = cv.matFromArray(2, 2, cv.CV_64FC2, arrayC2);
let mat64FC3 = cv.matFromArray(2, 2, cv.CV_64FC3, arrayC3);
let mat64FC4 = cv.matFromArray(2, 2, cv.CV_64FC4, arrayC4);
assert.deepEqual(mat8UC1.data, new Uint8Array(arrayC1));
assert.deepEqual(mat8UC2.data, new Uint8Array(arrayC2));
assert.deepEqual(mat8UC3.data, new Uint8Array(arrayC3));
assert.deepEqual(mat8UC4.data, new Uint8Array(arrayC4));
assert.deepEqual(mat8SC1.data8S, new Int8Array(arrayC1));
assert.deepEqual(mat8SC2.data8S, new Int8Array(arrayC2));
assert.deepEqual(mat8SC3.data8S, new Int8Array(arrayC3));
assert.deepEqual(mat8SC4.data8S, new Int8Array(arrayC4));
assert.deepEqual(mat16UC1.data16U, new Uint16Array(arrayC1));
assert.deepEqual(mat16UC2.data16U, new Uint16Array(arrayC2));
assert.deepEqual(mat16UC3.data16U, new Uint16Array(arrayC3));
assert.deepEqual(mat16UC4.data16U, new Uint16Array(arrayC4));
assert.deepEqual(mat16SC1.data16S, new Int16Array(arrayC1));
assert.deepEqual(mat16SC2.data16S, new Int16Array(arrayC2));
assert.deepEqual(mat16SC3.data16S, new Int16Array(arrayC3));
assert.deepEqual(mat16SC4.data16S, new Int16Array(arrayC4));
assert.deepEqual(mat32SC1.data32S, new Int32Array(arrayC1));
assert.deepEqual(mat32SC2.data32S, new Int32Array(arrayC2));
assert.deepEqual(mat32SC3.data32S, new Int32Array(arrayC3));
assert.deepEqual(mat32SC4.data32S, new Int32Array(arrayC4));
assert.deepEqual(mat32FC1.data32F, new Float32Array(arrayC1));
assert.deepEqual(mat32FC2.data32F, new Float32Array(arrayC2));
assert.deepEqual(mat32FC3.data32F, new Float32Array(arrayC3));
assert.deepEqual(mat32FC4.data32F, new Float32Array(arrayC4));
assert.deepEqual(mat64FC1.data64F, new Float64Array(arrayC1));
assert.deepEqual(mat64FC2.data64F, new Float64Array(arrayC2));
assert.deepEqual(mat64FC3.data64F, new Float64Array(arrayC3));
assert.deepEqual(mat64FC4.data64F, new Float64Array(arrayC4));
mat8UC1.delete();
mat8UC2.delete();
mat8UC3.delete();
mat8UC4.delete();
mat8SC1.delete();
mat8SC2.delete();
mat8SC3.delete();
mat8SC4.delete();
mat16UC1.delete();
mat16UC2.delete();
mat16UC3.delete();
mat16UC4.delete();
mat16SC1.delete();
mat16SC2.delete();
mat16SC3.delete();
mat16SC4.delete();
mat32SC1.delete();
mat32SC2.delete();
mat32SC3.delete();
mat32SC4.delete();
mat32FC1.delete();
mat32FC2.delete();
mat32FC3.delete();
mat32FC4.delete();
mat64FC1.delete();
mat64FC2.delete();
mat64FC3.delete();
mat64FC4.delete();
}
// matFromImageData
{
// Only test in browser
if (typeof window === 'undefined') {
return;
}
let canvas = window.document.createElement('canvas');
canvas.width = 2;
canvas.height = 2;
let ctx = canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0, 0, 1, 1);
ctx.fillRect(1, 1, 1, 1);
let imageData = ctx.getImageData(0, 0, 2, 2);
let mat = cv.matFromImageData(imageData);
assert.deepEqual(mat.data, new Uint8Array(imageData.data));
mat.delete();
}
// Mat(mat)
{
let mat = new cv.Mat(2, 2, cv.CV_8UC4, new cv.Scalar(1, 0, 1, 0));
let mat1 = new cv.Mat(mat);
let mat2 = mat;
assert.equal(mat.rows, mat1.rows);
assert.equal(mat.cols, mat1.cols);
assert.equal(mat.type(), mat1.type());
assert.deepEqual(mat.data, mat1.data);
mat.delete();
assert.equal(mat1.isDeleted(), false);
assert.equal(mat2.isDeleted(), true);
mat1.delete();
}
// mat.setTo
{
let mat = new cv.Mat(2, 2, cv.CV_8UC4);
let s = [0, 1, 2, 3];
mat.setTo(s);
assert.deepEqual(mat.ptr(0, 0), new Uint8Array(s));
assert.deepEqual(mat.ptr(0, 1), new Uint8Array(s));
assert.deepEqual(mat.ptr(1, 0), new Uint8Array(s));
assert.deepEqual(mat.ptr(1, 1), new Uint8Array(s));
let s1 = [0, 0, 0, 0];
mat.setTo(s1);
let mask = cv.matFromArray(2, 2, cv.CV_8UC1, [0, 1, 0, 1]);
mat.setTo(s, mask);
assert.deepEqual(mat.ptr(0, 0), new Uint8Array(s1));
assert.deepEqual(mat.ptr(0, 1), new Uint8Array(s));
assert.deepEqual(mat.ptr(1, 0), new Uint8Array(s1));
assert.deepEqual(mat.ptr(1, 1), new Uint8Array(s));
mat.delete();
mask.delete();
}
});
QUnit.test('test_mat_ptr', function(assert) {
const RValue = 3;
const GValue = 7;
const BValue = 197;
// cv.CV_8UC1 + Mat::ptr(int).
{
let mat = new cv.Mat(10, 10, cv.CV_8UC1);
let view = mat.data;
// Alter matrix[2, 1].
let step = 10;
view[2 * step + 1] = RValue;
// Access matrix[2, 1].
view = mat.ptr(2);
assert.equal(view[1], RValue);
mat.delete();
}
// cv.CV_8UC3 + Mat::ptr(int).
{
let mat = new cv.Mat(10, 10, cv.CV_8UC3);
let view = mat.data;
// Alter matrix[2, 1].
let step = 3 * 10;
view[2 * step + 3] = RValue;
view[2 * step + 3 + 1] = GValue;
view[2 * step + 3 + 2] = BValue;
// Access matrix[2, 1].
view = mat.ptr(2);
assert.equal(view[3], RValue);
assert.equal(view[3 + 1], GValue);
assert.equal(view[3 + 2], BValue);
mat.delete();
}
// cv.CV_8UC3 + Mat::ptr(int, int).
{
let mat = new cv.Mat(10, 10, cv.CV_8UC3);
let view = mat.data;
// Alter matrix[2, 1].
let step = 3 * 10;
view[2 * step + 3] = RValue;
view[2 * step + 3 + 1] = GValue;
view[2 * step + 3 + 2] = BValue;
// Access matrix[2, 1].
view = mat.ptr(2, 1);
assert.equal(view[0], RValue);
assert.equal(view[1], GValue);
assert.equal(view[2], BValue);
mat.delete();
}
const RValueF32 = 3.3;
const GValueF32 = 7.3;
const BValueF32 = 197.3;
const EPSILON = 0.001;
// cv.CV_32FC1 + Mat::ptr(int).
{
let mat = new cv.Mat(10, 10, cv.CV_32FC1);
let view = mat.data32F;
// Alter matrix[2, 1].
let step = 10;
view[2 * step + 1] = RValueF32;
// Access matrix[2, 1].
view = mat.floatPtr(2);
assert.ok(Math.abs(view[1] - RValueF32) < EPSILON);
mat.delete();
}
// cv.CV_32FC3 + Mat::ptr(int).
{
let mat = new cv.Mat(10, 10, cv.CV_32FC3);
let view = mat.data32F;
// Alter matrix[2, 1].
let step = mat.step1(0);
view[2 * step + 3] = RValueF32;
view[2 * step + 3 + 1] = GValueF32;
view[2 * step + 3 + 2] = BValueF32;
// Access matrix[2, 1].
view = mat.floatPtr(2);
assert.ok(Math.abs(view[3] - RValueF32) < EPSILON);
assert.ok(Math.abs(view[3 + 1] - GValueF32) < EPSILON);
assert.ok(Math.abs(view[3 + 2] - BValueF32) < EPSILON);
mat.delete();
}
// cv.CV_32FC3 + Mat::ptr(int, int).
{
let mat = new cv.Mat(10, 10, cv.CV_32FC3);
let view = mat.data32F;
// Alter matrix[2, 1].
let step = mat.step1(0);
view[2 * step + 3] = RValueF32;
view[2 * step + 3 + 1] = GValueF32;
view[2 * step + 3 + 2] = BValueF32;
// Access matrix[2, 1].
view = mat.floatPtr(2, 1);
assert.ok(Math.abs(view[0] - RValueF32) < EPSILON);
assert.ok(Math.abs(view[1] - GValueF32) < EPSILON);
assert.ok(Math.abs(view[2] - BValueF32) < EPSILON);
mat.delete();
}
});
QUnit.test('test_mat_zeros', function(assert) {
let zeros = new Uint8Array(10*10).fill(0);
// Mat::zeros(int, int, int)
{
let mat = cv.Mat.zeros(10, 10, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, zeros);
mat.delete();
}
// Mat::zeros(Size, int)
{
let mat = cv.Mat.zeros({height: 10, width: 10}, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, zeros);
mat.delete();
}
});
QUnit.test('test_mat_ones', function(assert) {
let ones = new Uint8Array(10*10).fill(1);
// Mat::ones(int, int, int)
{
let mat = cv.Mat.ones(10, 10, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, ones);
}
// Mat::ones(Size, int)
{
let mat = cv.Mat.ones({height: 10, width: 10}, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, ones);
}
});
QUnit.test('test_mat_eye', function(assert) {
let eye4by4 = new Uint8Array([1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1]);
// Mat::eye(int, int, int)
{
let mat = cv.Mat.eye(4, 4, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, eye4by4);
}
// Mat::eye(Size, int)
{
let mat = cv.Mat.eye({height: 4, width: 4}, cv.CV_8UC1);
let view = mat.data;
assert.deepEqual(view, eye4by4);
}
});
QUnit.test('test_mat_miscs', function(assert) {
// Mat::col(int)
{
let mat = cv.matFromArray(2, 2, cv.CV_8UC2, [1, 2, 3, 4, 5, 6, 7, 8]);
let col = mat.col(1);
assert.equal(col.isContinuous(), false);
assert.equal(col.ptr(0, 0)[0], 3);
assert.equal(col.ptr(0, 0)[1], 4);
assert.equal(col.ptr(1, 0)[0], 7);
assert.equal(col.ptr(1, 0)[1], 8);
col.delete();
mat.delete();
}
// Mat::row(int)
{
let mat = cv.Mat.zeros(5, 5, cv.CV_8UC2);
let row = mat.row(1);
let view = row.data;
assert.equal(view[0], 0);
assert.equal(view[4], 0);
row.delete();
mat.delete();
}
// Mat::convertTo(Mat, int, double, double)
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC3);
let grayMat = cv.Mat.zeros(5, 5, cv.CV_8UC1);
mat.convertTo(grayMat, cv.CV_8U, 2, 1);
// dest = 2 * source(x, y) + 1.
let view = grayMat.data;
assert.equal(view[0], (1 * 2) + 1);
mat.convertTo(grayMat, cv.CV_8U);
// dest = 1 * source(x, y) + 0.
assert.equal(view[0], 1);
mat.convertTo(grayMat, cv.CV_8U, 2);
// dest = 2 * source(x, y) + 0.
assert.equal(view[0], 2);
grayMat.delete();
mat.delete();
}
// split
{
const R =7;
const G =13;
const B =29;
let mat = cv.Mat.ones(5, 5, cv.CV_8UC3);
let view = mat.data;
view[0] = R;
view[1] = G;
view[2] = B;
let bgrPlanes = new cv.MatVector();
cv.split(mat, bgrPlanes);
assert.equal(bgrPlanes.size(), 3);
let rMat = bgrPlanes.get(0);
view = rMat.data;
assert.equal(view[0], R);
let gMat = bgrPlanes.get(1);
view = gMat.data;
assert.equal(view[0], G);
let bMat = bgrPlanes.get(2);
view = bMat.data;
assert.equal(view[0], B);
mat.delete();
rMat.delete();
gMat.delete();
bgrPlanes.delete();
bMat.delete();
}
// elemSize
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC3);
assert.equal(mat.elemSize(), 3);
assert.equal(mat.elemSize1(), 1);
let mat2 = cv.Mat.zeros(5, 5, cv.CV_8UC1);
assert.equal(mat2.elemSize(), 1);
assert.equal(mat2.elemSize1(), 1);
let mat3 = cv.Mat.eye(5, 5, cv.CV_16UC3);
assert.equal(mat3.elemSize(), 2 * 3);
assert.equal(mat3.elemSize1(), 2);
mat.delete();
mat2.delete();
mat3.delete();
}
// step
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC3);
assert.equal(mat.step[0], 15);
assert.equal(mat.step[1], 3);
let mat2 = cv.Mat.zeros(5, 5, cv.CV_8UC1);
assert.equal(mat2.step[0], 5);
assert.equal(mat2.step[1], 1);
let mat3 = cv.Mat.eye(5, 5, cv.CV_16UC3);
assert.equal(mat3.step[0], 30);
assert.equal(mat3.step[1], 6);
mat.delete();
mat2.delete();
mat3.delete();
}
// dot
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC1);
let mat2 = cv.Mat.eye(5, 5, cv.CV_8UC1);
assert.equal(mat.dot(mat), 25);
assert.equal(mat.dot(mat2), 5);
assert.equal(mat2.dot(mat2), 5);
mat.delete();
mat2.delete();
}
// mul
{
const FACTOR = 5;
let mat = cv.Mat.ones(4, 4, cv.CV_8UC1);
let mat2 = cv.Mat.eye(4, 4, cv.CV_8UC1);
let expected = new Uint8Array([FACTOR, 0, 0, 0,
0, FACTOR, 0, 0,
0, 0, FACTOR, 0,
0, 0, 0, FACTOR]);
let mat3 = mat.mul(mat2, FACTOR);
assert.deepEqual(mat3.data, expected);
mat.delete();
mat2.delete();
mat3.delete();
}
});
QUnit.test('test mat access', function(assert) {
// test memory view
{
let data = new Uint8Array([0, 0, 0, 255, 0, 1, 2, 3]);
let dataPtr = cv._malloc(8);
let dataHeap = new Uint8Array(cv.HEAPU8.buffer, dataPtr, 8);
dataHeap.set(new Uint8Array(data.buffer));
let mat = new cv.Mat(8, 1, cv.CV_8UC1, dataPtr, 0);
let unsignedCharView = new Uint8Array(data.buffer);
let charView = new Int8Array(data.buffer);
let shortView = new Int16Array(data.buffer);
let unsignedShortView = new Uint16Array(data.buffer);
let intView = new Int32Array(data.buffer);
let float32View = new Float32Array(data.buffer);
let float64View = new Float64Array(data.buffer);
assert.deepEqual(unsignedCharView, mat.data);
assert.deepEqual(charView, mat.data8S);
assert.deepEqual(shortView, mat.data16S);
assert.deepEqual(unsignedShortView, mat.data16U);
assert.deepEqual(intView, mat.data32S);
assert.deepEqual(float32View, mat.data32F);
assert.deepEqual(float64View, mat.data64F);
}
// test ucharAt(i)
{
let data = new Uint8Array([0, 0, 0, 255, 0, 1, 2, 3]);
let dataPtr = cv._malloc(8);
let dataHeap = new Uint8Array(cv.HEAPU8.buffer, dataPtr, 8);
dataHeap.set(new Uint8Array(data.buffer));
let mat = new cv.Mat(8, 1, cv.CV_8UC1, dataPtr, 0);
assert.equal(mat.ucharAt(0), 0);
assert.equal(mat.ucharAt(1), 0);
assert.equal(mat.ucharAt(2), 0);
assert.equal(mat.ucharAt(3), 255);
assert.equal(mat.ucharAt(4), 0);
assert.equal(mat.ucharAt(5), 1);
assert.equal(mat.ucharAt(6), 2);
assert.equal(mat.ucharAt(7), 3);
}
// test ushortAt(i)
{
let data = new Uint16Array([0, 1000, 65000, 255, 0, 1, 2, 3]);
let dataPtr = cv._malloc(16);
let dataHeap = new Uint16Array(cv.HEAPU8.buffer, dataPtr, 8);
dataHeap.set(new Uint16Array(data.buffer));
let mat = new cv.Mat(8, 1, cv.CV_16SC1, dataPtr, 0);
assert.equal(mat.ushortAt(0), 0);
assert.equal(mat.ushortAt(1), 1000);
assert.equal(mat.ushortAt(2), 65000);
assert.equal(mat.ushortAt(3), 255);
assert.equal(mat.ushortAt(4), 0);
assert.equal(mat.ushortAt(5), 1);
assert.equal(mat.ushortAt(6), 2);
assert.equal(mat.ushortAt(7), 3);
}
// test intAt(i)
{
let data = new Int32Array([0, -1000, 65000, 255, -2000000, -1, 2, 3]);
let dataPtr = cv._malloc(32);
let dataHeap = new Int32Array(cv.HEAPU32.buffer, dataPtr, 8);
dataHeap.set(new Int32Array(data.buffer));
let mat = new cv.Mat(8, 1, cv.CV_32SC1, dataPtr, 0);
assert.equal(mat.intAt(0), 0);
assert.equal(mat.intAt(1), -1000);
assert.equal(mat.intAt(2), 65000);
assert.equal(mat.intAt(3), 255);
assert.equal(mat.intAt(4), -2000000);
assert.equal(mat.intAt(5), -1);
assert.equal(mat.intAt(6), 2);
assert.equal(mat.intAt(7), 3);
}
// test floatAt(i)
{
const EPSILON = 0.001;
let data = new Float32Array([0, -10.5, 650.001, 255, -20.1, -1.2, 2, 3.5]);
let dataPtr = cv._malloc(32);
let dataHeap = new Float32Array(cv.HEAPU32.buffer, dataPtr, 8);
dataHeap.set(new Float32Array(data.buffer));
let mat = new cv.Mat(8, 1, cv.CV_32FC1, dataPtr, 0);
assert.equal(Math.abs(mat.floatAt(0)-0) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(1)+10.5) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(2)-650.001) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(3)-255) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(4)+20.1) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(5)+1.2) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(6)-2) < EPSILON, true);
assert.equal(Math.abs(mat.floatAt(7)-3.5) < EPSILON, true);
}
// test intAt(i,j)
{
let mat = cv.Mat.eye({height: 3, width: 3}, cv.CV_32SC1);
assert.equal(mat.intAt(0, 0), 1);
assert.equal(mat.intAt(0, 1), 0);
assert.equal(mat.intAt(0, 2), 0);
assert.equal(mat.intAt(1, 0), 0);
assert.equal(mat.intAt(1, 1), 1);
assert.equal(mat.intAt(1, 2), 0);
assert.equal(mat.intAt(2, 0), 0);
assert.equal(mat.intAt(2, 1), 0);
assert.equal(mat.intAt(2, 2), 1);
mat.delete();
}
});
QUnit.test('test_mat_operations', function(assert) {
// test minMaxLoc
{
let src = cv.Mat.ones(4, 4, cv.CV_8UC1);
src.data[2] = 0;
src.data[5] = 2;
let result = cv.minMaxLoc(src);
assert.equal(result.minVal, 0);
assert.equal(result.maxVal, 2);
assert.deepEqual(result.minLoc, {x: 2, y: 0});
assert.deepEqual(result.maxLoc, {x: 1, y: 1});
src.delete();
}
});
QUnit.test('test_mat_roi', function(assert) {
// test minMaxLoc
{
let mat = cv.matFromArray(2, 2, cv.CV_8UC1, [0, 1, 2, 3]);
let roi = mat.roi(new cv.Rect(1, 1, 1, 1));
assert.equal(roi.rows, 1);
assert.equal(roi.cols, 1);
assert.deepEqual(roi.data, new Uint8Array([mat.ucharAt(1, 1)]));
mat.delete();
roi.delete();
}
});
QUnit.test('test_mat_range', function(assert) {
{
let src = cv.matFromArray(2, 2, cv.CV_8UC1, [0, 1, 2, 3]);
let mat = src.colRange(0, 1);
assert.equal(mat.isContinuous(), false);
assert.equal(mat.rows, 2);
assert.equal(mat.cols, 1);
assert.equal(mat.ucharAt(0), 0);
assert.equal(mat.ucharAt(1), 2);
mat.delete();
mat = src.colRange({start: 0, end: 1});
assert.equal(mat.isContinuous(), false);
assert.equal(mat.rows, 2);
assert.equal(mat.cols, 1);
assert.equal(mat.ucharAt(0), 0);
assert.equal(mat.ucharAt(1), 2);
mat.delete();
mat = src.rowRange(1, 2);
assert.equal(mat.rows, 1);
assert.equal(mat.cols, 2);
assert.deepEqual(mat.data, new Uint8Array([2, 3]));
mat.delete();
mat = src.rowRange({start: 1, end: 2});
assert.equal(mat.rows, 1);
assert.equal(mat.cols, 2);
assert.deepEqual(mat.data, new Uint8Array([2, 3]));
mat.delete();
src.delete();
}
});
QUnit.test('test_mat_diag', function(assert) {
// test diag
{
let mat = cv.matFromArray(3, 3, cv.CV_8UC1, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
let d = mat.diag();
let d1 = mat.diag(1);
let d2 = mat.diag(-1);
assert.equal(mat.isContinuous(), true);
assert.equal(d.isContinuous(), false);
assert.equal(d1.isContinuous(), false);
assert.equal(d2.isContinuous(), false);
assert.equal(d.ucharAt(0), 0);
assert.equal(d.ucharAt(1), 4);
assert.equal(d.ucharAt(2), 8);
assert.equal(d1.ucharAt(0), 1);
assert.equal(d1.ucharAt(1), 5);
assert.equal(d2.ucharAt(0), 3);
assert.equal(d2.ucharAt(1), 7);
mat.delete();
d.delete();
d1.delete();
d2.delete();
}
});
+161
View File
@@ -0,0 +1,161 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
//
// //////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//
if (typeof module !== 'undefined' && module.exports) {
// The envrionment is Node.js
var cv = require('./opencv.js'); // eslint-disable-line no-var
cv.FS_createLazyFile('/', 'haarcascade_frontalface_default.xml', // eslint-disable-line new-cap
'haarcascade_frontalface_default.xml', true, false);
}
QUnit.module('Object Detection', {});
QUnit.test('Cascade classification', function(assert) {
// Group rectangle
{
let rectList = new cv.RectVector();
let weights = new cv.IntVector();
let groupThreshold = 1;
const eps = 0.2;
let rect1 = new cv.Rect(1, 2, 3, 4);
let rect2 = new cv.Rect(1, 4, 2, 3);
rectList.push_back(rect1);
rectList.push_back(rect2);
cv.groupRectangles(rectList, weights, groupThreshold, eps);
rectList.delete();
weights.delete();
}
// CascadeClassifier
{
let classifier = new cv.CascadeClassifier();
const modelPath = '/haarcascade_frontalface_default.xml';
assert.equal(classifier.empty(), true);
classifier.load(modelPath);
assert.equal(classifier.empty(), false);
let image = cv.Mat.eye({height: 10, width: 10}, cv.CV_8UC3);
let objects = new cv.RectVector();
let numDetections = new cv.IntVector();
const scaleFactor = 1.1;
const minNeighbors = 3;
const flags = 0;
const minSize = {height: 0, width: 0};
const maxSize = {height: 10, width: 10};
classifier.detectMultiScale2(image, objects, numDetections, scaleFactor,
minNeighbors, flags, minSize, maxSize);
// test default parameters
classifier.detectMultiScale2(image, objects, numDetections, scaleFactor,
minNeighbors, flags, minSize);
classifier.detectMultiScale2(image, objects, numDetections, scaleFactor,
minNeighbors, flags);
classifier.detectMultiScale2(image, objects, numDetections, scaleFactor,
minNeighbors);
classifier.detectMultiScale2(image, objects, numDetections, scaleFactor);
classifier.delete();
objects.delete();
numDetections.delete();
}
// HOGDescriptor
{
let hog = new cv.HOGDescriptor();
let mat = new cv.Mat({height: 10, width: 10}, cv.CV_8UC1);
let descriptors = new cv.FloatVector();
let locations = new cv.PointVector();
assert.equal(hog.winSize.height, 128);
assert.equal(hog.winSize.width, 64);
assert.equal(hog.nbins, 9);
assert.equal(hog.derivAperture, 1);
assert.equal(hog.winSigma, -1);
assert.equal(hog.histogramNormType, 0);
assert.equal(hog.nlevels, 64);
hog.nlevels = 32;
assert.equal(hog.nlevels, 32);
hog.delete();
mat.delete();
descriptors.delete();
locations.delete();
}
});
+253
View File
@@ -0,0 +1,253 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
// //////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//
if (typeof module !== 'undefined' && module.exports) {
// The envrionment is Node.js
var cv = require('./opencv.js'); // eslint-disable-line no-var
}
QUnit.module('Utils', {});
QUnit.test('Test vectors', function(assert) {
{
let pointVector = new cv.PointVector();
for (let i=0; i<100; ++i) {
pointVector.push_back({x: i, y: 2*i});
}
assert.equal(pointVector.size(), 100);
let index = 10;
let item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
index = 0;
item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
index = 99;
item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
pointVector.delete();
}
{
let pointVector = new cv.PointVector();
for (let i=0; i<100; ++i) {
pointVector.push_back(new cv.Point(i, 2*i));
}
pointVector.push_back(new cv.Point());
assert.equal(pointVector.size(), 101);
let index = 10;
let item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
index = 0;
item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
index = 99;
item = pointVector.get(index);
assert.equal(item.x, index);
assert.equal(item.y, 2*index);
index = 100;
item = pointVector.get(index);
assert.equal(item.x, 0);
assert.equal(item.y, 0);
pointVector.delete();
}
});
QUnit.test('Test Rect', function(assert) {
let rectVector = new cv.RectVector();
let rect = {x: 1, y: 2, width: 3, height: 4};
rectVector.push_back(rect);
rectVector.push_back(new cv.Rect());
rectVector.push_back(new cv.Rect(rect));
rectVector.push_back(new cv.Rect({x: 5, y: 6}, {width: 7, height: 8}));
rectVector.push_back(new cv.Rect(9, 10, 11, 12));
assert.equal(rectVector.size(), 5);
let item = rectVector.get(0);
assert.equal(item.x, 1);
assert.equal(item.y, 2);
assert.equal(item.width, 3);
assert.equal(item.height, 4);
item = rectVector.get(1);
assert.equal(item.x, 0);
assert.equal(item.y, 0);
assert.equal(item.width, 0);
assert.equal(item.height, 0);
item = rectVector.get(2);
assert.equal(item.x, 1);
assert.equal(item.y, 2);
assert.equal(item.width, 3);
assert.equal(item.height, 4);
item = rectVector.get(3);
assert.equal(item.x, 5);
assert.equal(item.y, 6);
assert.equal(item.width, 7);
assert.equal(item.height, 8);
item = rectVector.get(4);
assert.equal(item.x, 9);
assert.equal(item.y, 10);
assert.equal(item.width, 11);
assert.equal(item.height, 12);
rectVector.delete();
});
QUnit.test('Test Size', function(assert) {
{
let mat = new cv.Mat();
mat.create({width: 5, height: 10}, cv.CV_8UC4);
let size = mat.size();
assert.ok(mat.type() === cv.CV_8UC4);
assert.ok(size.height === 10);
assert.ok(size.width === 5);
assert.ok(mat.channels() === 4);
mat.delete();
}
{
let mat = new cv.Mat();
mat.create(new cv.Size(5, 10), cv.CV_8UC4);
let size = mat.size();
assert.ok(mat.type() === cv.CV_8UC4);
assert.ok(size.height === 10);
assert.ok(size.width === 5);
assert.ok(mat.channels() === 4);
mat.delete();
}
});
QUnit.test('test_rotated_rect', function(assert) {
{
let rect = {center: {x: 100, y: 100}, size: {height: 100, width: 50}, angle: 30};
assert.equal(rect.center.x, 100);
assert.equal(rect.center.y, 100);
assert.equal(rect.angle, 30);
assert.equal(rect.size.height, 100);
assert.equal(rect.size.width, 50);
}
{
let rect = new cv.RotatedRect();
assert.equal(rect.center.x, 0);
assert.equal(rect.center.y, 0);
assert.equal(rect.angle, 0);
assert.equal(rect.size.height, 0);
assert.equal(rect.size.width, 0);
let points = cv.RotatedRect.points(rect);
assert.equal(points[0].x, 0);
assert.equal(points[0].y, 0);
assert.equal(points[1].x, 0);
assert.equal(points[1].y, 0);
assert.equal(points[2].x, 0);
assert.equal(points[2].y, 0);
assert.equal(points[3].x, 0);
assert.equal(points[3].y, 0);
}
{
let rect = new cv.RotatedRect({x: 100, y: 100}, {height: 100, width: 50}, 30);
assert.equal(rect.center.x, 100);
assert.equal(rect.center.y, 100);
assert.equal(rect.angle, 30);
assert.equal(rect.size.height, 100);
assert.equal(rect.size.width, 50);
let points = cv.RotatedRect.points(rect);
assert.equal(points[0].x, cv.RotatedRect.boundingRect2f(rect).x);
assert.equal(points[1].y, cv.RotatedRect.boundingRect2f(rect).y);
}
});
+107
View File
@@ -0,0 +1,107 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
// //////////////////////////////////////////////////////////////////////////////////////
// Author: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
//
// LICENSE AGREEMENT
// Copyright (c) 2015 The Regents of the University of California (Regents)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions 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.
// 3. Neither the name of the University nor the
// names of its contributors may 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 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.
//
if (typeof module !== 'undefined' && module.exports) {
// The envrionment is Node.js
var cv = require('./opencv.js'); // eslint-disable-line no-var
}
QUnit.module('Video', {});
QUnit.test('Background Segmentation', function(assert) {
// BackgroundSubtractorMOG2
{
const history = 600;
const varThreshold = 15;
const detectShadows = true;
let mog2 = new cv.BackgroundSubtractorMOG2(history, varThreshold, detectShadows);
assert.equal(mog2 instanceof cv.BackgroundSubtractorMOG2, true);
mog2.delete();
mog2 = new cv.BackgroundSubtractorMOG2();
assert.equal(mog2 instanceof cv.BackgroundSubtractorMOG2, true);
mog2.delete();
mog2 = new cv.BackgroundSubtractorMOG2(history);
assert.equal(mog2 instanceof cv.BackgroundSubtractorMOG2, true);
mog2.delete();
mog2 = new cv.BackgroundSubtractorMOG2(history, varThreshold);
assert.equal(mog2 instanceof cv.BackgroundSubtractorMOG2, true);
mog2.delete();
}
});
+78
View File
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>OpenCV JS Tests</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.20.0.css" type="text/css" media="screen">
<style>
body {
font-family: Monospace;
background-color: #ffffff;
margin: 0px;
}
a {
color: #0040ff;
}
</style>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="http://code.jquery.com/qunit/qunit-2.0.1.js"></script>
<script type="application/javascript" async src="opencv.js"></script>
<script type="application/javascript" src="test_mat.js"></script>
<script type="application/javascript" src="test_utils.js"></script>
<script type="application/javascript" src="test_imgproc.js"></script>
<script type="application/javascript" src="test_objdetect.js"></script>
<script type="application/javascript" src="test_video.js"></script>
<script type='text/javascript'>
QUnit.config.autostart = false;
var Module = {
preRun: [function() {
Module.FS_createPreloadedFile('/', 'haarcascade_frontalface_default.xml', 'haarcascade_frontalface_default.xml', true, false);
}],
postRun: [] ,
onRuntimeInitialized: function() {
console.log("Runtime is ready...");
QUnit.start();
},
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
printErr: function(text) {
console.log(text);
},
setStatus: function(text) {
console.log(text);
},
totalDependencies: 0
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
Module.setStatus('Exception thrown, see JavaScript console');
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
<!--
TODO
<script type="application/javascript" src="test_features2d.js"></script>
-->
</body>
</html>
+53
View File
@@ -0,0 +1,53 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
let testrunner = require('qunit');
testrunner.options.maxBlockDuration = 20000; // cause opencv_js.js need time to load
testrunner.run(
{
code: 'opencv.js',
tests: ['test_mat.js', 'test_utils.js', 'test_imgproc.js',
'test_objdetect.js', 'test_video.js'],
},
function(err, report) {
console.log(report.failed + ' failed, ' + report.passed + ' passed');
}
);
+1 -1
View File
@@ -1,2 +1,2 @@
set(the_description "Object Detection")
ocv_define_module(objdetect opencv_core opencv_imgproc WRAP java python)
ocv_define_module(objdetect opencv_core opencv_imgproc WRAP java python js)
+29 -1
View File
@@ -105,6 +105,14 @@ class CppHeaderParser(object):
modlist.append("/CA " + macro_arg)
arg_str = arg_str[:npos] + arg_str[npos3+1:]
npos = arg_str.find("const")
if npos >= 0:
modlist.append("/C")
npos = arg_str.find("&")
if npos >= 0:
modlist.append("/Ref")
arg_str = arg_str.strip()
word_start = 0
word_list = []
@@ -406,13 +414,27 @@ class CppHeaderParser(object):
func_modlist.append("="+arg)
decl_str = decl_str[:npos] + decl_str[npos3+1:]
virtual_method = False
pure_virtual_method = False
const_method = False
# filter off some common prefixes, which are meaningless for Python wrappers.
# note that we do not strip "static" prefix, which does matter;
# it means class methods, not instance methods
decl_str = self.batch_replace(decl_str, [("virtual", ""), ("static inline", ""), ("inline", ""),\
decl_str = self.batch_replace(decl_str, [("static inline", ""), ("inline", ""),\
("CV_EXPORTS_W", ""), ("CV_EXPORTS", ""), ("CV_CDECL", ""), ("CV_WRAP ", " "), ("CV_INLINE", ""),
("CV_DEPRECATED", "")]).strip()
if decl_str.strip().startswith('virtual'):
virtual_method = True
decl_str = decl_str.replace('virtual' , '')
end_tokens = decl_str[decl_str.rfind(')'):].split()
const_method = 'const' in end_tokens
pure_virtual_method = '=' in end_tokens and '0' in end_tokens
static_method = False
context = top[0]
if decl_str.startswith("static") and (context == "class" or context == "struct"):
@@ -575,6 +597,12 @@ class CppHeaderParser(object):
if static_method:
func_modlist.append("/S")
if const_method:
func_modlist.append("/C")
if virtual_method:
func_modlist.append("/V")
if pure_virtual_method:
func_modlist.append("/PV")
return [funcname, rettype, func_modlist, args, original_type, docstring]
+1 -1
View File
@@ -1,2 +1,2 @@
set(the_description "Video Analysis")
ocv_define_module(video opencv_imgproc WRAP java python)
ocv_define_module(video opencv_imgproc WRAP java python js)