Opencv push_back图像Mat到vector <mat>

时间:2016-10-12 03:43:10

标签: c++ opencv mat push-back

我尝试将文件夹中的图像读入矢量。 但是,似乎我的图像Mat无法推送到向量中。

cout << "img vec:" << imgs[0].rows << " " << imgs[0].cols << endl;的结果是img vec:0 0

我已经尝试了imgs.push_back(img.clone());imgs.push_back(img);

这是我的代码:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <dirent.h>
#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

void readImageFiles(string dirName,  vector<cv::Mat> &imgs);

int _tmain(int argc, _TCHAR* argv[]){
    vector<cv::Mat> imgs;
    readImageFiles("training/", imgs);

    cout << imgs.size() << endl;
    cout << imgs[0] << endl;
    /*
    for(int i = 0; i < imgs.size(); i++){
        imshow("img", imgs[i]);
        waitKey();
    }
    */
    system("pause");
    return 0;
}


void readImageFiles(string dirName, vector<cv::Mat> &imgs){

    DIR *dir;   
    dir = opendir(dirName.c_str());
    struct dirent *ent;
    if (dir != NULL) {
        while ((ent = readdir (dir)) != NULL) {
            string imgPath(dirName + ent->d_name);
            Mat img = imread(imgPath);
            //cvtColor(img,img,CV_BGR2GRAY);
            imgs.push_back(img.clone());
            cout << "img:" << img.rows << " " << img.cols << endl;
            cout << "img vec:" << imgs[0].rows << " " << imgs[0].cols << endl;
        }
    }else{
        cout << "NULL" << endl;
    }

 }

1 个答案:

答案 0 :(得分:0)

我很抱歉。我现在知道问题来自哪里!!!

我认为向量中的Mat是空的,因为我打印出了imgs[0]的行和列。 但我忘了在读取文件目录时忽略前两个文件。 前两个文件不是./../的图片。所以跳过这两个文件就可以解决我的问题。