SVM手写数字的识别---python

来源:互联网 发布:sql语句update用法 编辑:程序博客网 时间:2024/03/28 23:52

SVM手写数字的识别---python


1、SVM手写数字识别

识别步骤:

(1)样本图像的准备。

(2)图像尺寸标准化:将图像大小都标准化为8*8大小。

(3)读取未知样本图像,提取图像特征,生成图像特征组。

(4)将未知测试样本图像特征组送入SVM进行测试,将测试的结果输出。

识别代码:

#!/usr/bin/env pythonimport numpy as npimport mlpyimport cv2print 'loading  ...'
def getnumc(fn):    '''返回数字特征'''    fnimg = cv2.imread(fn)#读取图像    img=cv2.resize(fnimg,(8,8))#将图像大小调整为8*8    alltz=[]    for now_h in xrange(0,8):        xtz=[]                for now_w in xrange(0,8):            b = img[now_h,now_w,0]            g = img[now_h,now_w,1]            r = img[now_h,now_w,2]            btz=255-b            gtz=255-g            rtz=255-r            if btz>0 or gtz>0 or rtz>0:                nowtz=1            else:                nowtz=0            xtz.append(nowtz)          alltz+=xtz    return alltz    #读取样本数字x=[]y=[]for numi in xrange(1,10):    for numij in xrange(1,5):        fn='nums/'+str(numi)+'-'+str(numij)+'.png'        x.append(getnumc(fn))        y.append(numi)    x=np.array(x)y=np.array(y)svm = mlpy.LibSvm(svm_type='c_svc', kernel_type='poly',gamma=10)svm.learn(x, y)print u"训练样本测试:"print svm.pred(x)print u"未知图像测试:"for iii in xrange (1,10):    testfn= 'nums/test/'+str(iii)+'-test.png'    testx=[]    testx.append(getnumc(testfn))    print         print testfn+":",    print svm.pred(testx)

样本:



结果


0 0
原创粉丝点击