# -*- coding: utf-8 -*-
#
zhangtao 2016/06/14
#
QQ 406878851

from PIL import *
import  Image
import numpy as np
import os

########################################################################################
#
#######################################################################################
class PixHelper(object):
    def __init__(self ,(r ,g ,b)):
        self. r =r
        self. g =g
        self. b =b
    def grayVal(self):
        return (self.r * 30 +self.g * 59 + self.b * 11) / 100

    def validPix(self):
        if self.isBackgroundPix():
            if self.grayVal() != 255:
                pass
                # print self.grayVal()
            return 255
        return 0

    def isBackgroundPix(self):
        background = PixHelper((150, 150, 150))
        background_grayVal = background.grayVal()
        return self.grayVal() > background_grayVal

    def isNeetPix(self):
        return False == self.isBackgroundPix()

########################################################################################
#
#######################################################################################
class ImageHelper(object):
    model_file="svm.model"
    def __init__(self, image):
        self.image = image
        self.width = image.size[0]
        self.height = image.size[1]
        self.subWidth=16
        self.subHeight=self.height

    #二值图
    def convertGrayImage(self):
        for x in xrange(self.width):
            for y in xrange(self.height):
                pix = self.image.getpixel((x, y))
                pixhelper = PixHelper(pix)
                pix2 = pixhelper.validPix()
                self.image.putpixel((x, y), (pix2, pix2, pix2))

    def fixCropSubImages(self):
        boxList = []
        box0 = (7, 0, 20, self.height)
        box1 = (20, 0, 34, self.height)
        box2 = (34, 0, 46, self.height)
        box3 = (46, 0, 59, self.height)
        box4 = (59, 0, 72, self.height)
        box5 = (72, 0, 88, self.height)
        boxList.append(box0)
        boxList.append(box1)
        boxList.append(box2)
        boxList.append(box3)
        boxList.append(box4)
        boxList.append(box5)
        subList = []
        for box in boxList:
            sub = self.image.crop(box)
            subList.append(sub)
        return subList

    def getRect(self,block):
        minx = self.width
        maxx = 0
        miny = self.height
        maxy = 0
        for p in block:
            # print p
            minx = min(minx, p[0])
            maxx = max(maxx, p[0])
            miny = min(miny, p[1])
            maxy = max(maxy, p[1])
        return (minx, miny, maxx - minx + 1, maxy - miny + 1)

    def getValidPoints(self):
        points = list()
        for x in xrange(self.width):
            for y in xrange(self.height):
                p = (x, y)
                pix = self.image.getpixel(p)
                pixhelper = PixHelper(pix)
                if pixhelper.isNeetPix():
                    points.append(p)
                    pass
        return points

    def getDataListWithOffset(self):
        points = self.getValidPoints()
        (left, top, width, height) = self.getRect(points)
        dataList = list()

        # if 1 == 0:
        #      data = self.getData()
        #      dataList.append(data)
        #      return dataList

        xBegin = 0 - left
        xEnd = self.subWidth - (left + width)
        yBegin = 0 - top
        yEnd = self.subHeight - (top + height)

        h_i = 0
        w_i = 0
        # print "######################"
        for h_i in xrange(yBegin, yEnd, 1):
            for w_i in xrange(xBegin, xEnd, 1):
                data = [0] * (self.subWidth * self.subHeight)
                for p in points:
                    (x, y) = p
                    (x2, y2) = (x + w_i, y + h_i)
                    if x2 >= self.subWidth  or y2 >= self.subHeight:
                        continue
                    idx = x2 + y2 * self.subWidth
                    data[idx] = 1
                dataList.append(data)

        return dataList


    def getData(self):
        points = self.getValidPoints()
        (left, top, width, height) = self.getRect(points)
        data = [0] * (self.subWidth * self.subHeight)
        for p in points:
            (x, y) = p
            idx = x + y * self.subWidth
            data[idx] = 1
        return data

----
# -*- coding: utf-8 -*-
#
zhangtao 2016/06/14
#
QQ 406878851
import os
import numpy as np
import mlpy
import sys
import time
from PIL import Image
from ImageHelper import *
from common import *

def checkSampleSucc(train_label, test_result):
    if len(train_label) != len(test_result):
        print "checkSampleSucc shape no match"
        return

    total = len(train_label)
    succ = 0
    for i in xrange(total):
        item1 = test_result[i]
        item2 = train_label[i]
        if int(item1) == int(item2):
            succ += 1
    succRate = float(succ) / float(total)
    print "checkSampleSucc : ", (succ, total), succRate



def getDataListFromFile(srcfilepath):
    im = Image.open(srcfilepath).convert('RGB')
    helper = ImageHelper(im)
    return helper.getDataListWithOffset()




