基于opencv的手写数字识别(MFC,HOG,SVM)

因为本程序是提取HOG特征,使用SVM进行分类的,所以大概了解下HOG的一些知识,其中我觉得怎么计算图像HOG特征的维度会对程序了解有帮助


关于HOG,我们可以参考:


http://gz-ricky.blogbus.com/logs/85326280.html


http://blog.csdn.net/raodotcong/article/details/6239431


关于手写的数字0-9的数据库下载地址和如何生成此数据库HOG特征的xml文件可以参考文章开头的参考博客。


本人提供一个已经训练好的关于此库我生成的xml文件,下载地址:


http://pan.baidu.com/s/1qXSYp



训练模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>
using  namespace  std;
using  namespace  cv;
int  main()
{
     vector<string> img_path; //输入文件名变量
     vector< int > img_catg;
     int  nLine = 0;
     string buf;
     ifstream svm_data(  "D:/project/HOG/t10k-images-bmp/t10k-images/result.txt"  ); //训练样本图片的路径都写在这个txt文件中,使用bat批处理文件可以得到这个txt文件
     unsigned  long  n;
     while ( svm_data ) //将训练样本文件依次读取进来
     {
         if ( getline( svm_data, buf ) )
         {
             nLine ++;
             if ( nLine % 2 == 0 ) //注:奇数行是图片全路径,偶数行是标签
             {
                 img_catg.push_back(  atoi ( buf.c_str() ) ); //atoi将字符串转换成整型,标志(0,1,2,...,9),注意这里至少要有两个类别,否则会出错
             }
             else
             {
                 img_path.push_back( buf ); //图像路径
             }
         }
     }
     svm_data.close(); //关闭文件
     CvMat *data_mat, *res_mat;
     int  nImgNum = nLine / 2;  //nImgNum是样本数量,只有文本行数的一半,另一半是标签
     data_mat = cvCreateMat( nImgNum, 324, CV_32FC1 );   //第二个参数,即矩阵的列是由下面的descriptors的大小决定的,可以由descriptors.size()得到,且对于不同大小的输入训练图片,这个值是不同的
     cvSetZero( data_mat );
     //类型矩阵,存储每个样本的类型标志
     res_mat = cvCreateMat( nImgNum, 1, CV_32FC1 );
     cvSetZero( res_mat );
     IplImage* src;
     IplImage* trainImg=cvCreateImage(cvSize(28,28),8,3); //需要分析的图片,这里默认设定图片是28*28大小,所以上面定义了324,如果要更改图片大小,可以先用debug查看一下descriptors是多少,然后设定好再运行
     //处理HOG特征
     for ( string::size_type i = 0; i != img_path.size(); i++ )
     {
         src=cvLoadImage(img_path[i].c_str(),1);
         if ( src == NULL )
         {
             cout<< " can not load the image: " <<img_path[i].c_str()<<endl;
             continue ;
         }
         cout<< "deal with\t" <<img_path[i].c_str()<<endl;
         cvResize(src,trainImg);
         HOGDescriptor *hog= new  HOGDescriptor(cvSize(28,28),cvSize(14,14),cvSize(7,7),cvSize(7,7),9);
         vector< float >descriptors; //存放结果
         hog->compute(trainImg, descriptors,Size(1,1), Size(0,0));  //Hog特征计算
         cout<< "HOG dims: " <<descriptors.size()<<endl;
         n=0;
         for (vector< float >::iterator iter=descriptors.begin();iter!=descriptors.end();iter++)
         {
             cvmSet(data_mat,i,n,*iter); //存储HOG特征
             n++;
         }
         cvmSet( res_mat, i, 0, img_catg[i] );
         cout<< "Done !!!: " <<img_path[i].c_str()<< " " <<img_catg[i]<<endl;
     }
     CvSVM svm; //新建一个SVM
     CvSVMParams param; //这里是SVM训练相关参数
     CvTermCriteria criteria;
     criteria = cvTermCriteria( CV_TERMCRIT_EPS, 1000, FLT_EPSILON );
     param = CvSVMParams( CvSVM::C_SVC, CvSVM::RBF, 10.0, 0.09, 1.0, 10.0, 0.5, 1.0, NULL, criteria );
     svm.train( data_mat, res_mat, NULL, NULL, param ); //训练数据
     //保存训练好的分类器
     svm.save(  "HOG_SVM_DATA.xml"  );
     cout<< "HOG_SVM_DATA.xml is saved !!! \n exit program" <<endl;
     cvReleaseMat( &data_mat );
     cvReleaseMat( &res_mat );
     cvReleaseImage(&trainImg);
     return  0;
}
1
D:/project/HOG/t10k-images-bmp/t10k-images/result.txt  的生成方法<br>使用createpath.py脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import  os, sys
def  get_filepaths(directory):
     file_paths  =  []   # List which will store all of the full filepaths.
     for  root, directories, files  in  os.walk(directory):
         for  filename  in  files:
             # Join the two strings in order to form the full filepath.
             filepath  =  os.path.join(root, filename)
             file_paths.append(filepath)   # Add it to the list.
     return  file_paths   # Self-explanatory.
