[英]Captcha preprocessing and solving with Opencv and pytesseract
問題
我正在嘗試使用Tesseract-OCR在Python中編寫用於圖像預處理和識別的代碼。 我的目標是可靠地解決這種形式的驗證碼。
截至目前的步驟
圖像的灰度和閾值
使用PIL增強圖像
轉換為TIF並縮放到> 300px
將它送到Tesseract-OCR(將所有大寫字母列入白名單)
但是,我仍然得到一個相當不正確的讀數(EPQ MQ)。 我可以采取哪些其他預處理步驟來提高准確性? 我的代碼和類似性質的附加驗證碼將在下面附加。
碼
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可以很好地識別字母。 橫向定位的文本越多,您獲得的結果就越好。
因此,您必須創建算法,該算法將檢測驗證碼圖像中的每個字母,檢測其方向並旋轉它以使其水平,然后進行預處理,然后使用tesseract處理此旋轉的水平圖像並將其輸出存儲在結果字符串中。 然后去檢測下一個字母並執行相同的過程並在結果字符串中添加tesseract輸出。 您還需要圖像轉換功能 ,以旋轉您的字母。 而且你必須考慮找到你檢測到的字母的角落。 可能這個項目會幫助你,因為他們在圖像上旋轉文字以提高tesseract的質量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.