OpenCV.js in Web Worker problem

asked 2018-09-12 06:54:18 -0600

m93c gravatar image

Hi everyone!
In my application I have to use multiple haar cascades so I thought that using parallel computing would be a good idea.
To achieve this I'm trying to use OpenCV's classifiers in Web Workers but I'm having some problems with them.
My worker code is as follows:

importScripts("./opencv.js");
importScripts("./utils.js");
let utils = new Utils('errorMessage');
let cascadeFile = 'HAAR_19Stages.xml';
let num = new cv.RectVector();
let result = false;
var classifier = new cv.CascadeClassifier();

init = function () {

    utils.createFileFromUrl(cascadeFile, cascadeFile, () => {
        classifier.load(cascadeFile);
    })
}

self.addEventListener('message', function (e) {

    let frame = e.data.grayScaleframe;
    classifier.detectMultiScale(frame, num, 1.1, 3, 0, new cv.Size(10, 10), new cv.Size(300, 300));
    if (num.size() > 0) {
        result = true;
    } else {
        result = false;
    }
    self.postMessage(result);
}, false)

init();

First I load the classifier with the "init" function, then, from the main thread, I call the code sending a message to the event listener. I pass a frame (grayScaleframe) and I want to analyze it with detectMultiScale.
The problem is that it gives me the error "Uncaught TypeError: Cannot read property '$$' of undefined" when using the "detectMultiScale" function. It's like if it forgets of the classifier declaration and initialization.
Since I'm new to Web Workers and OpenCV.js, I was asking if some of you has a solution to this.
Thank you

edit retag flag offensive close merge delete

Comments

idk how it is with the js bindings, but the c++ CascadeClassifier is NOT threadsafe

(it has an "inner state", so you cannot use the same cascade with several threads at the same time)

berak gravatar imageberak ( 2018-09-13 01:47:44 -0600 )edit

I wanted to declare a classifier in a thread and then use it only in that thread. Another thread will use a different classifier declared only in it. So (I think) there's no concurrency problem since they are different threads with different resources, or am I wrong?

m93c gravatar imagem93c ( 2018-09-13 07:38:15 -0600 )edit

sorry, but all of this is kinda "unexplored territory"

while your concept sounds sane, we may have no idea, what's actually happening with js.

berak gravatar imageberak ( 2018-09-13 13:41:15 -0600 )edit

Ok, no problem. I've seen it can handle 2-3 classifiers in the main thread so I'll put them there for now.

m93c gravatar imagem93c ( 2018-09-14 02:01:20 -0600 )edit