Skip to main content

Statistical Functions

sum

Scalar sum(InputArray src)
Calculates the sum of array elements.
src
InputArray
Input array (1 to 4 channels)
return
Scalar
Sum of all array elements for each channel
Example:
Mat img(100, 100, CV_8UC3);
Scalar total = sum(img); // Returns sum for each channel
double blueSum = total[0];
double greenSum = total[1];
double redSum = total[2];

mean

Scalar mean(InputArray src, InputArray mask = noArray())
Calculates the mean value of array elements.
src
InputArray
Input array (1 to 4 channels)
mask
InputArray
Optional operation mask (8-bit single channel)
return
Scalar
Mean value for each channel
Example:
Mat img;
Scalar avgColor = mean(img); // Average color

Mat mask;
Scalar avgInRegion = mean(img, mask); // Average within masked region

meanStdDev

void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
                InputArray mask = noArray())
Calculates mean and standard deviation of array elements.
src
InputArray
Input array (1 to 4 channels)
mean
OutputArray
Output parameter: calculated mean value
stddev
OutputArray
Output parameter: calculated standard deviation
mask
InputArray
Optional operation mask
Example:
Mat img;
Mat mean, stddev;
meanStdDev(img, mean, stddev);

std::cout << "Mean: " << mean << std::endl;
std::cout << "Std Dev: " << stddev << std::endl;

minMaxLoc

void minMaxLoc(InputArray src, double* minVal, double* maxVal = 0,
               Point* minLoc = 0, Point* maxLoc = 0, InputArray mask = noArray())
Finds the global minimum and maximum in an array.
src
InputArray
Input single-channel array
minVal
double*
Pointer to returned minimum value (can be NULL)
maxVal
double*
Pointer to returned maximum value (can be NULL)
minLoc
Point*
Pointer to returned minimum location (can be NULL)
maxLoc
Point*
Pointer to returned maximum location (can be NULL)
mask
InputArray
Optional mask to select a sub-array
Example:
Mat img;
double minVal, maxVal;
Point minLoc, maxLoc;

minMaxLoc(img, &minVal, &maxVal, &minLoc, &maxLoc);

std::cout << "Min: " << minVal << " at " << minLoc << std::endl;
std::cout << "Max: " << maxVal << " at " << maxLoc << std::endl;

norm

double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray())
double norm(InputArray src1, InputArray src2, int normType = NORM_L2,
            InputArray mask = noArray())
Calculates an absolute array norm, absolute difference norm, or relative difference norm.
src1
InputArray
First input array
src2
InputArray
Second input array (for difference norms)
normType
int
Type of norm: NORM_INF, NORM_L1, NORM_L2, NORM_L2SQR, NORM_HAMMING, NORM_HAMMING2
mask
InputArray
Optional operation mask
return
double
Calculated norm value
Norm Types:
  • NORM_INF: max(|x_i|)
  • NORM_L1: Σ|x_i|
  • NORM_L2: √(Σx_i²)
  • NORM_L2SQR: Σx_i²
Example:
Mat vec1, vec2;
double l2norm = norm(vec1, NORM_L2);
double diff = norm(vec1, vec2, NORM_L2); // Euclidean distance

normalize

void normalize(InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
               int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray())
Normalizes the norm or value range of an array.
src
InputArray
Input array
dst
InputOutputArray
Output array (same size as src)
alpha
double
Norm value to normalize to or lower range boundary in range normalization
beta
double
Upper range boundary in range normalization (not used for norm normalization)
norm_type
int
Normalization type: NORM_INF, NORM_L1, NORM_L2, or NORM_MINMAX
dtype
int
Optional depth of output array
mask
InputArray
Optional operation mask
Example:
Mat src, dst;

// Normalize to range [0, 255]
normalize(src, dst, 0, 255, NORM_MINMAX, CV_8U);

// Normalize to unit norm
normalize(src, dst, 1.0, 0, NORM_L2);

countNonZero

