![](/img/trans.png)
[英]How to extract text from specific bounding boxes in an image using pytesseract?
[英]How to extract text from image using pytesseract?
我正在使用 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']
处理后的图像:
编辑
使用cv2
库更新答案并从图像中获取所有数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.