操作系统:Mac OS
Python版本:3.7.2
OCR:百度云
遇到的问题:
API测试过程中,遇到API Resopnse 为图片验证码的情况,需要对图片进行识别得到text code,进行断言或者下一步操作。
验证码图片:
直接使用OCR识别图片结果为:
复制代码
1
2
3
4
5/usr/local/bin/python3.7 /Users/test.py -----> hci Process finished with exit code 0
由于图片带有干扰线且文本不规则,所以出现识别错误的情况。
解决方案:
- 对原图片进行“灰度转换”处理
- 二值化
- 百度云OCR识别(点击查看如何使用)
Python代码实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49from 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)
结果打印
复制代码
1
2
3
4
5/usr/local/bin/python3.7 /Users/test.py -----> hxciV Process finished with exit code 0
大功搞成!
最后
以上就是长情芹菜最近收集整理的关于百度云 OCR 识别图片验证码的全部内容,更多相关百度云内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复