Question

I'm beginner in opencv. I have not gotten main concepts of opencv in details.

So maybe my code it's too dumb;

Out of my curiosity I want to try machine learning functions like a KNN, ANN. I have the set of images with size 28*28 pixels. I want to do train cassifier for digit recognition. So first I need to assemble train set and train classes;

    Mat train_data = Mat(rows, cols, CV_32FC1);
    Mat train_classes = Mat(rows, 1, CV_32SC1);
    Mat img = imread(image);
    Mat float_data(1, cols, CV_32FC1);
    img.convertTo(float_data, CV_32FC1);

How to fill train_data with float_data ? I thought It was smth like this:

for (int i = 0; i < train_data.rows; ++i) 
{
    ... // image is a string which contains next image path
    image = imread(image);
    img.convertTo(float_data, CV_32FC1);
    for( int x = 0; x < train_data.cols; x++ ){
      train_data.at<float> (i, x) = float_data.at<float>( x);; 
    }
 }

 KNearest knn;
 knn.train(train_data, train_classes);

but it's of course doesn't work . . . Please, tell me how to do it right. Or at least suggest the books for dummies :)

Was it helpful?

Solution

Mat train_data; // initially empty
Mat train_labels; // empty, too.

// for each img in the train set : 
    Mat img = imread("image_path");
    Mat float_data;
   img.convertTo(float_data, CV_32FC1);             // to float
   train_data.push_back( float_data.reshape(1,1) ); // add 1 row (flattened image)
   train_labels.push_back( label_for_image );       // add 1 item

KNearest knn;
knn.train(train_data, train_labels);

it's all the same for other ml algos !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top