一个零行和1000列的矩阵?

时间:2012-12-01 22:34:17

标签: c++ opencv

我正在查看输入/输出矩阵为1D向量的CvNormalBayesClassifier::train示例。

我正在研究的例子是通过使用这一行创建一个包含0行和1000列的cv :: Mat矩阵来实现这一目的:

Mat trainingData(0, 1000, CV_32FC1);

在opencv文档中读取基本数据类型这是我在Mat中找到的:

  

创建Mat对象有许多不同的方法。这是一些   受欢迎的:

using create(nrows, ncols, type) method or

    the similar constructor

Mat(nrows, ncols, type[, fill_value]) constructor.

以任何方式,第一个参数是行。我看待它的方式是,即使我们创建一个1000列矩阵,它至少会有一行。怎么会有0行?

很抱歉,如果这是一个非常基本的问题。

更新:根据要求,这是完整的代码。

    #include <vector>
#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace boost::filesystem;
using namespace cv;

//location of the training data
#define TRAINING_DATA_DIR "data/train/"
//location of the evaluation data
#define EVAL_DATA_DIR "data/eval/"

//See article on BoW model for details
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("FlannBased");
Ptr<DescriptorExtractor> extractor = DescriptorExtractor::create("SURF");
Ptr<FeatureDetector> detector = FeatureDetector::create("SURF");

//See article on BoW model for details
int dictionarySize = 1000;
TermCriteria tc(CV_TERMCRIT_ITER, 10, 0.001);
int retries = 1;
int flags = KMEANS_PP_CENTERS;

//See article on BoW model for details
BOWKMeansTrainer bowTrainer(dictionarySize, tc, retries, flags);
//See article on BoW model for details
BOWImgDescriptorExtractor bowDE(extractor, matcher);

/**
 * \brief Recursively traverses a folder hierarchy. Extracts features from the training images and adds them to the bowTrainer.
 */
void extractTrainingVocabulary(const path& basepath) {
    for (directory_iterator iter = directory_iterator(basepath); iter
            != directory_iterator(); iter++) {
        directory_entry entry = *iter;

    if (is_directory(entry.path())) {

        cout << "Processing directory " << entry.path().string() << endl;
        extractTrainingVocabulary(entry.path());

    } else {

        path entryPath = entry.path();
        if (entryPath.extension() == ".jpg") {

            cout << "Processing file " << entryPath.string() << endl;
            Mat img = imread(entryPath.string());
            if (!img.empty()) {
                vector<KeyPoint> keypoints;
                detector->detect(img, keypoints);
                if (keypoints.empty()) {
                    cerr << "Warning: Could not find key points in image: "
                            << entryPath.string() << endl;
                } else {
                    Mat features;
                    extractor->compute(img, keypoints, features);
                    bowTrainer.add(features);
                }
            } else {
                cerr << "Warning: Could not read image: "
                        << entryPath.string() << endl;
            }

        }
    }
}
}

/**
 * \brief Recursively traverses a folder hierarchy. Creates a BoW descriptor for each image encountered.
 */
void extractBOWDescriptor(const path& basepath, Mat& descriptors, Mat& labels) {
    for (directory_iterator iter = directory_iterator(basepath); iter
            != directory_iterator(); iter++) {
        directory_entry entry = *iter;
        if (is_directory(entry.path())) {
            cout << "Processing directory " << entry.path().string() << endl;
            extractBOWDescriptor(entry.path(), descriptors, labels);
        } else {
            path entryPath = entry.path();
            if (entryPath.extension() == ".jpg") {
                cout << "Processing file " << entryPath.string() << endl;
                Mat img = imread(entryPath.string());
                if (!img.empty()) {
                    vector<KeyPoint> keypoints;
                    detector->detect(img, keypoints);
                    if (keypoints.empty()) {
                        cerr << "Warning: Could not find key points in image: "
                                << entryPath.string() << endl;
                    } else {
                        Mat bowDescriptor;
                        bowDE.compute(img, keypoints, bowDescriptor);
                        descriptors.push_back(bowDescriptor);
                        float label=atof(entryPath.filename().c_str());
                        labels.push_back(label);
                    }
                } else {
                    cerr << "Warning: Could not read image: "
                            << entryPath.string() << endl;
                }
            }
        }
    }
}

int main(int argc, char ** argv) {

cout<<"Creating dictionary..."<<endl;
extractTrainingVocabulary(path(TRAINING_DATA_DIR));
vector<Mat> descriptors = bowTrainer.getDescriptors(); //descriptors from training images
int count=0;
for(vector<Mat>::iterator iter=descriptors.begin();iter!=descriptors.end();iter++)
{
    count+=iter->rows;
}
cout<<"Clustering "<<count<<" features"<<endl;
Mat dictionary = bowTrainer.cluster();
bowDE.setVocabulary(dictionary);
cout<<"Processing training data..."<<endl;
Mat trainingData(0, dictionarySize, CV_32FC1);
Mat labels(0, 1, CV_32FC1);
extractBOWDescriptor(path(TRAINING_DATA_DIR), trainingData, labels);

NormalBayesClassifier classifier;
cout<<"Training classifier..."<<endl;

classifier.train(trainingData, labels);

cout<<"Processing evaluation data..."<<endl;
Mat evalData(0, dictionarySize, CV_32FC1);
Mat groundTruth(0, 1, CV_32FC1);
extractBOWDescriptor(path(EVAL_DATA_DIR), evalData, groundTruth);

cout<<"Evaluating classifier..."<<endl;
Mat results;
classifier.predict(evalData, &results);

double errorRate = (double) countNonZero(groundTruth - results) / evalData.rows;
        ;
cout << "Error rate: " << errorRate << endl;

}

1 个答案:

答案 0 :(得分:2)

现在你发布了代码是有道理的。该0行向量初始化为0行,但是以递增方式创建。

0行矩阵传递给extractBOWDescriptor()cv::Mat.push_back()本身计算几个描述符,并使用{{1}}向矩阵添加行。

它从0行开始,因为在开始时我们没有填充矩阵的描述符。