flask ajax 上传 图片,python +flask+ajax+百度图像识别接口实现图片异步上传转文字功能(初级版)...

8369a503bcf5bfbebb372ae3fcc2395d.png

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;}

上传图片

确定上传

mobile-image

转换结果

立即转换

清空内容

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('');

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值