opencv - 如何提高识别率?
问题描述
我给自己设定了识别护照的任务,但我不能完全识别所有区域。告诉我,有什么可以帮助的?使用了不同的过滤和精明算法,但缺少一些东西。Код не может распознать серию и номер документа, а также мелкие символы, иногда не может распознать имя или фамилию с.
# import the necessary packages
from PIL import Image
import pytesseract
import argparse
import cv2
import os
import numpy as np
# построить разбор аргументов и разбор аргументов
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image" )
ap.add_argument("-p", "--preprocess", type=str, default="thresh")
args = vars(ap.parse_args())
# загрузить пример изображения и преобразовать его в оттенки серого
image = cv2.imread ("pt.jpg")
gray = cv2.cvtColor (image, cv2.COLOR_BGR2GRAY)
gray = cv2.Canny(image,300,300,apertureSize = 3)
# check to see if we should apply thresholding to preprocess the
# image
if args["preprocess"] == "thresh":
gray = cv2.threshold (gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# make a check to see if median blurring should be done to remove
# noise
elif args["preprocess"] == "blur":
gray = cv2.medianBlur (gray, 3)
# write the grayscale image to disk as a temporary file so we can
# apply OCR to it
filename = "{}.png".format (os.getpid ())
cv2.imwrite (filename, gray)
# load the image as a PIL/Pillow image, apply OCR, and then delete
# the temporary file
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
text = pytesseract.image_to_string (image, lang = 'rus+eng')
os.remove (filename)
print (text)
os.system('python gon.py > test.txt') # doc output file
# show the output images
cv2.imshow ("Image", image)
cv2.imshow ("Output", gray)
cv2.waitKey (0)
解决方案
当您仅向 Tesseract 提供包含您要解释的文本的区域时,Tesseract 识别文本更容易(也更快),在您的情况下,中间是大的黑色字母,例如:
我指的是仅在绿色区域中运行 Tesseract。由于文档的结构是可预测的,因此您可以轻松找到这些区域,如下所示:
- 二值化和反转图像(黑色=空)
- 使用 opencv 的 connectedComponentsWithStats() 函数获取所有连接组件的列表及其位置和大小
- 您可以硬编码阈值以仅过滤所需的字符,或获取区域的直方图并使用统计数据动态定义阈值
- 在剩余的连接组件上使用形态学操作(例如,使用水平核的膨胀)将字母水平连接在一起
- 得到最终连通分量的边界框
- 可选:后处理在这些孤立的盒子中会更好地工作
将每个边界框作为单独的 Mat 提供给 tesseract,这将大大简化问题。