Opencv Mat向量分配到矩阵的一行,最快的方法吗? [英] Opencv Mat vector assignment to a row of a matrix, fastest way?
问题描述
在循环中将向量分配给矩阵行的最快方法是什么?我想用向量在其行中填充数据矩阵.这些向量是循环计算的.该循环一直持续到数据矩阵的所有条目都被这些向量填充为止.
What is the fastest way of assigning a vector to a matrix row in a loop? I want to fill a data matrix along its rows with vectors. These vectors are computed in a loop. This loop last until all the entries of data matrix is filled those vectors.
当前,我正在使用cv::Mat::at<>()
方法访问矩阵的元素并将其填充矢量,但是,此过程似乎很慢.我已经尝试过使用cv::Mat::X.row(index) = data_vector
的另一种方法,它可以快速运行,但是用一些我不理解的垃圾值填充我的矩阵X
,为什么.
Currently I am using cv::Mat::at<>()
method for accessing the elements of the matrix and fill them with the vector, however, it seems this process is quite slow. I have tried another way by using cv::Mat::X.row(index) = data_vector
, it works fast but fill my matrix X
with some garbage values which I can not understand, why.
我了解到存在使用指针的另一种方法(最快的方法),但是我无法理解.有人可以解释如何使用它们或其他不同的方法吗?
I read that there exists another way of using pointers (fastest way), however, I can not able to understand. Can somebody explain how to use them or other different methods?
这是我的代码的一部分:
Here is a part of my code:
#define OFFSET 2
cv::Mat im = cv::imread("001.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat X = cv::Mat((im.rows - 2*OFFSET)*(im.cols - 2*OFFSET), 25, CV_64FC1); // Holds the training data. Data contains image patches
cv::Mat patch = cv::Mat(5, 5, im.type()); // Holds a cropped image patch
typedef cv::Vec<float, 25> Vec25f;
int ind = 0;
for (int row = 0; row < (im.rows - 2*OFFSET); row++){
for (int col = 0; col < (im.cols - 2*OFFSET); col++){
cv::Mat temp_patch = im(cv::Rect(col, row, 5, 5)); // crop an image patch (5x5) at each pixel
patch = temp_patch.clone(); // Needs to do this because temp_patch is not continuous in memory
patch.convertTo(patch, CV_64FC1);
Vec25f data_vector = patch.reshape(0, 1); // make it row vector (1X25).
for (int i = 0; i < 25; i++)
{
X.at<float>(ind, i) = data_vector[i]; // Currently I am using this way (quite slow).
}
//X_train.row(ind) = patch.reshape(0, 1); // Tried this but it assigns some garbage values to the data matrix!
ind += 1;
}
}
推荐答案
要使用常规的opencv方法,您可以这样做:-
To do it the regular opencv way you could do :-
ImageMat.row(RowIndex) = RowMat.clone();
或
RowMat.copyTo(ImageMat.row(RowIndex));
尚未测试正确性或速度.
Haven't tested for correctness or speed.
这篇关于Opencv Mat向量分配到矩阵的一行,最快的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!