我正在使用 python-tesseract 从图像中提取单词。这是 tesseract 的 Python 包装器,它是一个 OCR 代码。
我使用以下代码来获取单词:
import tesseract
api = tesseract.TessBaseAPI()
api.Init(".","eng",tesseract.OEM_DEFAULT)
api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyz")
api.SetPageSegMode(tesseract.PSM_AUTO)
mImgFile = "test.jpg"
mBuffer=open(mImgFile,"rb").read()
result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api)
print "result(ProcessPagesBuffer)=",result
这仅返回单词,而不返回它们在图像中的位置/大小/方向(或者换句话说,包含它们的边界框)。我也想知道是否有什么办法可以得到它
使用
pytesseract.image_to_data()
import pytesseract
from pytesseract import Output
import cv2
img = cv2.imread('image.jpg')
d = pytesseract.image_to_data(img, output_type=Output.DICT)
n_boxes = len(d['level'])
for i in range(n_boxes):
(x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
pytesseract.image_to_data()
返回的数据中:
left
是距边界左上角的距离
框,到图像的左边框。top
是距边界框左上角的距离,
到图像的上边框。width
和 height
是边界框的宽度和高度。conf
是模型预测该边界框中单词的置信度。如果 conf
为 -1,则意味着相应的边界框包含文本块,而不仅仅是单个单词。由
pytesseract.image_to_boxes()
返回的边界框包含字母,所以我相信 pytesseract.image_to_data()
就是您正在寻找的内容。
tesseract.GetBoxText()
方法返回数组中每个字符的确切位置。
此外,还有一个命令行选项
tesseract test.jpg result hocr
将生成一个 result.html
文件,其中包含每个已识别单词的坐标。但不确定是否可以通过python脚本调用。
Python tesseract 可以使用
image_to_boxes
函数来执行此操作,而无需写入文件:
import cv2
import pytesseract
filename = 'image.png'
# read the image and get the dimensions
img = cv2.imread(filename)
h, w, _ = img.shape # assumes color image
# run tesseract, returning the bounding boxes
boxes = pytesseract.image_to_boxes(img) # also include any config options you use
# draw the bounding boxes on the image
for b in boxes.splitlines():
b = b.split(' ')
img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2)
# show annotated image and wait for keypress
cv2.imshow(filename, img)
cv2.waitKey(0)
使用下面的代码你可以得到每个字符对应的边界框。
import csv
import cv2
from pytesseract import pytesseract as pt
pt.run_tesseract('bw.png', 'output', lang=None, boxes=True, config="hocr")
# To read the coordinates
boxes = []
with open('output.box', 'rb') as f:
reader = csv.reader(f, delimiter = ' ')
for row in reader:
if(len(row)==6):
boxes.append(row)
# Draw the bounding box
img = cv2.imread('bw.png')
h, w, _ = img.shape
for b in boxes:
img = cv2.rectangle(img,(int(b[1]),h-int(b[2])),(int(b[3]),h-int(b[4])),(255,0,0),2)
cv2.imshow('output',img)
会在lennon310下发表评论,但没有足够的声誉来发表评论...
在 python 脚本中运行命令行命令
tesseract test.jpg result hocr
:
from subprocess import check_call
tesseractParams = ['tesseract', 'test.jpg', 'result', 'hocr']
check_call(tesseractParams)
要获取单词的边界框:
import cv2
import pytesseract
from pytesseract import Output
img = cv2.imread('test-01.jpg')
d = pytesseract.image_to_data(img, output_type=Output.DICT)
n_boxes = len(d['level'])
for i in range(n_boxes):
if (d['text'][i] != ""):
(x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # in-place operation
cv2.imwrite('result.png', img)
一些示例可以与 pytesseract 一起使用,但是要使用 tesserocr python 库,您可以使用下面给出的代码来查找单个单词及其边界框:-
with PyTessBaseAPI(psm=6, oem=1) as api:
level = RIL.WORD
api.SetImageFile(imagePath)
api.Recognize()
ri = api.GetIterator()
while True::
word = ri.GetUTF8Text(level)
boxes = ri.BoundingBox(level)
print(word,"word")
print(boxes,"coords")
if not ri.Next(level):
break
如前所述,您可以使用 pytesseract 的
image_to_boxes
。您可以查看我的 Docker Hub 存储库 https://hub.docker.com/r/milanhlinak/tesseract-image-to-boxes - 一个使用 Tesseract 5.0.0 的简单 Flask 应用程序。
这是唯一在每个单词周围绘制矩形的解决方案。其他“有效”解决方案也会在文本块周围绘制方框,如果图像包含太多单词,则会导致混乱。这是我正在使用的图像:
import cv2
import pytesseract # version '0.3.10'
from pytesseract import Output
img = cv2.imread("images/easy_text.png")
# Extract recognized data
data = pytesseract.image_to_data(img, output_type=Output.DICT)
n_boxes = len(data["text"])
for i in range(n_boxes):
# Skip -1 confidence, because they correspond with blocks of text
if data["conf"][i] == -1:
continue
# Coordinates
x, y = data["left"][i], data["top"][i]
w, h = data["width"][i], data["height"][i]
# Corners
top_left = (x, y)
bottom_right = (x + w, y + h)
# Box params
green = (0, 255, 0)
thickness = 3 # pixels
cv2.rectangle(img, top_left, bottom_right, green, thickness)
# Save the image
output_image_path = "images/image_with_boxes.jpg"
cv2.imwrite(output_image_path, img)
这是结果: