用Flask构筑微型yolo服务器

深度学习的语言一般是python,需要强大的机器配置,还有GPU,而应用程序一般是其他语言c#,java,php等等,如何把2者联系起来?我们首先想到的就是web方式,因为web跨平台,简单维护方便。

Flask是一个使用 Python 编写的轻量级 Web 应用框架,简单易用著称,正好适合做服务器

  • Flask服务器端代码
from flask import Flask,request,make_response
from PIL import Image
from io import BytesIO
from yolo import YOLO
import json
app = Flask(__name__)

# 加载模型
yolo = YOLO()

# 处理请求
@app.route('/hello', methods=['POST'])
def hello():
    global yolo
    img = request.stream.read()
    f = BytesIO(img)
    image = Image.open(f)
    out_boxes, out_scores, out_classes = yolo.detect_image2(image)
    data = []
    for i, c in reversed(list(enumerate(out_classes))):
        item = {
        'predicted_class': yolo.class_names[c],
        #'box': out_boxes[i],
        'score': str(out_scores[i])
        }
        data.append(item)


    rsp = make_response(json.dumps(data))
    rsp.mimetype = 'application/json'
    rsp.headers['Connection'] = 'close'
    return rsp
if __name__ == '__main__':
    #app.debug = True
    app.run(processes=1,threaded=False)

yolo启动时初始化,常驻内存,这样识别速度就提高很多

注意: app.debug = True这句一定要注释掉,否则会出错,还有要使用单进程单线程,避免同时运行yolo

out_boxes, out_scores, out_classes = yolo.detect_image2(image)

这句调用了yolo3来识别图片,我使用的是keras-yolo3,需要再yolo.py里面追加下面的代码

    def detect_image2(self, image):
        start = timer()

        if self.model_image_size != (None, None):
            assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'
            assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'
            boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
        else:
            new_image_size = (image.width - (image.width % 32),
                              image.height - (image.height % 32))
            boxed_image = letterbox_image(image, new_image_size)
        image_data = np.array(boxed_image, dtype='float32')

        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.

        out_boxes, out_scores, out_classes = self.sess.run(
            [self.boxes, self.scores, self.classes],
            feed_dict={
                self.yolo_model.input: image_data,
                self.input_image_shape: [image.size[1], image.size[0]],
                K.learning_phase(): 0
            })
        return out_boxes, out_scores, out_classes
  • 客户端测试代码 

我们可以使用各种语言来写客户端,这里用python做一个例子 

import requests
import os
import json

url = 'http://127.0.0.1:5000/hello'
headers = {'Content-Type' : 'image/jpeg'}

files = {'media': open('a.jpg', 'rb')}
requests.post(url, files=files)

data = open('a.jpg','rb').read()
r = requests.post(url,data=data, headers=headers, verify=False)
print(r.text)

输出结果如下,结果被封装到json里面,只用了 predicted_class和score,没有用boxes,如需要可以自己加上。

(base) D:\keras\keras-yolo3>python sendimg.py
[{"predicted_class": "puromisu", "score": "0.8895045"}, {"predicted_class": "promise", "score": "0.86596465"}, {"predicted_class": "okamoto", "score": "0.85214925"}]

有了json,我们就可以愉快的和yolo玩耍了!

你可能感兴趣的:(Flask,python,yolo,keras)