int countNonZero(InputArray src)
Counts non-zero array elements.
src
InputArray
Single-channel array
return
int
Number of non-zero elements
Example:
Mat binary;
threshold(img, binary, 128, 255, THRESH_BINARY);
int whitePixels = countNonZero(binary);

hasNonZero

bool hasNonZero(InputArray src)
Checks if there are any non-zero elements in array.
return
bool
True if at least one non-zero element exists
Example:
Mat mask;
if (hasNonZero(mask)) {
    // Process masked region
}

findNonZero

void findNonZero(InputArray src, OutputArray idx)
Returns the list of locations of non-zero pixels.
src
InputArray
Single-channel array (8-bit or floating-point)
idx
OutputArray
Output array of Point locations (N×1 or 1×N)
Example:
Mat binary;
threshold(img, binary, 128, 255, THRESH_BINARY);

std::vector<Point> locations;
findNonZero(binary, locations);

for(const Point& pt : locations) {
    // Process each non-zero pixel location
}

Reduction Operations

reduce

void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1)
Reduces a matrix to a vector by applying an operation along a specified dimension.
src
InputArray
Input array
dst
OutputArray
Output vector
dim
int
Dimension to reduce: 0 (reduce to single row), 1 (reduce to single column)
rtype
int
Reduction operation: REDUCE_SUM, REDUCE_AVG, REDUCE_MAX, REDUCE_MIN, REDUCE_SUM2
dtype
int
Optional depth of output array
Operations:
  • REDUCE_SUM: Sum of all rows/columns
  • REDUCE_AVG: Mean of all rows/columns
  • REDUCE_MAX: Maximum of all rows/columns
  • REDUCE_MIN: Minimum of all rows/columns
  • REDUCE_SUM2: Sum of squared values
Example:
Mat matrix(100, 100, CV_32F);
Mat columnSums, rowMeans;

reduce(matrix, columnSums, 0, REDUCE_SUM); // Sum each column
reduce(matrix, rowMeans, 1, REDUCE_AVG);   // Mean of each row

reduceArgMin

void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false)
Finds indices of minimum elements along specified axis.
src
InputArray
Input array
dst
OutputArray
Output array of indices
axis
int
Dimension to reduce along
lastIndex
bool
Whether to return last index in case of multiple minimum values
Example:
Mat data, minIndices;
reduceArgMin(data, minIndices, 1); // Index of min in each row

reduceArgMax

void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false)
Finds indices of maximum elements along specified axis. Example:
Mat data, maxIndices;
reduceArgMax(data, maxIndices, 0); // Index of max in each column

Sorting

sort

void sort(InputArray src, OutputArray dst, int flags)
Sorts each matrix row or column in ascending or descending order.
src
InputArray
Input single-channel array
dst
OutputArray
Output array (same size and type as src)
flags
int
Operation flags: SORT_EVERY_ROW, SORT_EVERY_COLUMN, SORT_ASCENDING, SORT_DESCENDING
Example:
Mat data, sorted;
sort(data, sorted, SORT_EVERY_ROW | SORT_ASCENDING);

sortIdx

void sortIdx(InputArray src, OutputArray dst, int flags)
Sorts each matrix row or column and returns sorted indices instead of values.
dst
OutputArray
Output integer array of sorted indices
Example:
Mat values, indices;
sortIdx(values, indices, SORT_EVERY_ROW | SORT_DESCENDING);

Linear Algebra

determinant

double determinant(InputArray mtx)
Returns the determinant of a square matrix.
mtx
InputArray
Input matrix (must be square)
return
double
Determinant value
Example:
Mat A(3, 3, CV_64F);
double det = determinant(A);

trace

Scalar trace(InputArray mtx)
Returns the trace (sum of diagonal elements) of a matrix.
mtx
InputArray
Input matrix
return
Scalar
Trace of the matrix
Formula:
trace(A) = Σ A[i,i]
Example:
Mat A;
Scalar tr = trace(A);

invert

