python+百度AI实现卡证类图像身份信息识别


python+百度AI实现卡证类图像身份信息识别

步骤一:进入百度AI开放平台

 步骤二:创建应用,有通用和带有位置信息的两种api,根据需要选择,我这里选择的是通用版

 步骤三:创建成功后,会有三个参数,即:APP_ID, API_KEY, SECRECT_KEY,对应填写到程序的相关位置即可,如图

 步骤四:创建picture文件夹,这里放入你准备识别的图像。

和picture文件夹同目录创建python文件,写入以下代码:

 1 """
 2 Date:2020/03/13
 3 利用百度api实现图片文本识别
 4  
5
""" 6 7 import glob 8 from os import path 9 import os 10 from aip import AipOcr 11 from PIL import Image 12 13 14 def convertimg(picfile, outdir): 15 '''调整图片大小,对于过大的图片进行压缩 16 picfile: 图片路径 17 outdir: 图片输出路径 18 ''' 19 img = Image.open(picfile) 20 width, height = img.size 21 while (width * height > 4000000): # 该数值压缩后的图片大约 两百多k 22 width = width // 2 23 height = height // 2 24 new_img = img.resize((width, height), Image.BILINEAR) 25 new_img.save(path.join(outdir, os.path.basename(picfile))) 26 27 def baiduOCR(picfile, outfile): 28 """利用百度api识别文本,并保存提取的文字 29 picfile: 图片文件名 30 outfile: 输出文件 31 """ 32 filename = path.basename(picfile) 33   #***********************************************************在这里填写你的参数****************************************** 34 APP_ID = '**********' # 刚才获取的 ID,下同 35 API_KEY = '******************' 36 SECRECT_KEY = '******************'42 43 i = open(picfile, 'rb') 44 img = i.read() 45 print("正在识别图片:\t" + filename) 46 message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费 47 # message = client.basicAccurate(img) # 通用文字高精度识别,每天 800 次免费 48 print("识别成功!") 49 i.close() 50 51 with open(outfile, 'a+',encoding='utf-8') as fo: 52 fo.writelines("+" * 60 + '\n') 53 fo.writelines("识别图片:\t" + filename + "\n" * 2) 54 fo.writelines("文本内容:\n") 55 56 # 输出文本内容 57 for text in message.get('words_result'): 58 fo.writelines(text.get('words') + '\n') 59 fo.writelines('\n' * 2) 60 61 print("文本导出成功!") 62 print() 63 64 65 if __name__ == "__main__": 66 67 outfile = 'export.txt' 68 outdir = 'tmp' 69 if path.exists(outfile): 70 os.remove(outfile) 71 if not path.exists(outdir): 72 os.mkdir(outdir) 73 print("压缩过大的图片...") 74 #首先对过大的图片进行压缩,以提高识别速度,将压缩的图片保存与临时文件夹中 75 for picfile in glob.glob("picture/*"): 76 convertimg(picfile, outdir) 77 print("图片识别...") 78 for picfile in glob.glob("tmp/*"): 79 baiduOCR(picfile, outfile) 80 os.remove(picfile) 81 print('图片文本提取结束!文本输出结果位于 %s 文件中。' % outfile) 82 os.removedirs(outdir)

运行结果如下:

测试图像:

输出的文本:

 有什么问题欢迎评论区交流。