OpenCV---数字验证码识别

推文:Python验证码识别 安装Pillow、tesseract-ocr与pytesseract模块的安装以及错误解决

一:依赖环境安装

pip install Pillow
pip3 install pytesseract

二:安装tesseract-ocr

(一)介绍

其中pytesseract会直接调用tesseract模块,我们需要进行安装

不然可会报错

pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path

(二)下载地址

github地址:   https://github.com/tesseract-ocr/tesseract

(三)下载traineddata训练数据

github地址:https://github.com/tesseract-ocr/tessdata

注意:我们还是要将其设置环境变量

pytesseract.TesseractError: (1, 'Error opening data file \\OtherEnv\\tesseract-Win32\\tessdata/eng.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory. Failed loading language \'eng\' Tesseract couldn\'t load any languages! Could not initialize tesseract.')

现在我们重新启用cmd命令行,可以在cmd命令行调用python文件,获取到验证数据

但是我们在PyCharm中使用时还是需要修改python文件

还有在我们的程序文件中加入环境变量

os.environ['TESSDATA_PREFIX'] = "C:/OtherEnv/tesseract-Win32/tessdata"

三:代码实现

import cv2 as cv
import numpy as np
from PIL import Image
import os
import pytesseract as tess

os.environ['TESSDATA_PREFIX'] = "C:/OtherEnv/tesseract-Win32/tessdata"

def recognize_text(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV|cv.THRESH_OTSU)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(1,2))
    mid1 = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (2,1))
    open_out = cv.morphologyEx(mid1, cv.MORPH_OPEN, kernel)
    cv.imshow("bin1",open_out)

    cv.bitwise_not(open_out,open_out)   #变白色背景
    textImage = Image.fromarray(open_out)

    text = tess.image_to_string(textImage)
    print("result:%s"%text)

src = cv.imread("./y4.png")  #读取图片
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)    #创建GUI窗口,形式为自适应
cv.imshow("input image",src)    #通过名字将图像和窗口联系

recognize_text(src)

cv.waitKey(0)   #等待用户操作,里面等待参数是毫秒,我们填写0,代表是永远,等待用户操作
cv.destroyAllWindows()  #销毁所有窗口

 

posted @ 2018-07-10 10:51  山上有风景  阅读(3551)  评论(0编辑  收藏  举报