Python digit recognition - training model

Python digit recognition - training model

Introduction

Digital recognition is an important task in computational vision, and it can be used to complete the work of adding cameras to old equipment to complete data collection. This article introduces the use of opencv to realize digital recognition training.

the code

import sys
import numpy as np
import cv2

im = cv2.imread('train.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(44,58)]

for cnt in contours:
    # if cv2.contourArea(cnt)>5: #大于像素点的区域
            [x,y,w,h] = cv2.boundingRect(cnt)
        # print([x,y,w,h])#对应的区域的坐标
        # if  (h>25 and h < 29):#筛选不需要的区域
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)
            print(key)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                key = str(key)
                print(key)
                responses.append(int(key))#保存ascii码
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print ("training complete")
print(samples)
print(responses)

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Execute the code, circle the number recognized by the computer on the training picture, and then input the corresponding number to the computer for training on the keyboard, until the recognition is completed, two files will be output: generalsamples.data, generalresponses.data, and you are done here The job of training. The next article introduces the code used

insert image description here

Guess you like

Origin blog.csdn.net/sinat_35773915/article/details/132082245