调用百度的OCR接口进行识别
一、百度AI开放平台地址,进入创建 通用文字识别 应用(前提要先注册百度智能云账号)
/tech/ocr?track=cp:ainsem|pf:pc|pp:chanpin-wenzishibie|pu:wenzishibie-API|ci:|kw:10002768
二、安装 baidu-aip
pip install baidu-aip -i /simple/ --trusted-host
三、代码实战
读取这张图片的文字
from aip import AipOcr# APP_ID,API_KEY,SECRET_KEY的值在创建完应用后可以获取到APP_ID = '00000'API_KEY = '0000'SECRET_KEY = '0000000'client = AipOcr(APP_ID, API_KEY, SECRET_KEY)def open_file(filePath):with open(filePath, 'rb') as fp: # 要用二进制读方式打开return fp.read()def get_text(fileName):image = open_file(fileName)dic_result = client.basicGeneral(image)res = dic_result['words_result']return respicture_text = get_text(r'D:\app_project06\777.png') # 括号里是图片的路径print(picture_text)
打印结果如下:(是按行读取的,准确度较高)
[{'words': '4月9日美日要干一件大事中国不可不防!'}, {'words': '世卫组织发布中国一世卫组织新冠病毒溯源'}, {'words': '研究报告外交部回…'}, {'words': '孙小果逞凶踢裂他人膀胱现场首次嘬光!扫'}, {'words': '黑大片全揭秘'}, {'words': '苗苗苗”轻松出圈,深圳卫健委又火了!'}, {'words': '白宫发言人:美国与中国会在分歧中寻求合'}, {'words': '作'}]
也可以做个优化,读取出来的文字连接成一个字符串
from aip import AipOcrAPP_ID = '0000000'API_KEY = '0000000'SECRET_KEY = '00000000000'client = AipOcr(APP_ID, API_KEY, SECRET_KEY)def open_file(filePath):with open(filePath, 'rb') as fp: # 要用二进制读方式打开return fp.read()def get_text(fileName):image = open_file(fileName)dic_result = client.basicGeneral(image)res = dic_result['words_result']result = ''for m in res:result = result + str(m['words'])return resultpicture_text = get_text(r'D:\app_project06\777.png')print(picture_text)
打印结果如下:
4月9日美日要干一件大事中国不可不防!世卫组织发布中国一世卫组织新冠病毒溯源研究报告外交部回…孙小果逞凶踢裂他人膀胱现场首次嘬光!扫黑大片全揭秘苗苗苗”轻松出圈,深圳卫健委又火了!白宫发言人:美国与中国会在分歧中寻求合作