创建Mat OpenCV中常见的创建Mat的方法主要有以下八种方法,演示代码如下:
Mat的常见操作
这些常见操作主要包括,ROI截取、行截取、列截取、矩阵乘法、矩阵转置、矩阵点乘求和、矩阵乘法、矩阵reshape、矩阵求逆、forEach遍历,相关的代码片段如下:// create two Mat
Mat m1 = (Mat_<float>(3, 4) << 1, 2, 3, 4, 5,6,7,8, 10,11,12,13, 25,26,27,28);
Mat m2 = (Mat_<float>(2, 3) << 1, 2, 3, 1, 2, 3);
std::cout << " m1 : \n" << m1 << std::endl;
std::cout << " m2 : \n" << m2 << std::endl;
// roi截取
Rect box(0, 0, 2, 2);
Mat roi = m1(box);
std::cout << " roi : \n" << roi << std::endl;
// 按行截取
Mat row1 = Mat(m1, Range(0, 1), Range::all());
Mat row2 = Mat(m1, Range(1, 2), Range::all());
std::cout << " row1 : \n" << row1 << std::endl;
std::cout << " row2 : \n" << row2 << std::endl;
// 按列截取
Mat col1 = Mat(m1, Range::all(), Range(0, 1));
Mat col2 = Mat(m1, Range::all(), Range(1, 2));
std::cout << " col1 : \n" << col1 << std::endl;
std::cout << " col2 : \n" << col2 << std::endl;
// 矩阵乘法
Mat m3 = m2 * m1;
std::cout << " m3 : \n" << m3 << std::endl;
// 矩阵转置
Mat m3_t = m3.t();
std::cout << " m3_t : \n" << m3_t << std::endl;
// 矩阵点乘求和
Mat m4 = (Mat_<float>(2, 3) << 4, 2, 1, 3, 6, 9);
double sum = m2.dot(m4);
std::cout << " sum(m2xm4) = " << sum << std::endl;
// 矩阵乘法
Mat m5 = m2.mul(m4);
std::cout << " m5(m2xm4) = " << m5 << std::endl;
// reshape
Mat m6 = m5.reshape(0, 3);
std::cout << " m6(m5 reshape) = " << m6 << std::endl;
// 求逆
Mat m7 = (Mat_<float>(2, 2) << 1, 2, 3, 4);
std::cout << " m7 = \n" << m7 << std::endl;
std::cout << " m7(inv) = \n" << m7.inv() << std::endl;
// i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
typedef cv::Point3_<uint8_t> Pixel;
// forEach方式的像素遍历
image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
p.x = 255 - p.x;
p.y = 255 - p.y;
p.z = 255 - p.z;
});
运行结果如下:
|