我目前在c++项目中需要一个包含opencv:Mat矩阵的2D向量。我找到了一个类似的示例,可以创建一个deque的2D向量,这个示例运作得非常好:
vector < vector < deque<int> > > deques_vect2D;
deques_vect2D.resize(vect_col, vector <deque<int> > (vect_row, deque<int> (deque_init_size, deque_init_value)));
然而,将其用于矩阵的二维向量并不会创建独立的矩阵,更改一个矩阵会导致更改二维向量中的每个元素。看起来只有一个矩阵存在。
// init 2D vector
vector < vector < Mat > > mat_vect2D;
mat_vect2D.resize(vect_col, vector < Mat > (vect_row, Mat(mat_row, mat_col, CV_32S, Scalar::all(0))));
// change only the first Matrix
mat_vect2D[0][0].at<int>(0, 0) = 1;
mat_vect2D[0][0].at<int>(0, 1) = 2;
for (int r = 0; r < num_of_row; r++)
for (int c = 0; c < num_of_col; c++) {
cout << mat_vect2D[c][r] << endl;
}
// results in... (note how every matrix has changed)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
(...)
是的,我需要将矩阵作为二维向量中的元素,因为这些矩阵将作为另一个算法的输入(使用其他数据类型将意味着需要进行大量转换)。因此,我更喜欢使用矩阵作为元素的解决方案,但向量可以被任何其他二维结构替换。