一、矩阵的求和函数
Reduces a matrix to a vector.
-
C++:
void
reduce
(InputArray
src, OutputArray
dst, int
dim, int
rtype, int
dtype=-1
)
¶
-
Python:
cv2.
reduce
(src, dim, rtype
[, dst
[, dtype
]
]
) → dst
-
C:
void
cvReduce
(const CvArr*
src, CvArr*
dst, int
dim=-1, int
op=CV_REDUCE_SUM
)
-
Python:
-
Parameters: - src – input 2D matrix.
- dst – output vector. Its size and type is defined by
dim
anddtype
parameters. - dim – dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row. 1 means that the matrix is reduced to a single column.
- rtype –
reduction operation that could be one of the following:
- CV_REDUCE_SUM: the output is the sum of all rows/columns of the matrix.
- CV_REDUCE_AVG: the output is the mean vector of all rows/columns of the matrix.
- CV_REDUCE_MAX: the output is the maximum (column/row-wise) of all rows/columns of the matrix.
- CV_REDUCE_MIN: the output is the minimum (column/row-wise) of all rows/columns of the matrix.
- dtype – when negative, the output vector will have the same type as the input matrix, otherwise, its type will be
CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels())
.
cv.
Reduce
(src, dst, dim=-1, op=CV_REDUCE_SUM
) → None
The function reduce
reduces the matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of a raster image. In case of CV_REDUCE_SUM
and CV_REDUCE_AVG
, the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
总结一句话:参数的选择要对应
示例:
double a[5][4] =
{
{ 4, 0, 2, 5 },
{ 1, 1, 0, 7 },
{ 0, 5, 2, 0 },
{ 0, 3, 4, 0 },
{ 8, 0, 1, 2 }
};
Mat ma(5, 4, CV_64FC1, a);
Mat mb(5, 1, CV_64FC1, Scalar(0));
Mat mc(1, 4, CV_64FC1, Scalar(0));
cout << "原矩阵:" << endl;
cout << ma << endl;
reduce(ma, mb, 1, CV_REDUCE_SUM);
cout << "列向量" << endl;
cout << mb << endl;
reduce(ma, mc, 0, CV_REDUCE_SUM);
cout << "行向量" << endl;
cout << mc << endl;
Tips: 异常信息提示
cv::reduce for SUM and 8U input can return only 32S, 32F or 64F types.
所以在进行计算的时候一定要注意矩阵的数据类型,不然会出现以下错误提示信息:
cv::reduce gives unsupported format exception
uchar matrix[5][6] = { { 1, 2, 3, 4, 5, 6 },
{ 7, 8, 9, 10, 11, 12 },
{ 13, 14, 15, 16, 17, 18 },
{ 19, 20, 21, 22, 23, 24 },
{ 25, 26, 27, 28, 29, 30 } };
Mat matr(Size(6, 5), CV_8UC1, matrix);
Mat mb(5, 1, CV_8UC1, Scalar(0));
Mat mc(1, 6, CV_8UC1, Scalar(0));
reduce(matr, mb, 1, CV_REDUCE_SUM);
cout << "列向量" << endl;
cout << mb << endl;
参考链接:
http://answers.opencv.org/question/3698/cvreduce-gives-unsupported-format-exception/