I'm trying to multithread some OpenCV4Android code. I divide a 432x432 image into 9 144x144 segments and pass each to a different thread:
Thread[] threads = new Thread[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
threads[3*i+j] = new Thread(new MyThread(image.rowRange(144*i, 144*(i+1)).colRange(144*j, 144*(j+1))));
threads[3*i+j].start();
}
}
for (Thread thread : threads) try {thread.join();} catch (InterruptedException e) {};
Here is the thread class:
public class MyThread implements Runnable {
final Mat block;
public MyThread(Mat block) {
this.block = block;
}
public void run() {
/* do image processing on block */
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(19,19));
Mat closed = new Mat();
Imgproc.morphologyEx(block, closed, Imgproc.MORPH_CLOSE, kernel);
Core.divide(block, closed, block, 1, CvType.CV_32F);
Core.normalize(block, block, 0, 255, Core.NORM_MINMAX);
block.convertTo(block, CvType.CV_8UC1);
Imgproc.threshold(block, block, -1, 255, Imgproc.THRESH_BINARY_INV+Imgproc.THRESH_OTSU);
}
}
I have two issues:
Although the threads are modifying the individual blocks correctly, the modifications are not showing up in the final image. This would make sense if
Mat block
were passed by value to the thread, but Java should be passing its reference to the thread instead.The runtime is longer than the unthreaded code - in my emulator, it goes up from ~1200 to ~1500 ms. Is this a problem with the emulator, or is multithreading a really bad idea here for some reason?