k近邻算法分类

  • m5_802608
    了解作者
  • 11.4MB
    文件大小
  • rar
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-06-15 05:35
    上传日期
vs2010+opencv2.4.9环境下,通过knn算法对0-9数字进行分类
knn_test.rar
内容介绍
#include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/ml/ml.hpp> using namespace std; using namespace cv; char ad[128]={0}; int main() { Mat traindata ,trainlabel; int k=5,testnum=0,truenum=0; //读取训练数据 4000张 for (int i = 0; i < 10; i++) { for (int j =0;j<400;j++) { sprintf_s(ad, "C:\\Users\\DXC\\Desktop\\readvideo\\number\\%d\\%d.jpg",i,j); Mat srcimage = imread(ad); srcimage = srcimage.reshape(1,1); traindata.push_back(srcimage); trainlabel.push_back(i); } } traindata.convertTo(traindata,CV_32F); CvKNearest knn( traindata, trainlabel, cv::Mat(), false, k ); cv::Mat nearests( 1, k, CV_32F); //读取测试数据 1000张 for (int i = 0; i < 10; i++) { for (int j =400;j<500;j++) { testnum++; sprintf_s(ad, "C:\\Users\\DXC\\Desktop\\readvideo\\number\\%d\\%d.jpg",i,j); Mat testdata = imread(ad); testdata = testdata.reshape(1,1); testdata.convertTo(testdata,CV_32F); int response = knn.find_nearest(testdata,k,0,0,&nearests,0); if (response==i) { truenum++; } } } cout<<"测试总数"<<testnum<<endl; cout<<"正确分类数"<<truenum<<endl; cout<<"准确率:"<<(float)truenum/testnum*100<<"%"<<endl; return 0; }
评论
    相关推荐