深度学习模型预测时间很慢

在做深度学习任务时,我是做图像目标检测,用tensorflow或者keras或者pytorch训练完模型,然后就是做预测,发现无论是用GPU还是CPU都非常慢,然后百度了好久都没有解决问题。

无论是不是配置低,如果我们要做成品,一定要部署。

我每个函数都去用time.time()去计算耗时,最后发现调用模型的时候耗时最多,也是罪魁祸首。
在这里插入图片描述

无论你是调用ssd或者yolo模型,在这里的调用都非常耗时。系统有初始化,每次你去预测一张图片,系统都要重新调用一次模型,初始化一次模型,加载一次模型,这样就很慢了,我们的思路应该是这样,模型一直在系统后台跑着,初始化着,然后直接去用模型去预测就快了。

我是用了flask去做接口然后调用模型的。查了资料,flask对轻量级不错,也是主流的框架。

下面示范flask调用yolo目标检测的代码:

1.创建一个 API.py

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('/yolo', 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启动时初始化,常驻内存,这样识别速度就提高很多

2.在你自己工程的 yolo.py加上这个函数:

    def detect_image2(self, image):
        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

3.用Python写一个调用API接口的 test.py:(这里也可以用其他语言去调用我们的API)

import requests
import os
import json
 
url = 'http://127.0.0.1:5000/yolo'
headers = {'Content-Type' : 'image/jpeg'}
 
files = {'media': open('1.jpg', 'rb')}#你要预测的图片
requests.post(url, files=files)
 
data = open('1.jpg','rb').read()
r = requests.post(url,data=data, headers=headers, verify=False)
print(r.text)

1.jpg就是你要预测的图片

其他模型或者调用视频大家举一反三就好了。

评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzitao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值