百度云 OCR 识别图片验证码

操作系统:Mac OS

Python版本:3.7.2

OCR:百度云

遇到的问题:

API测试过程中,遇到API Resopnse 为图片验证码的情况,需要对图片进行识别得到text code,进行断言或者下一步操作。

验证码图片:
在这里插入图片描述
直接使用OCR识别图片结果为:

/usr/local/bin/python3.7 /Users/test.py
-----> hci

Process finished with exit code 0

由于图片带有干扰线且文本不规则,所以出现识别错误的情况。


解决方案:

Python代码实现

from PIL import Image
from aip import AipOcr

# 填入百度OCR API 提供的参数
config = {
    'appId': '---',
    'apiKey': '---',
    'secretKey': '---'
}

client = AipOcr(**config)


""" 1.将图片进行降噪处理, 通过二值化去掉后面的背景色并加深文字对比度 """
def processing_image(img_file, standard=127.5):
    img = Image.open(img_file)

    # 灰度转换
    _image = img.convert('L')

    # 二值化: 根据阈值 standard, 将所有像素都置为 0(黑色) 或 255(白色), 便于接下来的分割
    pixels = _image.load()
    for x in range(_image.width):
        for y in range(_image.height):
            if pixels[x, y] > standard:
                pixels[x, y] = 255
            else:
                pixels[x, y] = 0
    return _image


def get_file_content(file_path):
    with open(file_path, 'rb') as fp:
        return fp.read()


""" 2.将处理后的图片另存为b.png """
image_b = processing_image('a.png')
image_b.save('b.png')
# image_b.show()

""" 3. 通过百度OCR识别b.png"""
image = get_file_content('b.png')
result = client.basicAccurate(image)

text = '\n'.join([w['words'] for w in result['words_result']])
text = text.replace(' ', '')
print('----->', text)

结果打印

/usr/local/bin/python3.7 /Users/test.py
----->  hxciV

Process finished with exit code 0

大功搞成!

猜你喜欢

转载自blog.csdn.net/lan_yangbi/article/details/89251721