Pytesseract不识别小数点

2024-04-26 00:19:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试阅读这幅图像中的文本,其中也包含小数点和十进制数字 enter image description here

这样:

img = cv2.imread(path_to_image)
print(pytesseract.image_to_string(img))

我得到的是:

73-82
Primo: 50 —

我也尝试指定意大利语,但结果非常相似:

73-82 _
Primo: 50

通过搜索有关stackoverflow的其他问题,我发现使用白名单(在本例中为^{)可以提高十进制数的读取,但我也想读取图像中的单词。关于如何提高十进制数字的阅读能力有什么想法吗


Tags: topath图像image文本imgstring数字
2条回答

我建议将每行文本作为单独的图像传递给tesseract。
出于某种原因,解决小数点问题是很困难的

  • 使用cv2.threshold将图像从灰度转换为黑白
  • 对非常长的水平内核使用cv2.dilate形态学操作(沿水平方向合并块)
  • 使用“查找轮廓”-每个合并行将位于单独的轮廓中
  • 查找轮廓的边界框
  • 根据y坐标对边界框进行排序
  • 迭代边界框,并将切片传递给pytesseract

代码如下:

import numpy as np
import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # I am using Windows

path_to_image = 'image.png'

img = cv2.imread(path_to_image, cv2.IMREAD_GRAYSCALE)  # Read input image as Grayscale

# Convert to binary using automatic threshold (use cv2.THRESH_OTSU)
ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Dilate thresh for uniting text areas into blocks of rows.
dilated_thresh = cv2.dilate(thresh, np.ones((3,100)))


# Find contours on dilated_thresh
cnts = cv2.findContours(dilated_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]  # Use index [-2] to be compatible to OpenCV 3 and 4

# Build a list of bounding boxes
bounding_boxes = [cv2.boundingRect(c) for c in cnts]

# Sort bounding boxes from "top to bottom"
bounding_boxes = sorted(bounding_boxes, key=lambda b: b[1])


# Iterate bounding boxes
for b in bounding_boxes:
    x, y, w, h = b

    if (h > 10) and (w > 10):
        # Crop a slice, and inverse black and white (tesseract prefers black text).
        slice = 255 - thresh[max(y-10, 0):min(y+h+10, thresh.shape[0]), max(x-10, 0):min(x+w+10, thresh.shape[1])]

        text = pytesseract.image_to_string(slice, config="-c tessedit"
                                                          "_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-:."
                                                          "  psm 3"
                                                          " ")

        print(text)

我知道这不是最通用的解决方案,但它成功地解决了您发布的示例。
请将答案视为一个概念性的解决方案-找到一个可靠的解决方案可能非常具有挑战性


结果:

放大后的阈值图像:
enter image description here

第一片:
enter image description here

第二片:
enter image description here

第三部分:
enter image description here

输出文本:

7.3-8.2

Primo:50

通过down-sampling图像,您可以轻松识别

如果将样本减少0.5,结果将是:

enter image description here

现在如果你读到:

7.3 - 8.2
Primo: 50

我使用PyteSeract 0.3.7版本(current)得到了结果

代码:


# Load the libraries
import cv2
import pytesseract

# Load the image
img = cv2.imread("s9edQ.png")

# Convert to the gray-scale
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Down-sample
gry = cv2.resize(gry, (0, 0), fx=0.5, fy=0.5)

# OCR
txt = pytesseract.image_to_string(gry)
print(txt)

说明:


输入图像包含一点伪影。您可以在图像的右侧看到它。另一方面,当前图像非常适合OCR识别。当图像中的数据不可见或损坏时,需要使用预预处理方法。请阅读以下内容:

相关问题 更多 >