Overview
OpenCV uses automatic memory management with reference counting for Mat objects. This eliminates most manual memory management while providing efficiency through shallow copying.Reference Counting
How It Works
Each Mat object has:- Header: Small, cheap to copy (~100 bytes)
- Data block: Large, expensive to copy
- Reference counter: Tracks how many Mat objects share the data
Shallow vs Deep Copy
Shallow Copy (default):Memory Allocation
Automatic Allocation
Constructor Allocation
UMat and Memory Allocators
MatAllocator
Custom memory allocation throughMatAllocator class:
Memory Pools
OpenCV supports buffer pooling for frequent allocations:Best Practices
Avoid Unnecessary Copies
Return Values
Pre-allocation
Manual Memory Management
External Data
Wrap user-allocated memory:Release Memory
Memory Continuity
Continuous Storage
ROI and Continuity
Common Pitfalls
Performance Considerations
Pass by Reference
Always pass Mat as const reference to avoid header copies
Use ROI
ROI creates header only, no data copy
Avoid clone()
Use shallow copies when possible
Pre-allocate
Reuse matrices in loops to avoid reallocation
Memory Debugging
See Also
- Matrices - Understanding Mat class
- Image Basics - Working with images
- Core Module - Core data structures
