概述
操作系统: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
由于图片带有干扰线且文本不规则,所以出现识别错误的情况。
解决方案:
- 对原图片进行“灰度转换”处理
- 二值化
- 百度云OCR识别(点击查看如何使用)
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
大功搞成!
最后
以上就是长情芹菜为你收集整理的百度云 OCR 识别图片验证码的全部内容,希望文章能够帮你解决百度云 OCR 识别图片验证码所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复