簡體   English   中英

使用 OCR 從圖像中讀取文本,使用 python 讀取具有兩列或三列數據的圖像

[英]Read text from image using OCR for the image which have two columns or three columns of data using python

在示例圖像中(僅作為參考,我的圖像將具有相同的模式)一個頁面具有完整的水平文本,而其他頁面具有兩個水平的文本列。

在此處輸入圖片說明

python中如何自動檢測文檔的模式並逐列讀取另一列數據?

我正在將 Tesseract OCR 與 Psm 6 一起使用,它在水平讀取時是錯誤的。

實現這一點的一種方法是使用形態學操作和輪廓檢測。

對於前者,您基本上將所有字符“滲入”成一個大塊狀的斑點。 對於后者,您可以在圖像中找到這些斑點並提取那些看起來很有趣的斑點(意思是:足夠大)。 提取的輪廓

使用的腳本:

import cv2
import sys

SCALE = 4
AREA_THRESHOLD = 427505.0 / 2

def show_scaled(name, img):
    try:
        h, w  = img.shape
    except ValueError:
        h, w, _  = img.shape
    cv2.imshow(name, cv2.resize(img, (w // SCALE, h // SCALE)))

def main():
    img = cv2.imread(sys.argv[1])
    img = img[10:-10, 10:-10] # remove the border, it confuses contour detection
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    show_scaled("original", gray)

    # black and white, and inverted, because
    # white pixels are treated as objects in
    # contour detection
    thresholded = cv2.adaptiveThreshold(
                gray, 255,
                cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,
                25,
                15
            )
    show_scaled('thresholded', thresholded)
    # I use a kernel that is wide enough to connect characters
    # but not text blocks, and tall enough to connect lines.
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 33))
    closing = cv2.morphologyEx(thresholded, cv2.MORPH_CLOSE, kernel)

    im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    show_scaled("closing", closing)

    for contour in contours:
        convex_contour = cv2.convexHull(contour)
        area = cv2.contourArea(convex_contour)
        if area > AREA_THRESHOLD:
            cv2.drawContours(img, [convex_contour], -1, (255,0,0), 3)

    show_scaled("contours", img)
    cv2.imwrite("/tmp/contours.png", img)
    cv2.waitKey()

if __name__ == '__main__':
    main()

然后你所需要的就是計算輪廓的邊界框,並從原始圖像中切割出來。 添加一點邊距並將整個內容提供給tesseract。

暫無
暫無

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

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