0

I try to read images from a file folder into a vector. However, it seems like my image Mat fail to push_back in to the vector.

The result of cout << "img vec:" << imgs[0].rows << " " << imgs[0].cols << endl; is img vec:0 0.

I've tried both imgs.push_back(img.clone()); and imgs.push_back(img);.

Here is my code :

#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;
    }

 }
user4029119
  • 145
  • 1
  • 4
  • 10

1 Answers1

0

I'm so sorry. I now know where the problem came from!!!

I thought the Mat in vector is empty because I printed out the rows and cols of imgs[0]. But I forget to ignore the first two files while reading the file directory. The first two files aren't images but ./ and ../. So just skip these two files would fix my problem.

user4029119
  • 145
  • 1
  • 4
  • 10