webarkit / webarkit-cv

WebARKit thanks to OpenCV and Emscripten
4 stars 1 forks source link

Import opencv_js.js as a ES6 module into WebARKit #1

Open kalwalt opened 1 year ago

kalwalt commented 1 year ago

I leave some comments here to describe how you can import the opencv_js.js lib as an ES6 module into WebARKit and in other projects. The opencv js lib as it is can not be imported as a ES6 module, you need to modify the build Emscripten instructions. Infact now it lacks of the right commands:

set(EMSCRIPTEN_LINK_FLAGS "${EMSCRIPTEN_LINK_FLAGS} -s MODULARIZE=1")
set(EMSCRIPTEN_LINK_FLAGS "${EMSCRIPTEN_LINK_FLAGS} -s EXPORT_NAME=\"'cv'\" -s DEMANGLE_SUPPORT=1")

https://github.com/opencv/opencv/blob/a4ff46aab7b6325d76c83bfd55b5f70ccc13248f/modules/js/CMakeLists.txt#L73-L74 The MODULARIZE and EXPORT_NAME options are not sufficient for this feature. You need to add -s EXPORT_ES6=1 -s USE_ES6_IMPORT_META=0 as i did in this commit in this repository (see my opencv fork at this commit ) Doing this and you will be able to import cv into the project and use a bundler as i did.

This as a downside: it will be impossible to load in a Node.js env so i think it should be created as a separate build lib.

Note, that if you want to test the code probably that commit is not included as a submodule. I have to change the submodule url https://github.com/kalwalt/webarkit-cv/blob/4aba299b53df7d6dde63483d7cc10b2a7a0f6f81/.gitmodules#L3 I will fix this in a near future, probably i will make a fork in the webarkit org, and switch to this.

kalwalt commented 1 year ago

I discovered that it's not needed to alter the CMakeLists.txt file, just add a --build_flags option as i did in https://github.com/webarkit/webarkit-cv/commit/6c9bdaa6d7ea5d1fb3fbb826aedf3ceec6aa15a3 --build_flags="-s EXPORT_ES6=1 -s USE_ES6_IMPORT_META=0"

kalwalt commented 1 year ago

Actually the opencv_js.js file is 5113 Kb in size, i will see if i can shrink it; in a WebAR perspective this is a huge file.

kalwalt commented 1 year ago

compiled with emsdk 2.0.10 the opencv_js.js file is 4600 Kb with the same set up. I will sue this for now to avoid also this issue see comment. I was able to build with docker, using a newer emsdk instead will fails if you not applly that changes mentioned in the comment.