您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關如何使用OpenCV實現標準數字識別功能的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
import sys import numpy as np import cv2 im = cv2.imread('t.png') im3 = im.copy() gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #先轉換為灰度圖才能夠使用圖像閾值化 thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) #自適應閾值化 ################## Now finding Contours ################### # image,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) #邊緣查找,找到數字框,但存在誤判 samples = np.empty((0,900)) #將每一個識別到的數字所有像素點作為特征,儲存到一個30*30的矩陣內 responses = [] #label keys = [i for i in range(48,58)] #48-58為ASCII碼 count =0 for cnt in contours: if cv2.contourArea(cnt)>80: #使用邊緣面積過濾較小邊緣框 [x,y,w,h] = cv2.boundingRect(cnt) if h>25 and h < 30: #使用高過濾小框和大框 count+=1 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,(30,30)) cv2.imshow('norm',im) key = cv2.waitKey(0) if key == 27: # (escape to quit) sys.exit() elif key in keys: responses.append(int(chr(key))) sample = roismall.reshape((1,900)) samples = np.append(samples,sample,0) if count == 100: #過濾一下過多邊緣框,后期可能會嘗試極大抑制 break responses = np.array(responses,np.float32) responses = responses.reshape((responses.size,1)) print ("training complete") np.savetxt('generalsamples.data',samples) np.savetxt('generalresponses.data',responses) # cv2.waitKey() cv2.destroyAllWindows()
訓練數據為:
測試數據為:
使用openCV自帶的ML包,KNearest算法
import sys import cv2 import numpy as np ####### training part ############### samples = np.loadtxt('generalsamples.data',np.float32) responses = np.loadtxt('generalresponses.data',np.float32) responses = responses.reshape((responses.size,1)) model = cv2.ml.KNearest_create() model.train(samples,cv2.ml.ROW_SAMPLE,responses) def getNum(path): im = cv2.imread(path) out = np.zeros(im.shape,np.uint8) gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #預處理一下 for i in range(gray.__len__()): for j in range(gray[0].__len__()): if gray[i][j] == 0: gray[i][j] == 255 else: gray[i][j] == 0 thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2) image,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) count = 0 numbers = [] for cnt in contours: if cv2.contourArea(cnt)>80: [x,y,w,h] = cv2.boundingRect(cnt) if h>25: cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) roi = thresh[y:y+h,x:x+w] roismall = cv2.resize(roi,(30,30)) roismall = roismall.reshape((1,900)) roismall = np.float32(roismall) retval, results, neigh_resp, dists = model.findNearest(roismall, k = 1) string = str(int((results[0][0]))) numbers.append(int((results[0][0]))) cv2.putText(out,string,(x,y+h),0,1,(0,255,0)) count += 1 if count == 10: break return numbers numbers = getNum('1.png')
感謝各位的閱讀!關于“如何使用OpenCV實現標準數字識別功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。