我正在尝试多线程一些 OpenCV4Android 代码。我将 432x432 图像分成 9 个 144x144 段,并将每个段传递给不同的线程:
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) {};
这是线程类:
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);
}
}
我有两个问题:
尽管线程正在正确修改各个块,但修改并未显示在最终图像中。如果按值传递给线程,这将是有意义
Mat block
的,但 Java 应该将其引用传递给线程。运行时比非线程代码长 - 在我的模拟器中,它从 ~1200 上升到 ~1500 毫秒。这是模拟器的问题,还是由于某种原因多线程在这里是一个非常糟糕的主意?