微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

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

iamdu2019-12-25 22:13:33 浏览: 370720

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页面编写

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图片转文字-文字识别工具</title>
<link rel="stylesheet" href="../static/layui/css/layui.css">	
<link rel="stylesheet" href="../static/style.css">
<script src="../static/jquery-3.4.1.min.js"></script>		
<script src="../static/layui/layui.all.js"></script>	
</head>

<body>
<style type="text/css">
.tips{padding: 20px 0px;}
</style>
	<div style="width: 1200px; margin: 100px auto;">


<form class="layui-form" > <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 -->



<!-- AJAX上传图片STAT-->
  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">上传图片</label>
    <div class="layui-input-block">
      <input id="upload_input" class="admin img-fluid" type="file"  onchange="changePicture(this)">
    </div>

    <div class="layui-input-block">
      <div class="layui-btn"  onclick="confirm_up()">确定上传</div>

    </div>

	<div class="layui-input-block" style="margin-top: 20px;">
    <img id="up_img" src="static/images/up2.png" style="width:30%;height: 30%" alt="mobile-image">
    <input type="" id="saveurl" style="display: none;" name="" value="">
    </div>
  </div>

<!-- AJAX上传图片END-->


  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">转换结果</label>
    <div class="layui-input-block">
      <textarea placeholder="" class="layui-textarea result" style="height: 300px;"></textarea>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <div class="layui-btn fybtn" lay-submit lay-filter="*" >立即转换</div>
      <button type="reset" class="layui-btn layui-btn-primary clearbtn">清空内容</button>
    </div>
  </div>
  <!-- 更多表单结构排版请移步文档左侧【页面元素-表单】一项阅览 -->
</form>
<script src="layui.js"></script>
<script>
layui.use('form', function(){
  var form = layui.form;
  
  //各种基于事件的操作,下面会有进一步介绍
});
layui.use('layer', function(){
  var layer = layui.layer;
  
  
}); 
</script>	
	</div>


  <script type="text/javascript">
    //上传图片JS处理
    function changePicture() {
            var readfile=new FileReader();
            var f=document.getElementById('upload_input').files[0];
            readfile.readAsDataURL(f);
            readfile.onload=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;
                       
                        
                        
                    }

                }
            })

        }
    </script>


<script type="text/javascript">
//搜索结果局部刷新	
$(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('');
    })
</script>
</body>
</html>

 

欢迎留下你的看法

共 0 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注