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

问题描述 投票:1回答:1

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

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)

python image ocr tesseract python-tesseract
1个回答
1
投票

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

enter image description here

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()
© www.soinside.com 2019 - 2024. All rights reserved.