操作系统:Mac OS
Python版本:3.7.2
OCR:百度云
遇到的问题:
API测试过程中,遇到API Resopnse 为图片验证码的情况,需要对图片进行识别得到text code,进行断言或者下一步操作。
验证码图片:
直接使用OCR识别图片结果为:
/usr/local/bin/python3.7 /Users/test.py-----> hciProcess finished with exit code 0
由于图片带有干扰线且文本不规则,所以出现识别错误的情况。
解决方案:
对原图片进行“灰度转换”处理二值化百度云OCR识别(点击查看如何使用)Python代码实现
from PIL import Imagefrom 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] = 255else:pixels[x, y] = 0return _imagedef 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-----> hxciVProcess finished with exit code 0
大功搞成!