首頁 > 後端開發 > Python教學 > 如何使用 KNearest 和 SVM 演算法在 OpenCV-Python 中實現基本的數位識別 OCR 系統?

如何使用 KNearest 和 SVM 演算法在 OpenCV-Python 中實現基本的數位識別 OCR 系統?

Linda Hamilton
發布: 2024-11-08 16:21:02
原創
1004 人瀏覽過

How can I implement a basic digit recognition OCR system in OpenCV-Python using KNearest and SVM algorithms?

OpenCV-Python 中的簡單數字辨識OCR

介紹

旨在指導您可以透過實作基本的數位辨識OCR(光學字元辨識)系統使用OpenCV-Python。我們將探索兩種流行的機器學習演算法:KNearest 和 SVM。

問題 1:Letter_recognition.data 檔案

Letter_recognition.data 是 OpenCV-Python 中包含的資料集樣本。它包含手寫字母的集合以及每個字母的 16 個特徵值。該文件用作各種字符識別任務的訓練資料。

建立您自己的Letter_recognition.data:

您可以按照以下步驟建立自己的letter_recognition.data 檔案:
  1. 你的字母資料集,每個字母表示為10x10 像素影像。
  2. 從每張影像中擷取像素值,形成 100 個值的特徵向量。
  3. 手動為每個字母分配標籤(0-25,對應於 A-Z)。
  4. 將特徵向量和標籤保存在文字檔案中,每行的格式為:

問題2:KNearest

results.ravel() 將多維數組轉換為已識別數字數組到平面一維陣列。這樣可以更輕鬆地解釋和顯示結果。

問題3:簡單的數位辨識工具

要使用letter_recognition.data 建立簡單的數位辨識工具,請依照下列步驟操作步驟:

資料準備:

    載入自訂letter_recognition.data 檔案或使用OpenCV 中的範例。

訓練:

    建立 KNearest 或 SVM 分類器實例。
  • 使用 letter_recognition.data 中的樣本和反應訓練分類器。

測試:

    載入影像包含要辨識的數字。
  • 預處理影像以隔離個體數字。
  • 將每個數字轉換為特徵向量(100 個像素值)。
  • 使用經過訓練的分類器找到每個特徵向量的最接近匹配並顯示相應的數字。

範例程式碼:

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 分類器將其替換為 SVM。

以上是如何使用 KNearest 和 SVM 演算法在 OpenCV-Python 中實現基本的數位識別 OCR 系統?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板