验证码识别
验证码识别是爬虫必不可少的一项技能,但是目前的验证码花样百出,此教程只能做到识别较简单的,那些人眼都很难识别,或者字符扭曲混合在一起的验证码也很难做到正确识别。
我们不追求百分百的识别正确率,能达到10%已经是很好的结果。
识别思路:
graph LR
opencv图像预处理-->pytesseract进行识别
如果正确率很差,可以考虑在图像预处理后进行人工训练,使用训练的语言包进行识别
识别过程
graph LR
灰度图转换-->去噪
去噪-->otsu's二值化
otsu's二值化-->pytesseract识别
1.灰度图转换
灰度图转换有多重不同的算法实现,这里使用的算法对应的函数为imread
import cv2
img = cv2.imread('image.png', 0)
第一个参数为文件名,第二个参数有两个值,0代表cv2.IMREAD_RRATSCALE,表示读入灰度图
1代表cv2.IMREAD_COLOR,表示读入彩色图像
2. 去噪
常用图片平滑即图像模糊的方式进行去噪,opencv提供了4种图片平滑的方式:
1)均值滤波器 hamogeneous blur
blur = cv2.blur(img,(5,5))
2) 高斯滤波器 guassian blur
blur = cv2.GaussianBlur(img,(5,5),0)
3) 中值滤波器 median blur
median = cv2.medianBlur(img,5)
4) 双边滤波器 bilatrial blur
blur = cv2.bilateralFilter(img,9,75,75)
两外还有内置的4个函数也可以进行去噪
1. cv2.fastNlMeansDenoising() - works with a single grayscale images
2. cv2.fastNlMeansDenoisingColored() - works with a color image.
3. cv2.fastNlMeansDenoisingMulti() - works with image sequence captured in short period of time (grayscale images)
4. cv2.fastNlMeansDenoisingColoredMulti() - same as above, but for color images.
在遇到的验证码中经过测试,选定高斯滤波器和双边滤波器进行去噪效果较好
3. otsu's二值化
ret, th = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
4. pytesseract进行识别
pytesseract.image_to_string(image1, lang='eng')
其中lang为指定eng语言包
示例代码
# -*- coding:utf-8 -*-
"""
File Name : 'test'.py
Description:
Author: 'chengwei'
Date: '2016/5/24' '10:17'
python:2.7.10
"""
# coding=utf-8
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
import pytesseract
import os
import time
# 获取指定目录下验证码文件列表
image_path = "D:\\test_img"
def get_files(path):
file_list = []
files = os.listdir(path)
for f in files:
if(os.path.isfile(path + '\\' + f)):
file_list.append(path + '\\' + f)
return file_list
# 高斯滤波器
def guassian_blur(img, a, b):
#(a,b)为高斯核的大小,0 为标准差, 一般情况a,b = 5
blur = cv2.GaussianBlur(img,(a,b),0)
# 阈值一定要设为 0!
ret, th = otsu_s(blur)
return ret, th
# 均值滤波器
def hamogeneous_blur(img):
blur = cv2.blur(img,(5,5))
ret, th = otsu_s(blur)
return ret, th
# 中值滤波器
def median_blur(img):
blur = cv2.medianBlur(img,5)
ret, th = otsu_s(blur)
return ret, th
#双边滤波器
def bilatrial_blur(img):
blur = cv2.bilateralFilter(img,9,75,75)
ret, th = otsu_s(blur)
return ret, th
def otsu_s(img):
ret, th = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return ret, th
def main():
"""
测试模糊处理后otsu's二值化
:return:
"""
file_list = get_files(image_path)
for filename in file_list:
print filename
img = cv2.imread(filename, 0)
ret1, th1 = guassian_blur(img, 5, 5)
ret2, th2 = bilatrial_blur(img)
cv2.imwrite('temp1.png', th1)
cv2.imwrite('temp2.png', th2)
titles = ['original', 'guassian', 'bilatrial']
images = [img, th1, th2]
for i in xrange(3):
plt.subplot(1,3,i+1),plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
image1 = Image.open("temp1.png")
image2 = Image.open("temp2.png")
image3 = Image.open(filename)
print pytesseract.image_to_string(image1, lang='eng')
print pytesseract.image_to_string(image2, lang='eng')
print pytesseract.image_to_string(image3, lang='eng')
if __name__ == '__main__':
main()
补充说明:
- 精度不够可以通过人工训练提高,训练方法参考http://www.cnblogs.com/samlin/p/Tesseract-OCR.html
- opencv有很多强大的功能,这只是冰山一角,有兴趣可以到官方主页
- 更好的库?scikit?