Overview
TheMat class is the fundamental data structure in OpenCV, representing an n-dimensional dense numerical array. It can store images, matrices, vectors, histograms, point clouds, and other multi-dimensional data.
Mat Structure
Key Properties
A Mat object consists of:- Header: Contains metadata (dimensions, type, reference counter)
- Data pointer: Points to the actual pixel/element data
- Step array: Defines memory layout for multi-dimensional indexing
Memory Layout
For a 2D matrix, elementM(i,j) is located at:
Creating Matrices
Basic Creation
From Existing Data
Data Types
OpenCV supports various data types:CV_8U: 8-bit unsigned integerCV_8S: 8-bit signed integerCV_16U,CV_16S: 16-bit integersCV_32S: 32-bit signed integerCV_32F: 32-bit floating pointCV_64F: 64-bit floating point
CV_8UC1 (1 channel), CV_8UC3 (3 channels), CV_8UC(n) (n channels, max 512)
Reference Counting
Mat uses shallow copying by default:Element Access
Direct Access
Iterator Access
ROI (Region of Interest)
ROI operations are O(1) as they only create a new header pointing to the same data.
Continuous Matrices
Check if matrix data is continuous (no gaps between rows):Best Practices
Use ROI
Work with sub-matrices using ROI instead of copying data
Prefer Row Access
Access rows sequentially for better cache performance
Check Continuity
Optimize processing for continuous matrices
Deep Copy When Needed
Use clone() when you need independent data
See Also
- Image Basics - Working with images as matrices
- Memory Management - Understanding Mat memory model
- Core Module - Basic Mat operations
