python - 使用自定义字体的 Pytesseract 错误地对数字进行分类

标签 python image-processing classification ocr python-tesseract

我正在尝试使用 pytesseract 检测价格。

但是我的结果非常糟糕。

我有一张大图片,其中包含不同地点的多个价格。 这些位置是不变的,因此我裁剪图像并将每个区域保存为新图像,然后尝试检测文本。

我知道文本只会包含 0123456789$¢。

我使用 trainyourtesseract.com 训练了我的新字体。

例如,我拍摄了这张图片。

sdf

将其大小加倍,并设置阈值以获得此值。

sdf

通过 tesseract 运行它并获得输出 8

如有任何帮助,我们将不胜感激。

def getnumber(self, img):
   grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
   thresh, grey = cv2.threshold(grey, 50, 255, cv2.THRESH_BINARY_INV)

   filename = "{}.png".format(os.getpid())
   cv2.imwrite(filename, grey)

   text = pytesseract.image_to_string(Image.open(filename), lang='Droid',
                                      config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789.$¢')
   os.remove(filename)
   return(text)

最佳答案

你走在正确的道路上。在对图像进行 OCR 预处理时,您希望文本为黑色,背景为白色。这个想法是放大图像(Otsu 的阈值)以获得二值图像,然后执行 OCR。我们使用 --psm 6 告诉 Pytesseract 假设一个统一的文本 block 。看here了解更多配置选项。这是处理后的图像:

enter image description here

OCR 结果:

代码

import cv2
import pytesseract
import imutils

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Resize, grayscale, Otsu's threshold
image = cv2.imread('1.png')
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Perform text extraction
data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.imwrite('thresh.png', thresh)
cv2.waitKey()

机器规范:

Windows 10
opencv-python==4.2.0.32
pytesseract==0.2.7
numpy==1.14.5

关于python - 使用自定义字体的 Pytesseract 错误地对数字进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60160206/

相关文章:

python - 使用管理员权限打开 cmd (Windows 10)

python测量两个相似图像的质量

python - python 正数的对数结果为负无穷大

machine-learning - 当 k=4 时 KNN 选择类标签

nlp - Keras LSTM 的内部运作

python - Pandas DataFrame to_dict 在 drop_duplicates 之后失败

python - 在Python中循环遍历图像中每个像素的更快方法?

python - 通过每个选择 2 个元素来合并两个列表

algorithm - 推荐人脸检测工具/SDK/等

machine-learning - Weka 中级联分类器的错误方法