Skip to main content

Overview

The Mat 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, element M(i,j) is located at:
Matrices are stored row-by-row (row-major order), making row access more efficient than column access.

Creating Matrices

Basic Creation

From Existing Data

Data Types

OpenCV supports various data types:
  • CV_8U: 8-bit unsigned integer
  • CV_8S: 8-bit signed integer
  • CV_16U, CV_16S: 16-bit integers
  • CV_32S: 32-bit signed integer
  • CV_32F: 32-bit floating point
  • CV_64F: 64-bit floating point
Channel specification: CV_8UC1 (1 channel), CV_8UC3 (3 channels), CV_8UC(n) (n channels, max 512)

Reference Counting

Mat uses shallow copying by default:
For a deep copy:

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