我试图在Python上使用PyteSeract从图像中提取文本.这是我想要提取文本的图像:

Original Image

这是应用阈值后的图像:

Image with threshold

控制台输出:

20 hours

20 hours

Bhours

Console Output Image

这是我正在使用的代码:

from pytesseract import *
import cv2

path = r"path where image is located"             #path of image
folderPath = r"path for saving output image" 

grey_image = cv2.imread(path,0)                   #import image

_,bt = cv2.threshold(grey_image, 150 ,255,cv2.THRESH_BINARY)   #variable means binary threshold

cv2.imwrite(folderPath + "\\" + "test.png", bt)   #Saving result

imageout = pytesseract.image_to_string(bt)        #Convert image to text

print(imageout)                                   #Print text in console

我一直在try 不同的阈值范围,但仍然无法获得精确的输出.

为了得到准确的结果,你有什么建议?

推荐答案

由于您要处理的图像在黑暗背景下包含白色字符,建议在使用Pyteseract之前将其反转.

这是用inverted_grey_image = cv2.bitwise_not(grey_image)完成的.

然后可以在threshold:_,bt = cv2.threshold(inverted_grey_image, 140 ,255,cv2.THRESH_BINARY)中调整阈值

以下是完整代码:

from pytesseract import *
import cv2

path = r"path where image is located"             #path of image
folderPath = r"path for saving output image" 

grey_image = cv2.imread(path,0)                   #import image

inverted_grey_image = cv2.bitwise_not(grey_image)

_,bt = cv2.threshold(inverted_grey_image, 140 ,255,cv2.THRESH_BINARY)   #variable means binary threshold

cv2.imwrite(folderPath + "/" + "test.png", bt)   #Saving result

imageout = pytesseract.image_to_string(bt)        #Convert image to text


print(imageout)  

它返回:

20小时

20小时

3小时

EDIT:我目前正在处理一个类似的OCR问题:你可能想判断this recent post的灵感.

Python相关问答推荐

决策树分类器的基础sklearn熵和log_loss标准是否有差异?

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

在pandas DataFrame上运行apply()时如何访问DateTime索引?

零填充2D数组上的Numpy切片

如何修复fpdf中的线路出血

为什么使用SciPy中的Distance. cos函数比直接执行其Python代码更快?

Python如何让代码在一个程序中工作而不在其他程序中工作

pyramid 内部数组中的连续序列-两极

有什么方法可以避免使用许多if陈述

在Python中为变量的缺失值创建虚拟值

连接两个具有不同标题的收件箱

如何在箱形图中添加绘制线的传奇?

重新匹配{ }中包含的文本,其中文本可能包含{{var}

将输入管道传输到正在运行的Python脚本中

为什么这个带有List输入的简单numba函数这么慢

C#使用程序从Python中执行Exec文件

django禁止直接分配到多对多集合的前端.使用user.set()

pandas:排序多级列

提取相关行的最快方法—pandas

使用groupby方法移除公共子字符串