利用tesserocr识别图片验证码

一:识别方法

方法一:(简单,但是识别效果不如方法二)

import tesserocr
print(tesserocr.file_to_text('code.png'))

方法二:

import tesserocr
from PIL import Image
image = Image.open('code.png')
result = tesserocr.image_to_text(image)
print(result)

二:验证码处理:

 

import tesserocr
from PIL import Image
image = Image.open('CheckCode.jpg')
result = tesserocr.image_to_text(image)
print(result)

执行结果:ESER

这次执行结果稍有偏差,这是因为验证码中的线条阻止了识别。对于这种情况我们需要一些其他的特殊处理如转灰度、二值化等操作。

我们可以利用Image的convert()传入参数L,即可将图片转化为灰度图像,代码如下:

image = image.convert('L')
image.show()

传入参数“1”可转换为二进制:(采用默认127阈值)

image = image.convert('1')
image.show()
import tesserocr
from PIL import Image
image = Image.open('CheckCode.jpg')
image = image.convert('L')
threshold = 127
table = []
for i in range(256):
    if i <threshold:
        table.append(0)
    else:
        table.append(1)
image = image.point(table,'1')
image.show()
result = tesserocr.image_to_text(image)
print(result)

threhold代表二值化阈值,我们不能直接转化原图,要将原图先转为灰图。然后在指定二值化阈值。

 

posted on 2019-01-31 20:42  萌新python  阅读(448)  评论(0)    收藏  举报