lists  =  get_filepaths(os.path.dirname(os.path.abspath(__file__)))
with  open ( 'result.txt' 'a' ) as f:
     for  url  in  lists:       
         if  (os.path.basename(url).startswith( '0_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '0\n' )
         if  (os.path.basename(url).startswith( '1_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '1\n' )
         if  (os.path.basename(url).startswith( '2_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '2\n' )
         if  (os.path.basename(url).startswith( '3_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '3\n' )
         if  (os.path.basename(url).startswith( '4_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '4\n' )
         if  (os.path.basename(url).startswith( '5_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '5\n' )
         if  (os.path.basename(url).startswith( '6_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '6\n' )
         if  (os.path.basename(url).startswith( '7_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '7\n' )
         if  (os.path.basename(url).startswith( '8_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '8\n' )
         if  (os.path.basename(url).startswith( '9_' )):
             f.write(url)
             f.write( '\n' )
             f.write( '9\n' )

1
生成result.txt

1
使用模型
复制代码
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
    IplImage *test;
    char result[300]; //存放预测结果

    CvSVM svm;
    svm.load("d:\\HOG_SVM_DATA.xml");//加载训练好的xml文件,这里训练的是10K个手写数字
    //检测样本
    test = cvLoadImage("d:\\test.bmp", 1); //待预测图片,用系统自带的画图工具随便手写
    if (!test)
    {
        cout<<"not exist"<<endl;
        return -1;
    }
    cout<<"load image done"<<endl;
    IplImage* trainTempImg=cvCreateImage(cvSize(28,28),8,3);
    cvZero(trainTempImg);
    cvResize(test,trainTempImg);
    HOGDescriptor *hog=new HOGDescriptor(cvSize(28,28),cvSize(14,14),cvSize(7,7),cvSize(7,7),9);
    vector<float>descriptors;//存放结果
    hog->compute(trainTempImg, descriptors,Size(1,1), Size(0,0)); //Hog特征计算
    cout<<"HOG dims: "<<descriptors.size()<<endl;  //打印Hog特征维数  ,这里是324
    CvMat* SVMtrainMat=cvCreateMat(1,descriptors.size(),CV_32FC1);
    int n=0;
    for(vector<float>::iterator iter=descriptors.begin();iter!=descriptors.end();iter++)
    {
        cvmSet(SVMtrainMat,0,n,*iter);
        n++;
    }

    int ret = svm.predict(SVMtrainMat);//检测结果
    sprintf(result, "%d\r\n",ret );
    cvNamedWindow("dst",1);
    cvShowImage("dst",test);
    cout<<"result:"<<result<<endl;
    waitKey ();
    cvReleaseImage(&test);
    cvReleaseImage(&trainTempImg);

    return 0;
}
复制代码

 

工程源码(MFC):

http://pan.baidu.com/s/1rDQbO

程序下载(裸机可运行,无需环境):

http://pan.baidu.com/s/1byQeX

QT控制台版本(包含手写数据库,训练模型,使用模型)

http://pan.baidu.com/s/1pJ45bwZ

 

 

 

作者: 小菜鸟_yang
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值