Skip to content

Commit

Permalink
Merge pull request opencv#9466 from huningxin:js
Browse files Browse the repository at this point in the history
GSoC 2017: Improve and Extend the JavaScript Bindings for OpenCV (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 (opencv#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 opencv#23

* Fix test cases after opencv#34

Fix opencv#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 opencv#43

* Fix build of js doc

Limit copy_js_interactive_tutorials for doxygen build
Add dep to opencv.js

Fix opencv#53

* Implement cv.imread & cv.imshow and insert interactive pages in tutorials (opencv#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 opencv#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 opencv#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 opencv#60

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

* fix canvas name and default input image

* Expose cv::Moments

Fix opencv#85

* Add -Wno-missing-prototypes for emscripten build

* fix canvas name

* add tutorial of video input and output

* Expose enums as emscripten consts

Fix opencv#72

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

* Exclude cv::Mat for vecFromJSArray

Fix opencv#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 opencv#109

* Comment out the debug print in embindgen.py

* Expose RotatedRect

Fix opencv#96

* replace enum with constants and improve onload function

* delete some useless paras cause opencv#105 fixed this

* Modify const name

* Modify Contour Properties

* tutorials for imgprc2 and objdec

* Expose more functions for img proc tutorials

Fix opencv#76

* Expose polylines for video analysis tutorial

Fix opencv#121

* Expose constants for default parameters of img proc tutorials

Fix opencv#122

* Fix wrong parameter types of Mat.copyTo

Fix opencv#87

* Support default parameters of mat.convertTo

Fix opencv#123

* Support default parameters for external constructors

Fix opencv#131

* Revert "Expose polylines for video analysis tutorial"

This reverts commit 3ce7615.

Fix opencv#121

* Support cv.minMaxLoc

Fix opencv#127

* Expose cv.minEnclosingCircle

Fix opencv#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 opencv#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 opencv#147

* Add JS cv.Scalar object into helpers.js

* Update Install OpenCV-JavaScript tutorial page

Fix opencv#44

* Update the OpenCV-JavaScript introduction page

Fix opencv#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 opencv#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 opencv#75 and opencv#77

* support img id and element in cv.imread

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

Fix opencv#163

* Add matFromArray and matFromImageData as JS helpers

Fix opencv#79, opencv#78

* Lower camel case for Mat element getters

Fix opencv#81

* Mat.getRoiRect and tests

Fix opencv#86

* Support type for Mat.ptr

Fix opencv#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 opencv#171

* Support Mat.diag and Mat.isContinous

Fix opencv#84 and opencv#89

* Support Mat.setTo

Fix opencv#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 opencv#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 opencv#194

* Remove unnecessary files for test

Fix opencv#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 opencv#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 opencv#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 opencv#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 opencv#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 opencv#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
  • Loading branch information
Congxiang Pan authored and alalek committed Sep 25, 2017
1 parent b143f71 commit 89b6e68
Show file tree
Hide file tree
Showing 166 changed files with 15,406 additions and 10 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ OCV_OPTION(WITH_ITT "Include Intel ITT support" ON
# ===================================================
OCV_OPTION(BUILD_SHARED_LIBS "Build shared libraries (.dll/.so) instead of static ones (.lib/.a)" NOT (ANDROID OR APPLE_FRAMEWORK) )
OCV_OPTION(BUILD_opencv_apps "Build utility applications (used for example to train classifiers)" (NOT ANDROID AND NOT WINRT) IF (NOT APPLE_FRAMEWORK) )
OCV_OPTION(BUILD_opencv_js "Build JavaScript bindings by Emscripten" OFF )
OCV_OPTION(BUILD_ANDROID_EXAMPLES "Build examples for Android platform" ON IF ANDROID )
OCV_OPTION(BUILD_DOCS "Create build rules for OpenCV Documentation" ON IF (NOT WINRT OR APPLE_FRAMEWORK))
OCV_OPTION(BUILD_EXAMPLES "Build all examples" OFF )
Expand Down
45 changes: 41 additions & 4 deletions doc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ endif(HAVE_DOC_GENERATOR)

if(BUILD_DOCS AND DOXYGEN_FOUND)
# not documented modules list
list(APPEND blacklist "ts" "java" "python2" "python3" "world" "contrib_world")
list(APPEND blacklist "ts" "java" "python2" "python3" "js" "world" "contrib_world")
unset(CMAKE_DOXYGEN_TUTORIAL_CONTRIB_ROOT)
unset(CMAKE_DOXYGEN_TUTORIAL_JS_ROOT)

# gathering headers
set(paths_include)
Expand Down Expand Up @@ -134,11 +135,13 @@ if(BUILD_DOCS AND DOXYGEN_FOUND)
set(faqfile "${CMAKE_CURRENT_SOURCE_DIR}/faq.markdown")
set(tutorial_path "${CMAKE_CURRENT_SOURCE_DIR}/tutorials")
set(tutorial_py_path "${CMAKE_CURRENT_SOURCE_DIR}/py_tutorials")
set(CMAKE_DOXYGEN_TUTORIAL_JS_ROOT "- @ref tutorial_js_root")
set(tutorial_js_path "${CMAKE_CURRENT_SOURCE_DIR}/js_tutorials")
set(example_path "${CMAKE_SOURCE_DIR}/samples")

# set export variables
string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_INPUT_LIST "${rootfile} ; ${faqfile} ; ${paths_include} ; ${paths_hal_interface} ; ${paths_doc} ; ${tutorial_path} ; ${tutorial_py_path} ; ${paths_tutorial} ; ${tutorial_contrib_root}")
string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_IMAGE_PATH "${paths_doc} ; ${tutorial_path} ; ${tutorial_py_path} ; ${paths_tutorial}")
string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_INPUT_LIST "${rootfile} ; ${faqfile} ; ${paths_include} ; ${paths_hal_interface} ; ${paths_doc} ; ${tutorial_path} ; ${tutorial_py_path} ; ${tutorial_js_path} ; ${paths_tutorial} ; ${tutorial_contrib_root}")
string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_IMAGE_PATH "${paths_doc} ; ${tutorial_path} ; ${tutorial_py_path} ; ${tutorial_js_path} ; ${paths_tutorial}")
# TODO: remove paths_doc from EXAMPLE_PATH after face module tutorials/samples moved to separate folders
string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_EXAMPLE_PATH "${example_path} ; ${paths_doc} ; ${paths_sample}")
set(CMAKE_DOXYGEN_LAYOUT "${CMAKE_CURRENT_SOURCE_DIR}/DoxygenLayout.xml")
Expand All @@ -163,9 +166,43 @@ if(BUILD_DOCS AND DOXYGEN_FOUND)
configure_file(Doxyfile.in ${doxyfile} @ONLY)
configure_file(root.markdown.in ${rootfile} @ONLY)

