我想从一个附加的图片(png文件)中读取一列数字。
我的代码是
import cv2
import pytesseract
import os
img = cv2.imread(os.path.join(image_path, image_name), 0)
config= "-c
tessedit_char_whitelist=01234567890.:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
pytesseract.image_to_string(img, config=config)
这段代码给了我一个输出字符串:'n113\nun\n1.08'。我们可以看到,有两个问题。
它无法识别1.13中的小数点(见附图)。
它完全不能读取1.11(见所附图片)。它只是返回'nun'。
解决这些问题的办法是什么?
你需要对图像进行预处理。一个简单的方法是调整图像的大小,转换为灰度,并使用大津的阈值获得一个二进制图像。在这里,我们可以应用一个轻微的高斯模糊,然后反转图像,使要提取的文本为白色,背景为黑色。这是处理后的图像,准备用于OCR。
来自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=400) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # Blur and perform text extraction thresh = 255 - cv2.GaussianBlur(thresh, (5,5), 0) data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6')