簡體   English   中英

如何在 Python 中使用 OCR 提取數字或數字

[英]How to extract numbers or digits using OCR in Python

我嘗試使用 OCR 提取數字。

開發環境由 pycharm(Python 版本 3)運行。

我的問題是如何使用 OCR 提取數字。

圖像如下所示:

輸入圖像

在上圖中,我想獲得以下數字文本:

1 2   3
4 5 6 7
8 9   0

我怎樣才能得到我想要的結果?

有一系列庫可以實現這一點,這里有一個示例: https: //pypi.org/project/pytesseract/https://github.com/madmaze/pytesseract

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract

# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'
# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'

# Simple image to string
print(pytesseract.image_to_string(Image.open('test.png')))

您可以通過 Otsu 的閾值獲得二值圖像然后提取每個數字。 閾值化后我們得到這個

在此處輸入圖像描述

現在我們遍歷輪廓並提取/保存每個 ROI

在此處輸入圖像描述

現在您可以應用所需的 OCR 工具來讀取每個 ROI 上的文本

import cv2

image = cv2.imread('1.jpg', 0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c, num in zip(cnts, range(len(cnts))):
    x,y,w,h = cv2.boundingRect(c)
    ROI = 255 - thresh[y:y+h, x:x+w]
    cv2.imwrite('ROI_{}.png'.format(num), ROI)

cv2.imshow('thresh', 255 - thresh)
cv2.waitKey()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM