Python 使用Opencv和Pytesheract进行验证码预处理和求解
问题 我正在尝试用Python编写代码,用于使用Tesseract OCR进行图像预处理和识别。我的目标是可靠地解决这种形式的验证码 从现在开始的步骤Python 使用Opencv和Pytesheract进行验证码预处理和求解,python,image,opencv,tesseract,python-tesseract,Python,Image,Opencv,Tesseract,Python Tesseract,问题 我正在尝试用Python编写代码,用于使用Tesseract OCR进行图像预处理和识别。我的目标是可靠地解决这种形式的验证码 从现在开始的步骤 图像灰度与阈值化 PIL图像增强 转换为TIF并缩放至>300px 将其馈送至Tesseract OCR(将所有大写字母白名单) 然而,我仍然得到一个相当不正确的读数(EPQ)。我可以采取哪些其他预处理步骤来提高准确性?我的代码和类似性质的附加验证码附在下面 代码 import cv2 import pytesseract from PIL
import cv2
import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
def binarize_image_using_opencv(captcha_path, binary_image_path='input-black-n-white.jpg'):
im_gray = cv2.imread(captcha_path, cv2.IMREAD_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 85, 255, cv2.THRESH_BINARY)
# although thresh is used below, gonna pick something suitable
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite(binary_image_path, im_bw)
return binary_image_path
def preprocess_image_using_opencv(captcha_path):
bin_image_path = binarize_image_using_opencv(captcha_path)
im_bin = Image.open(bin_image_path)
basewidth = 300 # in pixels
wpercent = (basewidth/float(im_bin.size[0]))
hsize = int((float(im_bin.size[1])*float(wpercent)))
big = im_bin.resize((basewidth, hsize), Image.NEAREST)
# tesseract-ocr only works with TIF so save the bigger image in that format
tif_file = "input-NEAREST.tif"
big.save(tif_file)
return tif_file
def get_captcha_text_from_captcha_image(captcha_path):
# Preprocess the image befor OCR
tif_file = preprocess_image_using_opencv(captcha_path)
get_captcha_text_from_captcha_image("path/captcha.png")
im = Image.open("input-NEAREST.tif") # the second one
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('captchafinal.tif')
text = pytesseract.image_to_string(Image.open('captchafinal.tif'), config="-c
tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ -psm 6")
print(text)
主要问题来自字母的不同方向,而不是来自预处理阶段。您做了一些普通的预处理,这应该可以很好地工作,但是您可以用替换阈值,使您的程序在图像亮度方面更加通用 我在与tesseract合作进行汽车牌照识别时遇到了同样的问题。从那个次经历中,我意识到tesseract对图像上文本的方向非常敏感。当图像上的文字水平时,Tesseract可以很好地识别字母。水平方向的文本越多,效果越好
因此,您必须创建一个算法,该算法将检测captcha图像中的每个字母,检测其方向并旋转使其水平,然后进行预处理,然后使用tesseract处理旋转后的水平图像,并将其输出存储在生成的字符串中。然后转到检测下一个字母,执行相同的过程,并在结果字符串中添加tesseract输出。您还需要旋转字母。你必须考虑找到你被检测到的字母的角落。可能会对您有所帮助,因为他们会在图像上旋转文本以提高tesseract的质量。感谢您提出的一些想法。创建一个算法来检测每个字母似乎是一项相当艰巨的任务。对现有的工具有什么建议吗?还有,你认为在我的情况下,有什么深度学习技术会占上风吗?@SimonHolloway,要找到每个字母,请尝试opencv中可用的任何图像分割,如分水岭算法。我建议看一些关于手写识别的论文,它们使用NNs,如CTC和LSTM。这样的识别器需要对字形旋转更加鲁棒。