openCV js Loading a trained model file

asked 2018-05-25 03:39:26 -0600

Hello, I had trouble loading a model in openCV js. It came from js lack of access to fileSystem. I didn't find any related issue but I resolved the problem thanks to a bit of help from IRC. I'm posting the answer just beneath.

The trick was loading the file trough XML request then giving it to cv.FS_createDataFile. Then you just CascadeCassifier.load(path) to get your model. I couldn't get it to work with parametrized declaration though, but it may be because of emscripten compilation problem.

// parameters:
// path: string to access loaded file trough cv
// url: path of the actual file on your FS
// callback: what to do when file is loaded
createFileFromUrl = function(path, url, callback) {
    let request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function(ev) {
        request = this;
        if (request.readyState === 4) {
            if (request.status === 200) {
                let data = new Uint8Array(request.response);
                cv.FS_createDataFile('/', path, data, true, false, false);
                callback();
            } else {
                console.error('Failed to load ' + url + ' status: ' + request.status);
            }
        }
    };
    request.send();
}
edit retag flag offensive close merge delete