python - 如何使用 pytesseract 从图像中提取文本?

标签 python image-recognition text-extraction python-tesseract

我正在使用 pytesseract 尝试从图像中提取文本数字。

我正在尝试从这张图片中提取三个数字。

使用 pytesseract 的一个简单方法是:

from PIL import Image
from pytesseract import pytesseract
text = pytesseract.image_to_string(Image.open("uploaded_image.png"))
print(text)

但是打印出来的是空白。

为什么它不能像提取普通文本那样提取数字?

最佳答案

您的图像需要进行一些预处理才能被pytesseract有效处理。

下面显示了在将图像转换为黑白并将其反转之前使用 cv2.adaptiveThreshold()cv2.findContours()cv2.drawContours() 操作的过程:

import numpy as np
import cv2
from PIL import Image
import pytesseract

img = cv2.imread('uploaded_image.png', cv2.IMREAD_COLOR)
img = cv2.blur(img, (5, 5))

#HSV (hue, saturation, value)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)

#Applying threshold on pixels' Value (or Brightness)
thresh = cv2.adaptiveThreshold(v, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

#Finding contours
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#Filling contours
contours = cv2.drawContours(img,np.array(contours),-1,(255,255,255),-1)

#To black and white
grayImage = cv2.cvtColor(contours, cv2.COLOR_BGR2GRAY)

#And inverting it
#Setting all `dark` pixels to white
grayImage[grayImage > 200] = 0
#Setting relatively clearer pixels to black
grayImage[grayImage < 100] = 255
#Write the temp file
cv2.imwrite('temp.png',grayImage)

#Read it with tesseract
text = pytesseract.image_to_string(Image.open('temp.png'),config='tessedit_char_whitelist=0123456789 -psm 6 ')

#Output
print("####  Raw text ####")
print(text)
print()
print("#### Extracted digits ####")
print([''.join([y for y in x if y.isdigit()]) for x in text.split('\n')])

输出

####  Raw text ####
93
31
92

#### Extracted digits ####
['93', '31', '92']

处理后的图像:

enter image description here

编辑

使用cv2库更新答案并从图像中获取所有数字

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

相关文章:

javascript - 有没有办法用JS从渲染页面中获取所有文本?

python - Django Admin - 从添加/编辑组页面上的列表中删除权限

python - 添加一个数字到指定索引范围内的列表

java - 如何检查曲线是否相似

python-3.x - 从 Pandas 数据框中仅提取数字和字符串

java - 使用正则表达式提取子字符串不起作用

python - 在 Python 中迭代一个字符串并添加一些新字符

python - 使用 fabric 和 supervisor 部署 Web 应用程序 - SIGHUP 导致服务器终止

java - Java中图像计算方程

OpenCV 级联分类器训练 : Using more positive images to generate . vec 文件