# js tutorial assets
set(opencv_tutorial_html_dir "${CMAKE_CURRENT_BINARY_DIR}/doxygen/html")
set(js_tutorials_assets_dir "${CMAKE_CURRENT_SOURCE_DIR}/js_tutorials/js_assets")
set(js_tutorials_assets_deps "")

# make sure the build directory exists
file(MAKE_DIRECTORY "${opencv_tutorial_html_dir}")

# gather and copy specific files for js tutorials
file(GLOB_RECURSE js_assets "${js_tutorials_assets_dir}/*")
ocv_list_filterout(js_assets "\\\\.eslintrc.json")
list(APPEND js_assets "${OpenCV_SOURCE_DIR}/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/Data/box.mp4")

if(BUILD_opencv_js)
set(ocv_js_dir "${CMAKE_BINARY_DIR}/bin")
set(ocv_js "opencv.js")
list(APPEND js_assets "${ocv_js_dir}/${ocv_js}")
endif()

# copy haar cascade files
set(haar_cascade_files "")
set(data_harrcascades_path "${OpenCV_SOURCE_DIR}/data/haarcascades/")
list(APPEND js_tutorials_assets_deps "${data_harrcascades_path}/haarcascade_frontalface_default.xml" "${data_harrcascades_path}/haarcascade_eye.xml")

foreach(f ${js_assets})
get_filename_component(fname "${f}" NAME)
add_custom_command(OUTPUT "${opencv_tutorial_html_dir}/${fname}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${f}" "${opencv_tutorial_html_dir}/${fname}"
DEPENDS "${f}"
COMMENT "Copying ${fname}"
)
list(APPEND js_tutorials_assets_deps "${f}" "${opencv_tutorial_html_dir}/${fname}")
endforeach()

