OpenCV创建矩阵,每行包含多个图像

OpenCV create Matrix containing multiple images in each row

本文关键字:包含多 图像 创建 OpenCV      更新时间:2023-10-16

我需要在OpenCV中创建图像的数据矩阵。基本上矩阵的每一行都会包含同一个人的多个图像。我找到了@编写的RowMatrix教程bytefish,但是我目前不明白如何将多个图像复制到矩阵的一行中。我有一个图像路径的文本文件,当路径引用新主题时,用";"分隔,例如:

Subject1/Image1.png
Subject1/Image2.png
;
Subject2/Image1.png

我最初的想法是有一个2D矢量:

Vector<Vector<Mat>> intra;
    while(file.good()) {
    getline(file, path);
    if((path.compare(";"))!=0){
        try{
 //Add images to person-index
            intra[curRow].push_back(imread(path,0));
        } catch (Exception const & e){
            cerr<<"OpenCV exception: "<<e.what()<<std::endl;
        }
    } else{
//";" found --> increment person-index
        curRow++;
    }
}
imshow("Intra[0,0]",intra[0][0]);

但是,我收到一个错误,我认为这是由于向量大小不大(curRow+1)

OpenCV Error: Assertion failed (i < size()) in unknown function, file c:opencv
includeopencv2coreoperations.hpp, line 2357
OpenCV exception: c:opencvincludeopencv2coreoperations.hpp:2357: error: (-2
15) i < size()

在 else 中调整矢量大小并不能解决问题!任何关于解决此问题或使用不同 OpenCV 数据结构的指示将不胜感激!

我没有

使用push_back而是决定在每次添加图像时动态调整矢量的大小。这可能效率低下,但它解决了引用不正确的问题。我通过@jrok 2D 矢量元素访问问题的回答得到了这个想法。编辑的解决方案:

int curRow=0;
int numImages=0;
string line, path, temp;
while(file.good()) {
    getline(file, path);
    if((path.compare(";"))!=0){
        try{
            faces[curRow].resize(numImages+1);
            faces[curRow][numImages] = imread(path,0);
            numImages++;
        } catch (Exception const & e){
            cerr<<"OpenCV exception: "<<e.what()<<std::endl;
        }
    } else{
        numImages=0;
        curRow++;
    }
}

希望这对面临同样问题的其他人有所帮助!