OpenCV KNN绘制匹配

时间:2015-10-05 15:46:07

标签: opencv type-conversion match draw knn

我使用KNN对图像进行分类。现在我的问题是如何绘制结果。

Click here to get the documentation for KNN in OpenCV

我使用find_nearest函数,构造函数如下所示: C++: float CvKNearest::find_nearest(const Mat& samples, int k, Mat& results, Mat& neighborResponses, Mat& dists)

参数是:

samples:输入按行存储的样本。它是number\_of\_samples \times number\_of\_features size的单精度浮点矩阵。


k:使用的最近邻居数。它必须满足约束条件:k \le CvKNearest::get_max_k().

结果:具有每个输入样本的预测结果(回归或分类)的向量。它是single-precision floating-point向量,带有number_of_samples个元素。


neighbors:邻居向量本身的可选输出指针。它是一个k*samples->rows指针数组。


neighborResponses:对应邻居的可选输出值。它是number\_of\_samples \times k size的单精度浮点矩阵。


dist:从输入向量到相应邻居的可选输出距离。它是number\_of\_samples \times k size的单精度浮点矩阵。

一个可行的实现看起来像这样:

#include "ml.h"
#include "highgui.h"

int main( int argc, char** argv )
{
    const int K = 10;
    int i, j, k, accuracy;
    float response;
    int train_sample_count = 100;
    CvRNG rng_state = cvRNG(-1);
    CvMat* trainData = cvCreateMat( train_sample_count, 2, CV_32FC1 );
    CvMat* trainClasses = cvCreateMat( train_sample_count, 1, CV_32FC1 );
    IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
    float _sample[2];
    CvMat sample = cvMat( 1, 2, CV_32FC1, _sample );
    cvZero( img );

    CvMat trainData1, trainData2, trainClasses1, trainClasses2;

    // form the training samples
    cvGetRows( trainData, &trainData1, 0, train_sample_count/2 );
    cvRandArr( &rng_state, &trainData1, CV_RAND_NORMAL, cvScalar(200,200), cvScalar(50,50) );

    cvGetRows( trainData, &trainData2, train_sample_count/2, train_sample_count );
    cvRandArr( &rng_state, &trainData2, CV_RAND_NORMAL, cvScalar(300,300), cvScalar(50,50) );

    cvGetRows( trainClasses, &trainClasses1, 0, train_sample_count/2 );
    cvSet( &trainClasses1, cvScalar(1) );

    cvGetRows( trainClasses, &trainClasses2, train_sample_count/2, train_sample_count );
    cvSet( &trainClasses2, cvScalar(2) );

    // learn classifier
    CvKNearest knn( trainData, trainClasses, 0, false, K );
    CvMat* nearests = cvCreateMat( 1, K, CV_32FC1);

    for( i = 0; i < img->height; i++ )
    {
        for( j = 0; j < img->width; j++ )
        {
            sample.data.fl[0] = (float)j;
            sample.data.fl[1] = (float)i;

            // estimate the response and get the neighbors' labels
            response = knn.find_nearest(&sample,K,0,0,nearests,0);

            // compute the number of neighbors representing the majority
            for( k = 0, accuracy = 0; k < K; k++ )
            {
                if( nearests->data.fl[k] == response)
                    accuracy++;
            }
        }
    }

现在回到问题所在。我想使用DrawMatches函数。 Click here to see the description。此函数期望其输入为DMatch-Type矩阵。所以当你看到Knn.find_nearest没有给我这种类型的任何回报。你有什么建议如何转换它们吗?

提前致谢!

0 个答案:

没有答案