KNN识别LED数码管
利用KNN识别数码管
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <opencv2/ml.hpp>
using namespace cv;
using namespace std;
int main()
{
double t;
t=(double)cvGetTickCount();
const int k = 5;
cv::Ptr<cv::ml::KNearest> knn = ml::KNearest::create();
knn->setDefaultK(k);
knn->setIsClassifier(true); //分类问题
knn->setAlgorithmType(ml::KNearest::BRUTE_FORCE); //设置/获取KNN算法类型,目前支持两种:brute_force和KDTree;
Mat data,label;
string readName = "/home/tianjiazhao/图片/LED_Number/";
for(int i = 1; i < 10; i++)
{
string readName_ = readName + to_string(i);
for(int j = 1; j <51; j++)
{
Mat gray;
gray = imread(readName_ +"/"+ to_string(j) + ".jpg",0);
threshold(gray, gray, 200, 255, CV_THRESH_BINARY);
// imshow("",gray);
// waitKey(0);
Mat tmp;
resize(gray,tmp,Size(8,8));
imshow("",tmp);
data.push_back(tmp.reshape(0,1));
label.push_back(i);
}
}
data.convertTo(data,CV_32F); //char转化为cv_32F
knn->train(data,ml::ROW_SAMPLE,label);
knn->save("LED2.xml");
//predict
float train_hr = 0;
// Mat predoct_img =imread("/home/tianjiazhao/opencv/RuneDetector/"
// "build-RunDetector-Desktop_Qt_5_9_0_GCC_64bit-Debug/160.jpg",0);
// resize(predoct_img,predoct_img,Size(10,10));
// imshow("preditc",predoct_img);
// Mat sample;
// sample.push_back(predoct_img.reshape(0,1));
// cout<<sample<<endl;
// sample.convertTo(sample,CV_32F);
// float r = knn->predict(sample);
// cout<<"r"<<r<<endl;
for(int i = 0; i < data.rows; i++)
{
Mat sample = data.row(i);
// cout<<sample<<endl;
float r = knn->predict(sample);
r = std::abs(r - label.at<int>(i))<= FLT_EPSILON ? 1.f : 0.f;
// cout<<"r"<<r<<endl;
train_hr += r;
}
train_hr /= data.rows;
cout<<train_hr<<endl;
// waitKey(0);
t=(double)cvGetTickCount()-t;
printf("used time is %gms\n",(t/(cvGetTickFrequency()*1000)));
}
csdn源码下载:https://download.csdn.net/download/tianjiazhao/10500378
数据集下载:https://download.csdn.net/download/tianjiazhao/10500429