在conda的虚拟环境,用python随手写的代码,记录学习
识别图片
path="./"
for path,dir,file in os.walk(path):
break
pic=[]
for i in file:
if(".jpg" in i):
pic.append(i)
path指当前目录下,通过walk来遍历当前目录下的文件,寻找出文件后缀名为jpg的文件并存入pic中
申请百度api
from aip import AipOcr
APP_ID = '#####'
API_KEY = '####'
SECRET_KEY = '###'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
APP_ID,API_KEY,SECRET_KEY三个都是从百度AI创建应用中得到的,输入即可申请调用对应的api
文字识别
def i2t(picname):
with open(picname,'rb') as fp:
image=fp.read()
dic_result=client.basicAccurate(image)
res=dic_result['words_result']
result=''
for m in res:
result+=str(m['words'])
fp2=open('./text/a.txt','a')
fp2.write(result)
fp2.close()
basicAccurate表示百度文字识别的精准识别,通过这个函数来实现文字识别功能;把图片读取到image中,用api完成识别,最后把识别内容写入text文件中的a.txt。
附上完整代码
import os
from aip import AipOcr
APP_ID = '28641495'
API_KEY = 'Fsv5EiwDqk3dpe5DG5x3zFyr'
SECRET_KEY = 'wEtWGygI82wWuDBj0LkxGLDxrGN1UyWG'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
path="./"
for path,dir,file in os.walk(path):
break
pic=[]
for i in file:
if(".jpg" in i):
pic.append(i)
def i2t(picname):
with open(picname,'rb') as fp:
image=fp.read()
dic_result=client.basicAccurate(image)
res=dic_result['words_result']
result=''
for m in res:
result+=str(m['words'])
fp2=open('./text/a.txt','a')
fp2.write(result)
fp2.close()
n=1
for j in pic:
print("picture%d %s...\n" %(n,j))
i2t(j)
n=n+1