您的位置:首页 > 编程语言 > Python开发

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

2017-01-08 19:46 495 查看
SVM手写数字的识别---python

1、SVM手写数字识别

识别步骤:

(1)样本图像的准备。

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

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

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

识别代码:

#!/usr/bin/env python
import numpy as np
import mlpy
import cv2
print '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)

样本:





结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: