py文件编写
from flask import Flask,render_template,request,jsonify
import requests,json,os
from aip import AipOcr
Basepath=os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
#图片上传处理程序
@app.route('/upload_img',methods=['POST'])
def upload_img():
img=request.files.get('img')
path=Basepath+'/static/uploads/'
img_path=path+img.filename
test_path='../static/uploads/'+img.filename
img.save(img_path)
return jsonify({'signal':1,'img_path':test_path})
#图像转文字页面路由配置
@app.route('/image-to-txt', methods=['GET'])
def image():
return render_template('image-to-txt.html')
@app.route('/image-to-txt', methods=['POST'])
def image2():
# 定义常量
APP_ID = '18093507'
API_KEY = 'OeQ8jbtBOjbcYjgWyZtF3SPY'
SECRET_KEY = '13x96WsNkr6TSOseWjtcjRO0nI0WsbkL'
# 初始化AipFace对象
aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# 读取图片
data = json.loads(request.form.get('data'))
word = data['word']
print('图片地址是'+word)
filePath = word
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# 定义参数变量
options = {
'detect_direction': 'true',
'language_type': 'CHN_ENG',
}
# 调用通用文字识别接口
result = aipOcr.basicGeneral(get_file_content(filePath), options)
# print(json.dumps(result).encode('utf-8').decode("unicode-escape"))
res = json.dumps(result).encode('utf-8').decode("unicode-escape")
# print(eval(res)['words_result'])
# 通过eval函数转换成字典
# for word in eval(res)['words_result']:
# print(word['words'])
# print(eval(res)['words_result'])
try:
#json字符串
dic = json.dumps(eval(res)['words_result']).encode('utf-8').decode("unicode-escape")
list1 = []
#json.loads 将字符串转成字典格式
for d in json.loads(dic):
list1.append(d['words'])
result = '\n'.join(list1)
print(result)
return jsonify({"success": 200, "msg": "转换成功", "baiduocr": result})
except:
return jsonify({"success": 100, "msg": "转换失败", "baiduocr": "转换失败,可能是图像内容太复杂或者不清晰,换个图试试吧"})
if __name__ == '__main__':
app.run(debug=True) #FLASK开启调试模式,使程序修改即时生效
flask模板HTML页面编写
图片转文字-文字识别工具.tips{padding: 20px 0px;}
上传图片
转换结果
清空内容
layui.use('form', function(){
var form = layui.form;
//各种基于事件的操作,下面会有进一步介绍
});
layui.use('layer', function(){
var layer = layui.layer;
});
//上传图片JS处理
function changePicture() {
var readfile=new FileReader();
var f=document.getElementById('upload_input').files[0];
readfile.readAsDataURL(f);
readfile.οnlοad=function (e) {
document.getElementById('up_img').src=this.result;
}
}
function confirm_up() {
var formData=new FormData();
var f=document.getElementById('upload_input').files[0];
formData.append('img',f)
$.ajax({
url:"{{ url_for('upload_img') }}",
data:formData,
cache:false,
processData:false,
contentType:false,
type:'POST',
success:function (data) {
if(data.signal==1){
layer.msg('上传成功');
document.getElementById('saveurl').value=data.img_path;
}
}
})
}
//搜索结果局部刷新
$(function(){
$('.fybtn').click(function(){
urls1 = $('#saveurl').val();
urls2 = urls1.replace('..','app') //要在虚拟环境下运行,要不图片路径报错
var word = urls2;
var data= {
data: JSON.stringify({
'word': word,
}),
}
$.ajax({
type: 'POST',
url: '/image-to-txt',
data: data, // 这个data是要post的数据
success: function(data){ // 这个data是接收到的响应的实体
$('.result').val(data['baiduocr']);
}
});
});
});
//点击清空输入框
$('.clearbtn').on('click',function () {
$('.result').html('');
$('.txt').html('');
})