add_custom_target(doxygen
COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile}
DEPENDS ${doxyfile} ${rootfile} ${bibfile} ${deps}
DEPENDS ${doxyfile} ${rootfile} ${bibfile} ${deps} ${js_tutorials_assets_deps}
)
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html
DESTINATION "${OPENCV_DOC_INSTALL_PATH}"
Expand Down
2 changes: 1 addition & 1 deletion doc/Doxyfile.in
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ FORMULA_FONTSIZE = 14
FORMULA_TRANSPARENT = YES
USE_MATHJAX = YES
MATHJAX_FORMAT = HTML-CSS
MATHJAX_RELPATH = http://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0
MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0
MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
MATHJAX_CODEFILE = @CMAKE_CURRENT_SOURCE_DIR@/mymath.js
SEARCHENGINE = YES
Expand Down
22 changes: 22 additions & 0 deletions doc/js_tutorials/js_assets/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": "google",
"parserOptions": {
"ecmaVersion": 6
},
"rules": {
"max-len": ["error", 100, {"ignoreUrls": true}],
"quotes": ["error", "single"],
"indent": ["error", 4, {"ArrayExpression": "first",
"ObjectExpression": "first",
"CallExpression": {"arguments": "first"},
"SwitchCase": 1}],
"require-jsdoc": "off",
"new-cap": "off"
},
"plugins": ["html"],
"settings": {
"html/javascript-mime-types": ["text/javascript", "text/code-snippet"],
"html/indent": "0",
"html/report-bad-indent": "error"
}
}
Binary file added doc/js_tutorials/js_assets/apple.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/js_tutorials/js_assets/coins.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/js_tutorials/js_assets/cup.mp4
Binary file not shown.
Binary file added doc/js_tutorials/js_assets/handDst.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/js_tutorials/js_assets/handSrc.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions doc/js_tutorials/js_assets/js_basic_ops_copymakeborder.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image Padding Example</title>
<link href="js_example_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Image Padding Example</h2>
<p>
&lt;canvas&gt; elements named <b>canvasInput</b> and <b>canvasOutput</b> have been prepared.<br>
Click <b>Try it</b> button to see the result. You can choose another image.<br>
You can change the code in the &lt;textarea&gt; to investigate more.
</p>
<div>
<div class="control"><button id="tryIt" disabled>Try it</button></div>
<textarea class="code" rows="9" cols="100" id="codeEditor" spellcheck="false">
</textarea>
<p class="err" id="errorMessage"></p>
</div>
<div>
<div class="inputoutput">
<canvas id="canvasInput"></canvas>
<div class="caption">canvasInput <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput"></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
<script src="utils.js" type="text/javascript"></script>
<script id="codeSnippet" type="text/code-snippet">
let src = cv.imread('canvasInput');
let dst = new cv.Mat();
// You can try more different parameters
let s = new cv.Scalar(255, 0, 0, 255);
cv.copyMakeBorder(src, dst, 10, 10, 10, 10, cv.BORDER_CONSTANT, s);
cv.imshow('canvasOutput', dst);
src.delete();
dst.delete();
</script>
<script>
let utils = new Utils('errorMessage');

utils.loadCode('codeSnippet', 'codeEditor');
utils.loadImageToCanvas('lena.jpg', 'canvasInput');
utils.addFileInputHandler('fileInput', 'canvasInput');

let tryIt = document.getElementById('tryIt');
tryIt.addEventListener('click', () => {
utils.executeCode('codeEditor');
});

utils.loadOpenCv(() => {
tryIt.removeAttribute('disabled');
});
</script>
</body>
</html>
59 changes: 59 additions & 0 deletions doc/js_tutorials/js_assets/js_basic_ops_roi.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image ROI Example</title>
<link href="js_example_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Image ROI Example</h2>
<p>
&lt;canvas&gt; elements named <b>canvasInput</b> and <b>canvasOutput</b> have been prepared.<br>
Click <b>Try it</b> button to see the result. You can choose another image.<br>
You can change the code in the &lt;textarea&gt; to investigate more.
</p>
<div>
<div class="control"><button id="tryIt" disabled>Try it</button></div>
<textarea class="code" rows="9" cols="100" id="codeEditor" spellcheck="false">
</textarea>
<p class="err" id="errorMessage"></p>
</div>
<div>
<div class="inputoutput">
<canvas id="canvasInput"></canvas>
<div class="caption">canvasInput <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput"></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
<script src="utils.js" type="text/javascript"></script>
<script id="codeSnippet" type="text/code-snippet">
let src = cv.imread('canvasInput');
let dst = new cv.Mat();
// You can try more different parameters
let rect = new cv.Rect(100, 100, 200, 200);
dst = src.roi(rect);
cv.imshow('canvasOutput', dst);
src.delete();
dst.delete();
</script>
<script type="text/javascript">
let utils = new Utils('errorMessage');

