opencv4nodejs: Memory Leak: External Memory Growth When Using Async Methods in OpenCV Template Matching
I’ve identified a memory leak in a Node.js project using OpenCV for template matching operations. The external memory usage keeps increasing over time despite explicit release calls.
Environment
- Node.js version: 20
- OpenCV version: 4.10
- OS: macOS
Code Example
const full = await cv.imdecodeAsync(fs.readFileSync('src/dev/full.jpg'));
const img = await cv.imdecodeAsync(fs.readFileSync('src/dev/1.jpg'));
const matched = await full.matchTemplateAsync(img, cv.TM_CCOEFF_NORMED);
const minMax = matched.minMaxLoc();
const { maxVal } = minMax;
const matchPercentage = maxVal * 100;
console.log('matchPercentage', matchPercentage);
full.release();
img.release();
matched.release();
Memory Monitoring
setInterval(() => {
const used = process.memoryUsage();
console.log({
rss: `${Math.round(used.rss / 1024 / 1024 * 100) / 100} MB`,
heapTotal: `${Math.round(used.heapTotal / 1024 / 1024 * 100) / 100} MB`,
heapUsed: `${Math.round(used.heapUsed / 1024 / 1024 * 100) / 100} MB`,
external: `${Math.round(used.external / 1024 / 1024 * 100) / 100} MB`,
});
}, 1000);
Issue
Despite explicitly calling release() on all OpenCV Mat objects (full, img, matched), the external memory usage continues to grow:
{
"rss": "1488.89 MB",
"heapTotal": "96.58 MB",
"heapUsed": "61.1 MB",
"external": "4220.46 MB"
}
If you don’t use asynchronous methods, this problem doesn’t exist.
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 16
Yes, this issue is related to a specific operating system. My understanding should be related to V8, and the increase in RSS should be normal but not unlimited. Currently, the memory growth in my demo test has slowed down significantly, and there are no OOM issues. I will continue to monitor this phenomenon.
The code for this native module is very simple, and there may be aspects I haven’t noticed, but in any case, it’s better than the situation with opencv4nodejs.
When the release method is not called, the following crash log appears: