python - 使用 PyTesseract 读取数字
问题描述
我正在尝试从图像中读取数字,但无法找到使其始终如一地工作的方法(并非所有图像都有数字)。这些是图像:
(这里是相册的链接,以防图像无法正常工作)
这是我用来在图像上运行 tesseract 的命令:pytesseract.image_to_string(image, timeout=2, config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789')。我尝试了多种配置,但这似乎效果最好。
就预处理而言,这是最好的:
gray = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY_INV)[1]
这适用于除第三张以外的所有图像。为了解决第三张图像中的线条问题,我尝试使用cv2.Canny和一个相当大的阈值来获取边缘,但是当将它们拉回来时,即使它获得了每个数字边缘的 95% 以上,tesseract 也没有正确阅读它们。
我也尝试过调整图像的大小,使用cv2.morphologyEx,模糊它等。我找不到让它适用于每种情况的方法。
谢谢你。
解决方案
cv2.resize
一直为我使用INTER_CUBIC
插值。
将最后一步添加到预处理很可能会解决您的问题。
im_bw_scaled = cv2.resize(im_bw, (0, 0), fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
你可以玩天秤。我在上面使用了“4”。
编辑:
以下代码非常适用于您的图像,甚至是特殊字符。请尝试使用您的其余数据集。缩放、OTSU 和侵蚀是最佳组合。
import cv2
import numpy
import pytesseract
pytesseract.pytesseract.tesseract_cmd = "<path to tesseract.exe>"
# Page segmentation mode, PSM was changed to 6 since each page is a single uniform text block.
custom_config = r'--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789'
# load the image as grayscale
img = cv2.imread("5.png",cv2.IMREAD_GRAYSCALE)
# Change all pixels to black, if they aren't white already (since all characters were white)
img[img != 255] = 0
# Scale it 10x
scaled = cv2.resize(img, (0,0), fx=10, fy=10, interpolation = cv2.INTER_CUBIC)
# Retained your bilateral filter
filtered = cv2.bilateralFilter(scaled, 11, 17, 17)
# Thresholded OTSU method
thresh = cv2.threshold(filtered, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# Erode the image to bulk it up for tesseract
kernel = numpy.ones((5,5),numpy.uint8)
eroded = cv2.erode(thresh, kernel, iterations = 2)
pre_processed = eroded
# Feed the pre-processed image to tesseract and print the output.
ocr_text = pytesseract.image_to_string(pre_processed, config=custom_config)
if len(ocr_text) != 0:
print(ocr_text)
else: print("No string detected")
推荐阅读
- hive - HiveSQL 的 REPLACE() 函数,REGEXP_REPLACE() 未按预期工作
- r - 直接在一个因子上使用 case_when
- nginx - Nginx 条件代理通过配置
- node.js - 为什么我可以从浏览器访问 url 但从节点(axios.get)得到 403 错误(API)
- flutter - Flutter如何在类中保存数组并在任何页面中打印
- java - 字符串对象是不可变的;为什么我能够改变它?
- javascript - 在 JS 中将缓冲区的表示从 int8 转换为 float32
- python - Etsy 上的 HTML 加载错误 - 无法使用 Selenium 找到元素
- python - 与系列对象列表不同的熊猫新列
- node.js - 谷歌云功能上的快递服务器不能提供没有尾随/的静态文件