推广 热搜:     系统  行业  参数  教师  中国  机械  设备  基金 

python 利用百度API批量识别图片文字【1】

   日期:2024-12-11     移动:http://mip.tpjde.com/quote/3203.html
#!/usr/bin/env python3

python 利用百度API批量识别图片文字【1】

#
-*- coding: utf-8 -*- """ Created on Tue Jun 12 09:37:38 2018 利用百度api实现图片文本识别 @author: XnCSD """ import glob from os import path import os from aip import AipOcr from PIL import Image def convertimg(picfile, outdir): '''调整图片大小,对于过大的图片进行压缩 picfile: 图片路径 outdir: 图片输出路径 ''' img = Image.open(picfile) width, height = img.size while (width * height > 4000000): # 该数值压缩后的图片大约 两百多k width = width // 2 height = height // 2 new_img = img.resize((width, height), Image.BILINEAR) new_img.save(path.join(outdir, os.path.basename(picfile))) def baiduOCR(picfile, outfile): """利用百度api识别文本,并保存提取的文字 picfile: 图片文件名 outfile: 输出文件 """ filename = path.basename(picfile) APP_ID = '自己的' # 刚才获取的 ID,下同 API_KEY = '自己的' SECRECT_KEY = '自己的' client = AipOcr(APP_ID, API_KEY, SECRECT_KEY) i = open(picfile, 'rb') img = i.read() print("正在识别图片: " + filename) message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费 # message = client.basicAccurate(img) # 通用文字高精度识别,每天 800 次免费 print("识别成功!") i.close() try: filename1 = filename.split('.')[0] filename1 = ''.join(filename1) with open(outfile, 'a+') as fo: for text in message.get('words_result'): fo.writelines(''' + filename1 + ''' + ':' + text.get('words') + ',') fo.writelines(' ') # fo.writelines("+" * 60 + ' ') # fo.writelines("识别图片: " + filename + " " * 2) # fo.writelines("文本内容: ") # # 输出文本内容 # for text in message.get('words_result'): # fo.writelines(text.get('words') + ' ') # fo.writelines(' ' * 2) except: print('识别失败') print("文本导出成功!") print() if __name__ == "__main__": outfile = 'port_zidian.txt' outdir = 'tmp' if path.exists(outfile): os.remove(outfile) if not path.exists(outdir): os.mkdir(outdir) print("压缩过大的图片...") #首先对过大的图片进行压缩,以提高识别速度,将压缩的图片保存与临时文件夹中 try: for picfile in glob.glob("端口/*"): convertimg(picfile, outdir) print("图片识别...") for picfile in glob.glob("tmp/*"): baiduOCR(picfile, outfile) os.remove(picfile) print('图片文本提取结束!文本输出结果位于 %s 文件中。' % outfile) os.removedirs(outdir) except: print('失败')
本文地址:http://www.tpjde.com/quote/3203.html    推平第 http://www.tpjde.com/ , 查看更多

特别提示:本信息由相关企业自行提供,真实性未证实,仅供参考。请谨慎采用,风险自负。


相关行业动态
推荐行业动态
点击排行
网站首页  |  关于我们  |  联系方式  |  使用协议  |  版权隐私  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报  |  鄂ICP备2023001713号