AI Lab上部署demo服务的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/diligent_321/article/details/83444547

1. 引言

​ AI方向有很多的研究领域,比如图像领域有图像识别、OCR识别等,在对算法的效果进行优化后,可以将算法部署在服务器上,方便对外展示AI研发实力,同时也方便其他同学体验算法效果和给出反馈意见,下面介绍如何将自己的算法也部署成demo服务。

2. 功能框架介绍

从整体上来看,整个框架包括如下部分,

  1. 网页前端;
  2. http请求协议;
  3. 数据解析;
  4. 算法inference;
  5. 返回结果到服务器;

3. 算法代码准备

3.1 主程序 index.py(需要修改urls和port)

#!/home/anaconda2/bin/python
# coding: UTF-8

import sys
import os
import tornado.httpserver
import tornado.ioloop
import torndsession
from tornado.options import define, options
define("port", default=6007, help="run on the given port", type=int)

from interface import *

urls = [
    (r'/sample', TextRecognition),
]

def main():
    tornado.options.parse_command_line()
    app=tornado.web.Application(urls,
        template_path=os.path.join(os.path.dirname(__file__), 'template'),
        static_path=os.path.join(os.path.dirname(__file__), 'static'))
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()

3.2 http接口相关代码 interface.py

对于待修改的代码部分,

输入参数:原始图像矩阵,numpy格式;

输出参数:待显示到浏览器页面的结果数据;

# -*- coding: utf-8 -*-
import sys
import os
import hashlib
import time
import urllib2
import json
import datetime
import tornado.web
import tornado.gen
import random
import string
import requests
import main
import numpy as np
from PIL import Image
import cv2
from torndsession.sessionhandler import SessionBaseHandler

class TextRecognition(SessionBaseHandler):
    ocr=main.OCR()
    def get(self):
        pass
    def post(self):
        filepath=self.get_argument('file', '').encode('utf-8')
        im = Image.open(filepath)
        img = np.array(im.convert('RGB'))

        #-----------------------这一部分为待修改代码--------------------------
        result, img_with_boxes, angle, text_recs = self.ocr.detect_and_recognition(img)
        filepath = filepath.split('.')
        filepath.insert(-1,'gen')
        dest_path = '.'.join(filepath) 

        #向服务器返回图片数据。写图片到该文件夹即可,前端会做可视化相关的操作。
        dest_path = dest_path.split('/')[-1]
        dest_path = '/home/share/ocr/gen_pic/'+dest_path
        cv2.imwrite(dest_path, img_with_boxes[:, :, ::-1])

        #向服务器返回文本数据
        self.write('hello world!') #Here is an example
        #-----------------------这一部分为待修改代码,finished!--------------------------

3.3 前向inference代码main.py

# coding:utf-8
import numpy as np
from ctpn.tools.cfg import Config as cfg
from ctpn.src.other import CaffeModel
import cv2, os, caffe, sys
from detectors import TextProposalDetector, TextDetector
import os.path as osp
from utils.timer import Timer
import time

from glob import glob
from PIL import Image
from crnn.crnn import crnnSource
from matplotlib import cm
import model


NET_DEF_FILE="###.prototxt"
MODEL_FILE="###.caffemodel_T"
caffe.set_mode_cpu()


class OCR:
    def __init__(self):
        text_proposals_detector=TextProposalDetector(CaffeModel(NET_DEF_FILE, MODEL_FILE))
        self.text_detector=TextDetector(text_proposals_detector)
        self.recog_model, self.converter = crnnSource()

    def detect_and_recognition(self, img):
        '''result,img,angel分别对应-识别结果,图像的数组,文字旋转角度'''
        #text_recs=self.text_detector.detect(im)
        result, img_with_boxes, angle, text_recs = model.model(img, self.text_detector, self.recog_model, self.converter, detectAngle=False)
        return result, img_with_boxes, angle, text_recs
    

if __name__ == '__main__':
    ocr_obj = OCR()    
    img_path = "./test/ad_test.jpg"
    img_path = "./test/test.png"
    #img_path = "./test/004.jpg"
    im = Image.open(img_path)
    img = np.array(im.convert('RGB'))
    #img, f = resize_im(img, cfg.SCALE, cfg.MAX_SCALE)         
    result, img_with_boxes, angle, text_recs = ocr_obj.detect_and_recognition(img)

    dest_path = dest_path.split('/')[-1]
    dest_path = '/tmp/ocr/gen_pic/'+dest_path
    print dest_path
    cv2.imwrite(dest_path, img_with_boxes[:, :, ::-1])

    print('print recognition result:')
    res = []
    for key in result: 
        res.append(result[key][1]) 
    print('\n'.join(res))

`

注意:这里需要将模型加载等初始化操作放在 _init_ 函数内部,inference核心代码单独放在其余函数内!!!

4. 操作步骤

步骤1:准备优化好的算法模型,本地验证效果Ok;

步骤2:本地验证。将代码修改成main.py中的格式,运行main.py结果正常;

步骤3:修改index.py和interface.py,运行python index.py无语法错误;

步骤4:执行命令 nohup python index.py &,保持服务后台运行。

步骤5:联系服务器管理员,增加前端展示页面。

猜你喜欢

转载自blog.csdn.net/diligent_321/article/details/83444547
AI