hybridgroup / gocv

Go package for computer vision using OpenCV 4 and beyond. Includes support for DNN, CUDA, OpenCV Contrib, and OpenVINO.
https://gocv.io
Other
6.74k stars 868 forks source link

Region() memory leak #1246

Closed xins981 closed 3 weeks ago

xins981 commented 1 month ago

Region() croped image share origin image memory, but after free origin image, cropped image still use memory.

leak code: origin := gocv.NewMat() defer origin.Close() crop = origin.Region(rect)

I try free apparently "crop", but os throw re-free error.

image

but don't free will leak memory.

how solve this?

deadprogram commented 1 month ago

You probably should call close on the region before you call it on the original? Hard to tell from just that code.

You probably should run your tests using -tags matprofile to find the leaks in your program. See https://github.com/hybridgroup/gocv?tab=readme-ov-file#profiling

xins981 commented 1 month ago

Hi, deadprogram!

  1. I have test the Region() code through ablation experiment and monitoring top res, actually this is the source of memory leak.
  2. In fact, I first free sub-region then origin image(defer() LIFO) that still leak.

Has you any else advice?

deadprogram commented 1 month ago

The code for that function is tested here https://github.com/hybridgroup/gocv/blob/6935b87203d369548b1611d55a7b220fa80d9e97/core_test.go#L765 and is run with the MatProfile tests, so I do not see how that function is inherently the source. I'd again suggest running your tests using the profiler.

Hope that helps!

xins981 commented 3 weeks ago

deadprogram, thanks your advice! you are right. the obj returned by Region can be free normally. I re-try free origin image two, this is source.