utils.loadCode('codeSnippet', 'codeEditor');
utils.loadImageToCanvas('lena.jpg', 'canvasInput');
utils.addFileInputHandler('fileInput', 'canvasInput');

let tryIt = document.getElementById('tryIt');
tryIt.addEventListener('click', () => {
utils.executeCode('codeEditor');
});

utils.loadOpenCv(() => {
tryIt.removeAttribute('disabled');
});
</script>
</body>
</html>
126 changes: 126 additions & 0 deletions doc/js_tutorials/js_assets/js_bg_subtraction.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Background Subtraction Example</title>
<link href="js_example_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Background Subtraction Example</h2>
<p>
Click <b>Start/Stop</b> button to start or stop the camera capture.<br>
The <b>videoInput</b> is a &lt;video&gt; element used as input.
The <b>canvasOutput</b> is a &lt;canvas&gt; element used as output.<br>
The code of &lt;textarea&gt; will be executed when video is started.
You can modify the code to investigate more.
</p>
<div>
<div class="control"><button id="startAndStop" disabled>Start</button></div>
<textarea class="code" rows="29" cols="80" id="codeEditor" spellcheck="false">
</textarea>
</div>
<p class="err" id="errorMessage"></p>
<div>
<table cellpadding="0" cellspacing="0" width="0" border="0">
<tr>
<td>
<video id="videoInput" width="320" height="240" muted loop></video>
</td>
<td>
<canvas id="canvasOutput" width="320" height="240"></canvas>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<div class="caption">videoInput</div>
</td>
<td>
<div class="caption">canvasOutput</div>
</td>
<td></td>
<td></td>
</tr>
</table>
</div>
<script src="https://webrtc.github.io/adapter/adapter-5.0.4.js" type="text/javascript"></script>
<script src="utils.js" type="text/javascript"></script>
<script id="codeSnippet" type="text/code-snippet">
let video = document.getElementById('videoInput');
let cap = new cv.VideoCapture(video);

let frame = new cv.Mat(video.height, video.width, cv.CV_8UC4);
let fgmask = new cv.Mat(video.height, video.width, cv.CV_8UC1);
let fgbg = new cv.BackgroundSubtractorMOG2(500, 16, true);

const FPS = 30;
function processVideo() {
try {
if (!streaming) {
// clean and stop.
frame.delete(); fgmask.delete(); fgbg.delete();
return;
}
let begin = Date.now();
// start processing.
cap.read(frame);
fgbg.apply(frame, fgmask);
cv.imshow('canvasOutput', fgmask);
// schedule the next one.
let delay = 1000/FPS - (Date.now() - begin);
setTimeout(processVideo, delay);
} catch (err) {
utils.printError(err);
}
};

// schedule the first one.
setTimeout(processVideo, 0);
</script>
<script type="text/javascript">
let utils = new Utils('errorMessage');

utils.loadCode('codeSnippet', 'codeEditor');

let streaming = false;
let videoInput = document.getElementById('videoInput');
let startAndStop = document.getElementById('startAndStop');
let canvasOutput = document.getElementById('canvasOutput');
let canvasContext = canvasOutput.getContext('2d');

startAndStop.addEventListener('click', () => {
if (!streaming) {
utils.clearError();
videoInput.play().then(() => {
onVideoStarted();
});
} else {
videoInput.pause();
videoInput.currentTime = 0;
onVideoStopped();
}
});

function onVideoStarted() {
streaming = true;
startAndStop.innerText = 'Stop';
videoInput.height = videoInput.width * (videoInput.videoHeight / videoInput.videoWidth);
utils.executeCode('codeEditor');
}

function onVideoStopped() {
streaming = false;
canvasContext.clearRect(0, 0, canvasOutput.width, canvasOutput.height);
startAndStop.innerText = 'Start';
}

utils.loadOpenCv(() => {
videoInput.addEventListener('canplay', () => {
startAndStop.removeAttribute('disabled');
});
videoInput.src = 'box.mp4';
});
</script>
</body>
</html>
Loading

0 comments on commit 89b6e68

Please sign in to comment.