Skip to content

Memory Leak: External Memory Growth When Using Async Methods in OpenCV Template Matching #173

Description

@luckyyyyy

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions