OpenCV-Python 中的簡單數字辨識OCR
介紹
旨在指導您可以透過實作基本的數位辨識OCR(光學字元辨識)系統使用OpenCV-Python。我們將探索兩種流行的機器學習演算法:KNearest 和 SVM。問題 1:Letter_recognition.data 檔案
Letter_recognition.data 是 OpenCV-Python 中包含的資料集樣本。它包含手寫字母的集合以及每個字母的 16 個特徵值。該文件用作各種字符識別任務的訓練資料。建立您自己的Letter_recognition.data:
您可以按照以下步驟建立自己的letter_recognition.data 檔案:問題2:KNearest
results.ravel() 將多維數組轉換為已識別數字數組到平面一維陣列。這樣可以更輕鬆地解釋和顯示結果。問題3:簡單的數位辨識工具
要使用letter_recognition.data 建立簡單的數位辨識工具,請依照下列步驟操作步驟:資料準備:
訓練:
測試:
範例程式碼:
import numpy as np import cv2 # Load data samples = np.loadtxt('my_letter_recognition.data', np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') }) responses = a[:,0] # Create classifier model = cv2.KNearest() model.train(samples, responses) # Load test image test_img = cv2.imread('test_digits.png') # Preprocess image gray = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(gray, 255, 1, 1, 11, 2) # Extract digits contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) digits = [] for cnt in contours: if cv2.contourArea(cnt) > 50: [x, y, w, h] = cv2.boundingRect(cnt) roi = thresh[y:y+h, x:x+w] roismall = cv2.resize(roi, (10, 10)) digits.append(roismall) # Recognize digits results = [] for digit in digits: roismall = roismall.reshape((1, 100)) roismall = np.float32(roismall) _, results, _, _ = model.find_nearest(roismall, k=1) results = results.ravel() results = [chr(int(res) + ord('A')) for res in results] # Display results output = cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB) for (digit, (x, y, w, h)) in zip(results, contours): cv2.rectangle(output, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(output, str(digit), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.imshow('Output', output) cv2.waitKey(0)
以上是如何使用 KNearest 和 SVM 演算法在 OpenCV-Python 中實現基本的數位識別 OCR 系統?的詳細內容。更多資訊請關注PHP中文網其他相關文章!