Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

i'd recommend, that you get rid of your text files, and instead put your positive images into one folder, and the negatives into another.

then, use cv::glob to read in the directories, and get the data, like this:

void readData(String folderPath, Mat &data, Mat &labels, int label)
{
    vector<String> fn;
    glob(folderPath,fn,false);

    for (size_t i=0; i<fn.size(); i++)
    {
        Mat img = imread(fn[i], 1);
        if (img.empty()) 
        {
            cerr << "invalid image: " << fn[i] << endl;
            continue;
        }
        img.convertTo(img, CV_32FC1);
        data.push_back(img.reshape(1,1));
        labels.push_back(label);
    }
}

int main()
{
    Mat trainData;
    Mat trainLabels;
    readData("c:/path/to/positives/*.png", trainData, trainLabels, 1);
    readData("c:/path/to/negatives/*.png", trainData, trainLabels, 0);

    cv::Ptr<cv::ml::NormalBayesClassifier> classifier = cv::ml::NormalBayesClassifier::create();
    classifier->train(trainData, cv::ml::ROW_SAMPLE, trainLabels);
    classifier->save("bayes.xml");
    return 0;
}