double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU)
Finds the inverse or pseudo-inverse of a matrix.
src
InputArray
Input floating-point matrix
dst
OutputArray
Output matrix of the same size and type as src
flags
int
Inversion method: DECOMP_LU, DECOMP_SVD, DECOMP_CHOLESKY
return
double
Reciprocal condition number (for SVD) or 0 if singular
Decomposition Methods:
  • DECOMP_LU: LU decomposition (fastest for well-conditioned matrices)
  • DECOMP_SVD: Singular value decomposition (works for singular matrices)
  • DECOMP_CHOLESKY: Cholesky decomposition (for symmetric positive-definite matrices)
Example:
Mat A, invA;
double rcond = invert(A, invA, DECOMP_SVD);
if (rcond > 1e-6) {
    // Matrix is well-conditioned
}

solve

bool solve(InputArray src1, InputArray src2, OutputArray dst, int flags = DECOMP_LU)
Solves one or more linear systems or least-squares problems.
src1
InputArray
Coefficient matrix (A in Ax=b)
src2
InputArray
Right-hand side matrix (b in Ax=b)
dst
OutputArray
Output solution (x in Ax=b)
flags
int
Solution method: DECOMP_LU, DECOMP_SVD, DECOMP_CHOLESKY, DECOMP_QR, DECOMP_NORMAL
return
bool
True if solution exists
Example:
Mat A, b, x;
// Solve Ax = b
if (solve(A, b, x, DECOMP_LU)) {
    std::cout << "Solution: " << x << std::endl;
}

eigen

bool eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors = noArray())
Calculates eigenvalues and eigenvectors of a symmetric matrix.
src
InputArray
Input symmetric square matrix
eigenvalues
OutputArray
Output vector of eigenvalues (in descending order)
eigenvectors
OutputArray
Output matrix of eigenvectors (one per row)
return
bool
True if successful
Example:
Mat covar, eigenvalues, eigenvectors;
calcCovarMatrix(samples, covar, mean, COVAR_NORMAL | COVAR_ROWS);
eigen(covar, eigenvalues, eigenvectors);

// First eigenvector (principal component)
Mat pc1 = eigenvectors.row(0);
This function is optimized for symmetric matrices. For general matrices, use eigenNonSymmetric().

calcCovarMatrix

void calcCovarMatrix(InputArray samples, OutputArray covar, InputOutputArray mean,
                     int flags, int ctype = CV_64F)
Calculates covariance matrix of a set of vectors.
samples
InputArray
Input samples (each row or column is a sample)
covar
OutputArray
Output covariance matrix
mean
InputOutputArray
Input or output mean vector
flags
int
Operation flags: COVAR_SCRAMBLED, COVAR_NORMAL, COVAR_USE_AVG, COVAR_SCALE, COVAR_ROWS, COVAR_COLS
ctype
int
Type of output matrices (CV_32F or CV_64F)
Example:
Mat samples(1000, 5, CV_32F); // 1000 samples, 5 dimensions
Mat covar, mean;

calcCovarMatrix(samples, covar, mean, 
                COVAR_NORMAL | COVAR_ROWS | COVAR_SCALE, CV_32F);

Timing and Profiling

getTickCount

int64 getTickCount()
Returns the number of ticks since a certain event (e.g., machine startup).
return
int64
Current tick count
Example:
int64 t1 = getTickCount();
// ... perform operation ...
int64 t2 = getTickCount();
double time = (t2 - t1) / getTickFrequency();
std::cout << "Time: " << time << " seconds" << std::endl;

getTickFrequency

double getTickFrequency()
Returns the number of ticks per second.
return
double
Tick frequency in Hz

TickMeter

class TickMeter {
public:
    void start();
    void stop();
    void reset();
    double getTimeSec() const;
    double getTimeMilli() const;
    double getTimeMicro() const;
    int64 getCounter() const;
    double getFPS() const;
};
A class to measure passing time and calculate performance metrics. Example:
cv::TickMeter tm;
tm.start();
// ... perform operation ...
tm.stop();

std::cout << "Time: " << tm.getTimeMilli() << " ms" << std::endl;
std::cout << "FPS: " << tm.getFPS() << std::endl;

