add part of opencv

This commit is contained in:
Tang1705
2020-01-27 20:20:56 +08:00
parent 0c4ac1d8bb
commit a71fa47620
6518 changed files with 3122580 additions and 0 deletions

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"
}
}

View File

@@ -0,0 +1,745 @@
/*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 <emscripten/bind.h>
@INCLUDES@
#include "../../../modules/core/src/parallel_impl.hpp"
#ifdef TEST_WASM_INTRIN
#include "../../../modules/core/include/opencv2/core/hal/intrin.hpp"
#include "../../../modules/core/include/opencv2/core/utils/trace.hpp"
#include "../../../modules/ts/include/opencv2/ts/ts_gtest.h"
namespace cv {
namespace hal {
#include "../../../modules/core/test/test_intrin_utils.hpp"
}
}
#endif
using namespace emscripten;
using namespace cv;
#ifdef HAVE_OPENCV_DNN
using namespace dnn;
#endif
#ifdef HAVE_OPENCV_ARUCO
using namespace aruco;
#endif
namespace binding_utils
{
template<typename classT, typename enumT>
static inline typename std::underlying_type<enumT>::type classT::* underlying_ptr(enumT classT::* enum_ptr)
{
return reinterpret_cast<typename std::underlying_type<enumT>::type classT::*>(enum_ptr);
}
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;
};
#ifdef HAVE_OPENCV_IMGPROC
Circle minEnclosingCircle(const cv::Mat& points)
{
Circle circle;
cv::minEnclosingCircle(points, circle.center, circle.radius);
return circle;
}
int floodFill_withRect_helper(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4, emscripten::val arg5, Scalar arg6 = Scalar(), Scalar arg7 = Scalar(), int arg8 = 4)
{
cv::Rect rect;
int rc = cv::floodFill(arg1, arg2, arg3, arg4, &rect, arg6, arg7, arg8);
arg5.set("x", emscripten::val(rect.x));
arg5.set("y", emscripten::val(rect.y));
arg5.set("width", emscripten::val(rect.width));
arg5.set("height", emscripten::val(rect.height));
return rc;
}
int floodFill_wrapper(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4, emscripten::val arg5, Scalar arg6, Scalar arg7, int arg8) {
return floodFill_withRect_helper(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
int floodFill_wrapper_1(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4, emscripten::val arg5, Scalar arg6, Scalar arg7) {
return floodFill_withRect_helper(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
int floodFill_wrapper_2(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4, emscripten::val arg5, Scalar arg6) {
return floodFill_withRect_helper(arg1, arg2, arg3, arg4, arg5, arg6);
}
int floodFill_wrapper_3(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4, emscripten::val arg5) {
return floodFill_withRect_helper(arg1, arg2, arg3, arg4, arg5);
}
int floodFill_wrapper_4(cv::Mat& arg1, cv::Mat& arg2, Point arg3, Scalar arg4) {
return cv::floodFill(arg1, arg2, arg3, arg4);
}
#endif
#ifdef HAVE_OPENCV_VIDEO
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;
}
#endif // HAVE_OPENCV_VIDEO
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();
}
#ifdef TEST_WASM_INTRIN
void test_hal_intrin_uint8() {
cv::hal::test_hal_intrin_uint8();
}
void test_hal_intrin_int8() {
cv::hal::test_hal_intrin_int8();
}
void test_hal_intrin_uint16() {
cv::hal::test_hal_intrin_uint16();
}
void test_hal_intrin_int16() {
cv::hal::test_hal_intrin_int16();
}
void test_hal_intrin_uint32() {
cv::hal::test_hal_intrin_uint32();
}
void test_hal_intrin_int32() {
cv::hal::test_hal_intrin_int32();
}
void test_hal_intrin_uint64() {
cv::hal::test_hal_intrin_uint64();
}
void test_hal_intrin_int64() {
cv::hal::test_hal_intrin_int64();
}
void test_hal_intrin_float32() {
cv::hal::test_hal_intrin_float32();
}
void test_hal_intrin_float64() {
cv::hal::test_hal_intrin_float64();
}
void test_hal_intrin_all() {
cv::hal::test_hal_intrin_uint8();
cv::hal::test_hal_intrin_int8();
cv::hal::test_hal_intrin_uint16();
cv::hal::test_hal_intrin_int16();
cv::hal::test_hal_intrin_uint32();
cv::hal::test_hal_intrin_int32();
cv::hal::test_hal_intrin_uint64();
cv::hal::test_hal_intrin_int64();
cv::hal::test_hal_intrin_float32();
cv::hal::test_hal_intrin_float64();
}
#endif
}
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");
register_vector<cv::KeyPoint>("KeyPointVector");
register_vector<cv::DMatch>("DMatchVector");
register_vector<std::vector<cv::DMatch>>("DMatchVectorVector");
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(Size, int)>(&binding_utils::matEye))
.class_function("eye", select_overload<Mat(int, int, int)>(&binding_utils::matEye))
.class_function("ones", select_overload<Mat(Size, int)>(&binding_utils::matOnes))
.class_function("ones", select_overload<Mat(int, int, int)>(&binding_utils::matOnes))
.class_function("zeros", select_overload<Mat(Size, int)>(&binding_utils::matZeros))
.class_function("zeros", select_overload<Mat(int, int, 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_object<cv::KeyPoint>("KeyPoint")
.field("angle", &cv::KeyPoint::angle)
.field("class_id", &cv::KeyPoint::class_id)
.field("octave", &cv::KeyPoint::octave)
.field("pt", &cv::KeyPoint::pt)
.field("response", &cv::KeyPoint::response)
.field("size", &cv::KeyPoint::size);
emscripten::value_object<cv::DMatch>("DMatch")
.field("queryIdx", &cv::DMatch::queryIdx)
.field("trainIdx", &cv::DMatch::trainIdx)
.field("imgIdx", &cv::DMatch::imgIdx)
.field("distance", &cv::DMatch::distance);
emscripten::value_array<cv::Scalar_<double>> ("Scalar")
.element(emscripten::index<0>())
.element(emscripten::index<1>())
.element(emscripten::index<2>())
.element(emscripten::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());
#ifdef HAVE_OPENCV_IMGPROC
function("minEnclosingCircle", select_overload<binding_utils::Circle(const cv::Mat&)>(&binding_utils::minEnclosingCircle));
function("floodFill", select_overload<int(cv::Mat&, cv::Mat&, Point, Scalar, emscripten::val, Scalar, Scalar, int)>(&binding_utils::floodFill_wrapper));
function("floodFill", select_overload<int(cv::Mat&, cv::Mat&, Point, Scalar, emscripten::val, Scalar, Scalar)>(&binding_utils::floodFill_wrapper_1));
function("floodFill", select_overload<int(cv::Mat&, cv::Mat&, Point, Scalar, emscripten::val, Scalar)>(&binding_utils::floodFill_wrapper_2));
function("floodFill", select_overload<int(cv::Mat&, cv::Mat&, Point, Scalar, emscripten::val)>(&binding_utils::floodFill_wrapper_3));
function("floodFill", select_overload<int(cv::Mat&, cv::Mat&, Point, Scalar)>(&binding_utils::floodFill_wrapper_4));
#endif
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));
#ifdef HAVE_OPENCV_IMGPROC
function("morphologyDefaultBorderValue", &cv::morphologyDefaultBorderValue);
#endif
function("CV_MAT_DEPTH", &binding_utils::cvMatDepth);
#ifdef HAVE_OPENCV_VIDEO
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));
#endif
function("getBuildInformation", &binding_utils::getBuildInformation);
#ifdef HAVE_PTHREADS_PF
function("parallel_pthreads_set_threads_num", &cv::parallel_pthreads_set_threads_num);
function("parallel_pthreads_get_threads_num", &cv::parallel_pthreads_get_threads_num);
#endif
#ifdef TEST_WASM_INTRIN
function("test_hal_intrin_uint8", &binding_utils::test_hal_intrin_uint8);
function("test_hal_intrin_int8", &binding_utils::test_hal_intrin_int8);
function("test_hal_intrin_uint16", &binding_utils::test_hal_intrin_uint16);
function("test_hal_intrin_int16", &binding_utils::test_hal_intrin_int16);
function("test_hal_intrin_uint32", &binding_utils::test_hal_intrin_uint32);
function("test_hal_intrin_int32", &binding_utils::test_hal_intrin_int32);
function("test_hal_intrin_uint64", &binding_utils::test_hal_intrin_uint64);
function("test_hal_intrin_int64", &binding_utils::test_hal_intrin_int64);
function("test_hal_intrin_float32", &binding_utils::test_hal_intrin_float32);
function("test_hal_intrin_float64", &binding_utils::test_hal_intrin_float64);
function("test_hal_intrin_all", &binding_utils::test_hal_intrin_all);
#endif
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);
}

View File

@@ -0,0 +1,912 @@
###############################################################################
#
# 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 *
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', # special case, implemented in core_bindings.cpp
'phaseCorrelate',
'randShuffle',
'calibrationMatrixValues', #double&
'undistortPoints', # global redefinition
'CamShift', #Rect&
'meanShift' #Rect&
]
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 = None
exec(open(os.environ["OPENCV_JS_WHITELIST"]).read())
assert(white_list)
# 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 = handle_vector(tp[tp.find('_') + 1:])
tp = 'std::vector<' + "::".join(tp.split('_')) + '>'
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[0].rsplit(" ", 1)[1]
namespace, classes, val = self.split_decl_name(name)
namespace = '.'.join(namespace)
ns = self.namespaces.setdefault(namespace, Namespace())
if len(name) == 0: name = "<unnamed>"
if name.endswith("<unnamed>"):
i = 0
while True:
i += 1
candidate_name = name.replace("<unnamed>", "unnamed_%u" % i)
if candidate_name not in ns.enums:
name = candidate_name
break;
cname = name.replace('.', '::')
type_dict[normalize_class_name(name)] = cname
if name in ns.enums:
print("Generator warning: enum %s (cname=%s) already exists" \
% (name, cname))
# sys.exit(-1)
else:
ns.enums[name] = []
for item in decl[3]:
ns.enums[name].append(item)
const_decls = decl[3]
for decl in const_decls:
name = decl[0]
self.add_const(name.replace("const ", "").strip(), decl)
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 in ['int', 'float', 'double', 'char', 'uchar', 'String', 'std::string']:
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
headers = []
for hdr in src_files:
decls = self.parser.parse(hdr)
# print(hdr);
# self.print_decls(decls);
if len(decls) == 0:
continue
headers.append(hdr[hdr.rindex('opencv2/'):])
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.items():
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:
arg_type = type_dict[arg.tp] if arg.tp in type_dict else arg.tp
args.append(arg_type)
# 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.items():
# print("ext constructor", method_name)
#if class_info.ext_constructors:
# Generate bindings for properties
for property in class_info.props:
_class_property = class_property_enum_template if property.tp in type_dict else class_property_template
class_bindings.append(_class_property.substitute(js_name=property.name, cpp_name='::'.join(
[class_info.cname, property.name])))
dv = ''
base = Template("""base<$base>""")
assert len(class_info.bases) <= 1 , "multiple inheritance not supported"
if len(class_info.bases) == 1:
dv = "," + base.substitute(base=', '.join(class_info.bases))
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()
header_includes = '\n'.join(['#include "{}"'.format(hdr) for hdr in headers])
ret = ret.replace('@INCLUDES@', header_includes)
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)

View File

@@ -0,0 +1,403 @@
// //////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
if (typeof Module.FS === 'undefined' && typeof FS !== 'undefined') {
Module.FS = FS;
}
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;
};

View File

@@ -0,0 +1,115 @@
###############################################################################
#
# 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 if (typeof window === 'object') {
// Browser globals
root.cv = factory();
} else if (typeof importScripts === 'function') {
// Web worker
root.cv = factory;
} else {
// Other shells, e.g. d8
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]
if not os.path.isfile(opencvjs):
print('opencv.js file not found! Have you compiled the opencv_js module?')
exit()
make_umd(opencvjs, cvjs);

View File

@@ -0,0 +1,195 @@
###############################################################################
#
# 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)""")
class_property_enum_template = Template("""
.property("$js_name", binding_utils::underlying_ptr(&$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", static_cast<long>($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;
""")