Statistical Functions
sum
Scalar sum(InputArray src)
Calculates the sum of array elements.
Input array (1 to 4 channels)
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.
Input array (1 to 4 channels)
Optional operation mask (8-bit single channel)
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.
Input array (1 to 4 channels)
Output parameter: calculated mean value
Output parameter: calculated standard deviation
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.
Input single-channel array
Pointer to returned minimum value (can be NULL)
Pointer to returned maximum value (can be NULL)
Pointer to returned minimum location (can be NULL)
Pointer to returned maximum location (can be NULL)
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.
Second input array (for difference norms)
Type of norm: NORM_INF, NORM_L1, NORM_L2, NORM_L2SQR, NORM_HAMMING, NORM_HAMMING2
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.
Output array (same size as src)
Norm value to normalize to or lower range boundary in range normalization
Upper range boundary in range normalization (not used for norm normalization)
Normalization type: NORM_INF, NORM_L1, NORM_L2, or NORM_MINMAX
Optional depth of output array
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.
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.
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.
Single-channel array (8-bit or floating-point)
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.
Dimension to reduce: 0 (reduce to single row), 1 (reduce to single column)
Reduction operation: REDUCE_SUM, REDUCE_AVG, REDUCE_MAX, REDUCE_MIN, REDUCE_SUM2
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.
Dimension to reduce along
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.
Input single-channel array
Output array (same size and type as src)
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.
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.
Input matrix (must be square)
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.
Formula:
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.
Input floating-point matrix
Output matrix of the same size and type as src
Inversion method: DECOMP_LU, DECOMP_SVD, DECOMP_CHOLESKY
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.
Coefficient matrix (A in Ax=b)
Right-hand side matrix (b in Ax=b)
Output solution (x in Ax=b)
Solution method: DECOMP_LU, DECOMP_SVD, DECOMP_CHOLESKY, DECOMP_QR, DECOMP_NORMAL
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.
Input symmetric square matrix
Output vector of eigenvalues (in descending order)
Output matrix of eigenvectors (one per row)
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.
Input samples (each row or column is a sample)
Input or output mean vector
Operation flags: COVAR_SCRAMBLED, COVAR_NORMAL, COVAR_USE_AVG, COVAR_SCALE, COVAR_ROWS, COVAR_COLS
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
Returns the number of ticks since a certain event (e.g., machine startup).
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.
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;
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.
Number of threads. Use 0 or negative values to reset to default
getNumThreads
Returns the number of threads used by OpenCV for parallel regions.
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.).
True to enable optimizations, false to disable
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.
If true, doesn’t throw exceptions on invalid values
Optional output parameter for position of first invalid value
Minimum valid value (inclusive)
Maximum valid value (inclusive)
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.
Input/output floating-point array
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.
Input array (8-bit elements)
Look-up table (256 elements)
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.
Output array (CV_8U type)
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.
Second input array (same size and type as src1)
Maximum pixel value (255.0 for 8-bit images)
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.