def loadSampleFromDir(label, srcdir, x, y):
    print "load ..", srcdir
    srcfiles = os.listdir(srcdir)
    tm = int(time.time())
    k = 0
    for srcfilename in srcfiles:
        srcfilepath = os.path.join(srcdir, srcfilename)
        if srcfilename[0] == 'a':
            pass
            # continue
        # print srcfilename
        dataList = getDataListFromFile(srcfilepath)
        idx = 0
        for data in dataList:
            x.append(data)
            y.append(label)
            # createImageFromData(srcdir,data,idx)
            idx += 1
        newfilename = "{0}\\{1}.png".format(srcdir, k + tm)
        os.rename(srcfilepath,newfilename)
        k += 1



def loadSampleFiles():
    x = []
    y = []

    label_count = 0
    for c in xrange(ord('a'), ord('z') + 1, 1):
        if c == ord('i'):
            pass
            #continue
        srcdir = r'sample\{0}'.format(chr(c))
        #mkdir(srcdir)
        loadSampleFromDir(c, srcdir, x, y)
        label_count += 1

    for i  in xrange(1,10,1):
        srcdir=r'sample\{0}'.format(  i )
        #mkdir(srcdir)
        loadSampleFromDir(i,srcdir,x,y)
        label_count += 1
    print "label_count:",label_count

    return (x, y)


def train():
    (x, y) = loadSampleFiles()
    train_data = np.array(x, dtype='float32')
    train_label = np.array(y, dtype='int32')
    svm = mlpy.LibSvm(svm_type='c_svc', kernel_type='poly', gamma=10, probability=True)
    print "svm learn ."
    print "len(x):",len(x)
    svm.learn(train_data, train_label)
    print "svm learn done!"
    result = svm.pred(train_data)
    print result
    checkSampleSucc(y, result)
    svm.save_model(ImageHelper.model_file)
    # print result


def main():
    begin = time.time()
    train()
    #test()
    end = time.time()
    t = end - begin
    print "done:", t, t / (60)
    # test2()


if __name__ == "__main__":
    print  __file__
    main()

----
# -*- coding: utf-8 -*-
#
zhangtao 2016/06/14
#
QQ 406878851

import os
import numpy as np
import mlpy
import sys
import time
from PIL import Image
from ImageHelper import *
from common import *

testDir="test"

def processOne(i):
    dataList=[]
    fn=r'img/{0}.jpg'.format(i)
    fn2=r'img2/{0}.bmp'.format(i)
    im = Image.open(fn)
    helper = ImageHelper(im)
    helper.convertGrayImage()
    im.save(fn2)

    subList=helper.fixCropSubImages()
    count = len(subList)
    for j in xrange(count):
        fn3=r'img3/{0}_{1}.bmp'.format(i,j)
        sub = subList[j]
        sub.save(fn3)
        subHelper=ImageHelper(sub)
        data=subHelper.getData()
        dataList.append(data)
    return dataList


def savePredictResult(result_list):
    global testDir
    print "savePredictResult"
    count=len(result_list)
    if count > 0:
        with open("data.txt",'w') as file:
            for i in xrange(0,count,1):
                item=result_list[i]
                file.write(str(i)+":")
                file.write(item)
                file.write("\n")
                #print i, item
    lines1=[]
    lines2=[]
    with open("data.txt",'r') as f:
            lines1=f.readlines()
    with open(r"{0}/data.txt".format(testDir),'r') as f:
            lines2=f.readlines()
    count1=len(lines1)
    count2=len(lines2)
    if count1 != count2 :
        print "no match :",count1,count2
        return
    succ=0
    for i in xrange(count1):
        line1=lines1[i].strip()
        line2=lines2[i].strip()
        if line1 != line2:
             print "!=",line1,line2
        else:
             succ += 1
    rate= float(succ)/float(count1)
    print "result:",(succ,count1),rate

def main():
    print "-----------test---------------------"
    if False == os.path.exists(ImageHelper.model_file):
        print "s.path.exists ,faild ", ImageHelper.model_file
        return
    svm = mlpy.LibSvm.load_model(ImageHelper.model_file)
    #print 'nclasses:', svm.nclasses()
    #print 'labels:', svm.labels()
    test_list=[]
    for i in xrange(100):
        dataList=processOne(i)
        labels=[]
        for data in dataList:
            input_data = np.array(data, dtype='float32')
            result_label = int(svm.pred(input_data))
            labels.append(result_label)
        result_string=parseLabels(labels)
        print "{0}:{1}".format(i,result_string)
        test_list.append(result_string)
    savePredictResult(test_list)


if __name__ == "__main__":
    print  __file__
    main()
---
---