使用PaddleOCR识别文字 (二) 代码实现篇

vue页面axios上传图片到后台,python处理上传及识别,识别记录插入数据库。
代码还没拆分,后续优化时候再拆。
server.py

```python
#coding=utf8
import web,sys,os  #引入web.py的包
class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))
 
#定义web应用的路由规则
urls = (
    '/discern/word', 'word'  # 解析图片
)
 
class word:
    def POST(self):
        import time,random,json
        from PIL import Image
        from paddleocr import PaddleOCR, draw_ocr
        from db_config import db_config

        year = time.strftime('%Y',time.localtime(time.time()))
        month = time.strftime('%m',time.localtime(time.time()))
        aiBaseDir = os.path.realpath('./../../server/upload/ai/'+ year+'/'+ month)   # 上传的原始图片基础路径 dir/ai/2020/12
        aiResultDir = os.path.realpath('./../../server/upload/airesult/'+ year+'/'+ month)   # 识别之后的结果图片基础路径 dir/airesult/2020/12
        if not os.path.exists(aiBaseDir):
            os.makedirs( aiBaseDir )
        if not os.path.exists(aiResultDir):
            os.makedirs( aiResultDir )

        inp = web.input(myfile={},type="")  # post的值

        discernType = inp.type  #识别的类型

        #上传图片
        filename = str(time.time()) + str(random.randint(11111,999999)) + inp['myfile'].filename[inp['myfile'].filename.rfind('.'):]  # 文件名

        dbImgUrl = '/' + year + '/' + month + '/' + filename  # 数据库中存的图片路径 /2020/12/a.jpg

        baseFullPath = aiBaseDir +'/'+ filename  #上传的文件全路径
        resultFullPath = aiResultDir +'/'+ filename  #识别之后的文件全路径
        fout = open(baseFullPath,'wb')
        fout.write(inp.myfile.file.read())
        fout.write(inp.myfile.value)
        fout.close()

        ocr = PaddleOCR(use_angle_cls=True, langs="ch")
        result = ocr.ocr(baseFullPath, cls=True)

        # for line in result:
        #     print(line)
        # print(result)

        image = Image.open(baseFullPath).convert('RGB')
        boxes = [line[0] for line in result]
        txts = [line[1][0] for line in result]
        scores = [line[1][1] for line in result]
        imShow = draw_ocr(image, boxes, txts, scores, font_path=os.path.realpath('./../ai/simfang.ttf'))
        imShow = Image.fromarray(imShow)
        imShow.save(resultFullPath)
        web.header('Content-Type','text/json; charset=utf-8', unique=True) #防止中文乱码
        web.header("Access-Control-Allow-Origin", "*", unique=True) #允许跨域
        db = web.database(dbn=db_config['dbn'],host=db_config['host'], user=db_config['user'], pw=db_config['pwd'], db=db_config['database'])
        content = []
        for i in result:
            a = {}
            a['title'] = str(i[1][0])
            a['percent'] = str(i[1][1])
            a['position'] = i[0]
            if a['title']:
                content.append(a)
        insertId = db.insert("T_AI_LOG",IMG = dbImgUrl,IMG_NAME=inp.myfile.filename,TYPE = discernType,CONTENT= json.dumps(content),DATE=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        if insertId:
            return True
        else:
            return False
if __name__ == "__main__":
    app = MyApplication(urls, globals())
    app.run(port=6789)
```

安装nohup

yum install coreutils

后台启动脚本

nohup python3 server.py >/dev/null &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值