python - 如何使用python从图像中提取文本或数字

标签 python image ocr tesseract python-tesseract

我想像这样从图像中提取文本(主要是数字)

enter image description here

我试过这段代码

import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
img = Image.open('1.jpg')
text = pytesseract.image_to_string(img, lang='eng')
print(text)

但我得到的只是这个 (hE PPAR)

最佳答案

执行 OCR 时,对图像进行预处理很重要,这样要检测的文本为黑色,背景为白色。为此,这里有一个简单的方法,使用 OpenCV 对 Otsu 的图像进行阈值处理,这将生成二值图像。这是预处理后的图像:

enter image description here

我们使用 --psm 6 配置设置将图像视为统一的文本 block 。这是其他configuration options你可以试试。来自 Pytesseract 的结果

01153521976

代码

import cv2
import pytesseract

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

image = cv2.imread('1.png', 0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

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

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

关于python - 如何使用python从图像中提取文本或数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124487/

相关文章:

python - 使用 scipy 和 matplotlib 绘制分位数、中位数和分布

python - 这个打印语法是什么? (打印右移)

python - 从 BeautifulSoup html 解析器获取干净的文本文件

Java - 图形 DrawImage 缩放问题

javascript - 在显示真实网页之前先显示图像一段时间

python - 有没有更好的方法将文字与背景分开?

java - 如何使用人工智能开发光学字符识别器?

python - 安装 pytesser

python - Pandas 数据帧 : Operation per batch of rows

linux - 从pdf文件中提取矢量图像