System Information

getNumberOfCPUs

int getNumberOfCPUs()
Returns the number of logical CPUs available for the process.

setNumThreads

void setNumThreads(int nthreads)
Sets the number of threads used by OpenCV for parallel regions.
nthreads
int
Number of threads. Use 0 or negative values to reset to default

getNumThreads

int getNumThreads()
Returns the number of threads used by OpenCV for parallel regions.

getBuildInformation

String getBuildInformation()
Returns full configuration time cmake output including version, compiler, enabled modules, etc. Example:
std::cout << getBuildInformation() << std::endl;

getVersionString

String getVersionString()
Returns library version string (e.g., “4.8.0”).

getCPUFeaturesLine

std::string getCPUFeaturesLine()
Returns a string containing CPU features enabled during compilation. Example output:
SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *AVX *AVX2
  • No marker: baseline features
  • *: features enabled in dispatcher
  • ?: features enabled but not available in hardware

Utility Functions

setUseOptimized

void setUseOptimized(bool onoff)
Enables or disables optimized code (SSE, AVX, etc.).
onoff
bool
True to enable optimizations, false to disable

useOptimized

bool useOptimized()
Returns the status of optimized code usage.

checkRange

bool checkRange(InputArray a, bool quiet = true, Point* pos = 0,
                double minVal = -DBL_MAX, double maxVal = DBL_MAX)
Checks every element of an input array for invalid values.
a
InputArray
Input array
quiet
bool
If true, doesn’t throw exceptions on invalid values
pos
Point*
Optional output parameter for position of first invalid value
minVal
double
Minimum valid value (inclusive)
maxVal
double
Maximum valid value (inclusive)
return
bool
True if all elements are within range and not NaN/Inf
Example:
Mat result;
// ... computation ...
if (!checkRange(result)) {
    std::cerr << "Invalid values detected (NaN or Inf)" << std::endl;
}

patchNaNs

void patchNaNs(InputOutputArray a, double val = 0)
Replaces all NaN values in an array with specified value.
a
InputOutputArray
Input/output floating-point array
val
double
Value to replace NaNs with
Example:
Mat data;
// ... computation that might produce NaNs ...
patchNaNs(data, 0.0); // Replace NaNs with zeros

LUT

void LUT(InputArray src, InputArray lut, OutputArray dst)
Performs a look-up table transform of an array.
src
InputArray
Input array (8-bit elements)
lut
InputArray
Look-up table (256 elements)
dst
OutputArray
Output array (same size as src)
Example:
// Create a gamma correction LUT
Mat lut(1, 256, CV_8U);
for(int i = 0; i < 256; i++)
    lut.at<uchar>(i) = saturate_cast<uchar>(pow(i / 255.0, 0.5) * 255.0);

Mat img, corrected;
LUT(img, lut, corrected); // Apply gamma correction

convertScaleAbs

void convertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0)
Scales, calculates absolute values, and converts to 8-bit unsigned type.
src
InputArray
Input array
dst
OutputArray
Output array (CV_8U type)
alpha
double
Scale factor
beta
double
Delta added to scaled values
Formula:
dst(I) = saturate_cast<uchar>(|src(I) · alpha + beta|)
Example:
Mat gradient_x, abs_gradient;
Sobel(img, gradient_x, CV_16S, 1, 0);
convertScaleAbs(gradient_x, abs_gradient);

PSNR

double PSNR(InputArray src1, InputArray src2, double R = 255.0)
Computes Peak Signal-to-Noise Ratio (PSNR) between two images.
src1
InputArray
First input array
src2
InputArray
Second input array (same size and type as src1)
R
double
Maximum pixel value (255.0 for 8-bit images)
return
double
PSNR value in decibels (dB)
Example:
Mat original, compressed;
double psnr = PSNR(original, compressed);
std::cout << "PSNR: " << psnr << " dB" << std::endl;
Higher PSNR values indicate better quality. Typical values range from 20 to 50 dB, with 30-50 dB being good quality.