Python爬虫识别验证码
安装tesserocr
pip3 install tesserocr pillow
识别测试
将验证码图片放到项目根目录下,用tesserocr库识别该验证码,代码如下所示:
import locale
locale.setlocale(locale.LC_ALL, 'C')
import tesserocr
from PIL import Image
image = Image.open('code.jpg')
result = tesserocr.image_to_text(image)
print(result)
0
1
2
3
4
5
6
7
importlocale
locale.setlocale(locale.LC_ALL,'C')
importtesserocr
fromPILimportImage
image=Image.open('code.jpg')
result=tesserocr.image_to_text(image)
print(result)
新建了一个Image对象,调用了tesserocr的image_to_text( )方法。传入该Image对象即可完成识别,实现过程非常简单,结果如下:
识别的结果和实际结果有偏差,这是因为验证码内的多余线条干扰了图片的识别。
另外,tesserocr还有一个更加简单的方法,这个方法可以直接将图片文件转为字符串,代码如下:
import locale
locale.setlocale(locale.LC_ALL, 'C')
import tesserocr
from PIL import Image
print(tesserocr.image_to_text('code.jpg'))
0
1
2
3
4
5
importlocale
locale.setlocale(locale.LC_ALL,'C')
importtesserocr
fromPILimportImage
print(tesserocr.image_to_text('code.jpg'))
不过这种方法的识别效果不如上一种的好。
对于上面的图片,我们可以看到其实并没有完全识别正确,所以我们需要对图像作进一步的处理,如灰度转换、二值化等操作。
我们可以利用Image对象的convert( )方法参数传入L,即可将图片转化为灰度图像,代码如下:
image = Image.convert('L')
image.show()
0
1
image=Image.convert('L')
image.show()
传入1即可将图片进行二值化处理,如下所示:
image = Image.convert('1')
image.show()
0
1
image=Image.convert('1')
image.show()
我们还可以指定二值化的阈值。上面的方法采用的是默认阈值127。不过我们不能直接转化原图,要将原图先转化为灰度图像,然后再指定二值化阈值,代码如下:
import locale
locale.setlocale(locale.LC_ALL, 'C')
import tesserocr
from PIL import Image
image = Image.open('code.jpg')
image = image.convert('L')
threshold = 160
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
image.show()
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
importlocale
locale.setlocale(locale.LC_ALL,'C')
importtesserocr
fromPILimportImage
image=Image.open('code.jpg')
image=image.convert('L')
threshold=160
table=[]
foriinrange(256):
ifi
table.append(0)
else:
table.append(1)
image=image.point(table,'1')
image.show()
在这里,变量threshold代表二值化阈值,阈值设置为160,之后我们来看看我们的结果:
我们可以看到现在的二维码就比较方便我们进行识别了;那么对于一些有干扰的图片,我们做一些灰度和二值化处理,这会提高图片识别的正确率。