gocv icon indicating copy to clipboard operation
gocv copied to clipboard

May resource tracker be useful for auto GC ?

Open garfeng opened this issue 2 years ago • 0 comments

May resource tracker be useful for auto GC ? Like opencvSharp.

Description

When use Mat.Region(), FindContours(), GetStructingElement() ...... and many other functions, Close() is required, otherwise it will cause memory leak.

I understand that, using runtime.SetFinalizer may cause other thing bad.

So I read some wrapper of other language, such as c#.

https://github.com/shimat/opencvsharp

I got some examples here:

using (var t = new ResourcesTracker())
{
    Mat mat1 = t.NewMat(new Size(100, 100), MatType.CV_8UC3, new Scalar(0));
    Mat mat3 = t.T(255-t.T(mat1*0.8));
    Mat[] mats1 = t.T(mat3.Split());
    Mat mat4 = t.NewMat();
    Cv2.Merge(new Mat[] { mats1[0], mats1[1], mats1[2] }, mat4);
}

using (var t = new ResourcesTracker())
{
    var src = t.T(new Mat(@"lenna.png", ImreadModes.Grayscale));
    var dst = t.NewMat();
    Cv2.Canny(src, dst, 50, 200);
    var blurredDst = t.T(dst.Blur(new Size(3, 3)));
    t.T(new Window("src image", src));
    t.T(new Window("dst image", blurredDst));
    Cv2.WaitKey();
}    

I have written an example in GO:

The Main code is here: https://github.com/garfeng/gocv_resource_tracker/blob/master/tracker/tracker.go https://github.com/garfeng/gocv_resource_tracker/blob/master/resource_tracker.go

a simple example:

func Example() {
	rt := NewTracker()
	defer rt.Close() // only one time close needed
	
	mat := rt.NewMat()
	// ...
	// do something with mat
	kernel := rt.GetStructuringElement(gocv.MorphRect, image.Pt(10, 10))
	dst := rt.NewMat()
	
	gocv.Erode(mat, &dst, kernel)
}

Is it suitable for GoCV?

Independent as another package, or inside gocv, which is better ? Or in other way?

May you give me some suggestions?

I will contribute to it.

garfeng avatar May 10 '22 03:05 garfeng