通过引用复制垫



我在我的一个项目中使用OpenCV for Java。我在Mat的内存中有一些图像数据,并想创建指向相同本机内存的第二个引用(即通过引用复制Mat)。背景是我在多个地方使用Mat,并希望所有实例都指向相同的数据,同时允许所有使用release()它们的引用,一旦它们完成使用它们以避免内存泄漏。

目前,我正在这样做:

fun Mat.copyByReference(): Mat = this.submat(0, rows(), 0, cols())

这工作得很好,但不适合Mat的子类(例如MatOfKeyPoint),因为submat()总是返回Mat。因此,我的问题是是否有一种合适的方法来实现Mat的所有子类。

在查看Mat.java的源代码后,似乎有一个Mat的构造函数正好符合我的要求:

public Mat(Mat m, Rect roi) {
this.nativeObj = n_Mat(m.nativeObj, roi.y, roi.y + roi.height, roi.x, roi.x + roi.width);
}

这个构造函数也存在于所有子类中,除了那些不带roi的子类。因此,我将函数修改如下:

@Suppress("UNCHECKED_CAST")
fun <T : Mat> T.copyByReference(): T = when (this) {
is MatOfByte -> MatOfByte(this)
is MatOfDMatch -> MatOfDMatch(this)
is MatOfDouble -> MatOfDouble(this)
is MatOfFloat -> MatOfFloat(this)
is MatOfFloat4 -> MatOfFloat4(this)
is MatOfFloat6 -> MatOfFloat6(this)
is MatOfInt -> MatOfInt(this)
is MatOfInt4 -> MatOfInt4(this)
is MatOfKeyPoint -> MatOfKeyPoint(this)
is MatOfPoint -> MatOfPoint(this)
is MatOfPoint2f -> MatOfPoint2f(this)
is MatOfPoint3 -> MatOfPoint3(this)
is MatOfPoint3f -> MatOfPoint3f(this)
is MatOfRect -> MatOfRect(this)
is MatOfRect2d -> MatOfRect2d(this)
is MatOfRotatedRect -> MatOfRotatedRect(this)
else -> Mat(this, Rect(0, 0, cols(), rows()))
} as T

最新更新