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

6
我希望能从像这样的图像中提取文本(主要是数字)。

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)

1个回答

9
进行OCR时,预处理图像非常重要,使得要检测的文本为黑色,背景为白色。为此,可以使用OpenCV对图像进行Otsu二值化阈值处理,从而得到二值图像。以下是预处理后的图像:

enter image description here

我们使用--psm 6配置设置来将图像视为统一的文本块。这里还有其他配置选项可以尝试。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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接