[英]OpenCV image matrix to vector to matrix
I want to do the following: 我想做以下事情:
Lets say I have 100 images. 可以说我有100张图片。 I want to convert the matrix of each image to one vector and build a new matrix (of 100 rows), where each row is the vector that we got from the images. 我想将每个图像的矩阵转换为一个向量并构建一个新的矩阵(100行),其中每一行是我们从图像中得到的向量。 What is the best way to do that? 最好的方法是什么?
Assume all of your image is of same size, 假设您的所有图像大小相同,
then using Mat::push_back() you can store each image row by row to a new Mat, but you need to reshape your source image to a single row using Mat::reshape() . 然后使用Mat :: push_back(),您可以逐行将每个图像存储到新的Mat,但是您需要使用Mat :: reshape()将源图像重塑为单个行。 Later you can access each row(will be your source image) using Mat::row but again you need to reshape to your source size. 稍后您可以使用Mat :: row访问每一行(将是您的源图像),但您需要再次重塑您的源大小。
See below example. 见下面的例子。
Load source image of same size and channel. 加载相同大小和通道的源图像。
Mat src1=imread("a.jpg",1);
Mat src2=imread("b.jpg",1);
Mat src3=imread("c.jpg",1);
Push back each source Mat to a new Mat row by row, here you need to reshape your source to a single row Mat, as each row in the result Mat should represent each source image. 将每个源Mat逐行推回到新的Mat,这里需要将源重新整形为单行Mat,因为结果Mat中的每一行应代表每个源图像。
Mat A;
A.push_back(src1.reshape(0,1)); //0 makes channel unchanged and 1 makes single row
A.push_back(src2.reshape(0,1));
A.push_back(src3.reshape(0,1));
Later access each row from A, using A.row(index).clone()
and reshape to original size, 稍后使用A.row(index).clone()
访问A中的每一行并重新A.row(index).clone()
为原始大小,
Mat B;
B = A.row(0).clone();
imshow("src1",B.reshape(0,src1.rows));
B = A.row(1).clone();
imshow("src2",B.reshape(0,src1.rows));
B = A.row(2).clone();
imshow("src3",B.reshape(0,src1.rows));
vector<Mat> images;
// fill it with data
Mat matVec(images.size(), images[0].cols*images[0].rows, images[0].type());
for(unsigned int i=0; i<images.size(); i++)
(images[i].reshape(0,1)).copyTo(matVec.row(i));
This solution is based on solution that was proposed by Haris, but it is somewhat less time consuming. 该解决方案基于Haris提出的解决方案,但耗时较少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.