我想使用openCV修改多维矩阵的一部分。基本上我想实现与Matlab中写的相同:
A = zeros(5,5,25);
A(:,:,1) = some_matrix1;
A(:,:,2) = some_matrix2;
我不确定是否应该使用带有25个通道的5x5矩阵或带有单通道的5x5x25矩阵。这是我试过的:
int dim[3] = { 5,5,25 };
Mat A(3, dim, CV_32FC(1), Scalar::all(0));
A(Range::all(),Range::all(),0) = some_matrix;
但似乎我只能将Range用于两个维度。 或
Mat A(5, 5, CV_32FC(25), Scalar::all(0));
A(Range::all(),Range::all())[0] = some_matrix;
但在这种情况下,我不知道如何访问该频道。 你能帮帮我吗?
答案 0 :(得分:1)
OpenCV针对2D矩阵进行了优化。多维矩阵可以工作,但效率很低,难以访问。
此示例代码将向您展示如何从3D矩阵中写入和读取值:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
int sizes[] = { 5, 5, 25 };
Mat data(3, sizes, CV_32F);
Mat1f some_matrix(sizes[0], sizes[1]);
randu(some_matrix, 0.f, 100.f); // some random values
// Init data with each plane a constant increasing value
for (int z = 0; z < data.size[2]; ++z)
{
// Set each z-plane to some scalar value
Range ranges[] = { Range::all(), Range::all(), Range(z, z + 1) };
data(ranges) = data.size[2] - z;
}
// Set the n-th z-plane to some_matrix
int z = 0;
for (int r = 0; r < sizes[0]; ++r)
{
for (int c = 0; c < sizes[1]; ++c)
{
data.at<float>(r, c, z) = some_matrix(r, c);
}
}
// Access all slices along z dimension
for (int z = 0; z < data.size[2]; ++z)
{
Range ranges[] = { Range::all(), Range::all(), Range(z, z + 1) };
Mat slice3d(data(ranges).clone()); // with clone slice is continuous, but still 3d
Mat slice(2, &data.size[0], data.type(), slice3d.data);
}
return 0;
}
然而,将5x5x25 3D矩阵存储为std::vector<Mat>
更加容易和实用,其中vector
长度为25,每个矩阵为2D 5x5。
参见代码:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
int sizes[] = { 5, 5, 25 };
vector<Mat> data(sizes[2]);
// Init data with each plane a constant increasing value
for (int z = 0; z < sizes[2]; ++z)
{
data[z] = Mat(sizes[0], sizes[1], CV_32F, float(sizes[2] - z));
}
Mat1f some_matrix(sizes[0], sizes[1]);
randu(some_matrix, 0.f, 100.f); // some random values
// Set the n-th z-plane to some_matrix
int z = 0;
data[z] = some_matrix;
return 0;
}
答案 1 :(得分:0)
以下是从频道访问像素的代码段,您可以尝试一下。
col3