yolov3 flask部署 返回json(小白教程)

flask基础教程:https://blog.csdn.net/qq_34717531/article/details/107530288

前置条件:

pip install flask

新建文件夹 yolov3flask 其中包含cfg(yolov3的配置文件和权重),images(保存检测图片),out(保存检测后的图片),templates,web.py ,yolov3.py。

yolov3的配置文件和权重,没什么好说的。

templates文件夹里有个upload.html文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
</head>
<body>
    <h1>上传</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <input type="submit" value="上传并识别" class="button-new" style="margin-top:15px;"/>
    </form>
</body>
</html>

web.py

# -*- coding: utf-8 -*-#
#导入flask类库,render_template模板,
from flask import Flask, render_template, request, jsonify, make_response
#安全文件名
from werkzeug.utils import secure_filename
import os
import cv2
import time
import json
from PIL import Image
from io import BytesIO
import json
import numpy as np
from datetime import timedelta
import yolov3
set_upload_path = 'images'
set_result_path = 'out'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
app.send_file_max_age_default = timedelta(seconds=1)
#URL地址
@app.route('/', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "File type exception !"})
        #t就是获取的图片名
        t = f.filename
        #分割,取不带.jpg的文件名
        filename_ = t.split('.')[0]
        user_input = request.form.get("name")
        #工程主目录
        basepath = os.path.dirname(__file__)
        # 文件上传目录地址
        upload_path = os.path.join(basepath, set_upload_path, secure_filename(f.filename))
        f.save(upload_path)
        lab, img, loc, res = yolov3.yolo_detect(pathIn=upload_path)
        
        #检测结果写到的目录
        cv2.imwrite(os.path.join(basepath, set_result_path, filename_+'_res.jpg'), img)
        return res
    return render_template('upload.html')
if __name__ == '__main__':
    app.run(port=4555, debug=True)

yolov3.py

# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
import cv2
import numpy as np
import os
import time
import json

def yolo_detect(im=None,
                pathIn=None,
                label_path='./cfg/coco.names',
                config_path='./cfg/yolov3.cfg',
                weights_path='./cfg/yolov3.weights',
                confidence_thre=0.5,
                nms_thre=0.3):
    LABELS = open(label_path).read().strip().split("\n")
    nclass = len(LABELS)
    np.random.seed(42)
    COLORS = np.random.randint(0, 255, size=(nclass, 3), dtype='uint8')
    if pathIn == None:
        img = im
    else:
        img = cv2.imread(pathIn)
    # print(pathIn)
    filename = pathIn.split('/')[-1]
    name = filename.split('.')[0]
    (H, W) = img.shape[:2]
    net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)
    net.setInput(blob)
    start = time.time()
    layerOutputs = net.forward(ln)
    end = time.time()
    boxes = []
    confidences = []
    classIDs = []
    for output in layerOutputs:
    	for detection in output:
    		scores = detection[5:]
    		classID = np.argmax(scores)
    		confidence = scores[classID]
    		if confidence > confidence_thre:
    			# 将边界框的坐标还原至与原图片相匹配,记住YOLO返回的是
                # 边界框的中心坐标以及边界框的宽度和高度
    			box = detection[0:4] * np.array([W, H, W, H])
    			(centerX, centerY, width, height) = box.astype("int")
    			# 计算边界框的左上角位置
    			x = int(centerX - (width / 2))
    			y = int(centerY - (height / 2))
    			boxes.append([x, y, int(width), int(height)])
    			confidences.append(float(confidence))
    			classIDs.append(classID)
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence_thre, nms_thre)
    lab = []
    loc = []
    data={}
    data["filename"]=filename
    data["counts"]=len(idxs)
    if len(idxs) > 0:
        for i in idxs.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
            text = '{}: {:.3f}'.format(LABELS[classIDs[i]], confidences[i])
            (text_w, text_h), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2)
            cv2.rectangle(img, (x, y-text_h-baseline), (x + text_w, y), color, -1)
            cv2.putText(img, text, (x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
            text_inf = text + ' ' + '(' + str(x) + ',' + str(y) + ')' + ' ' + '宽:' + str(w) + '高:' + str(h)
            info = {"label":LABELS[classIDs[i]],"confidences":confidences[i],"x":str(x),"y":str(y),"w":str(w),"h":str(h)}

            data["data"+str(i)]=info
            # print(filename,LABELS[classIDs[i]],confidences[i],str(x),str(y),str(w),str(h))
            loc.append([x, y, w, h])
            lab.append(text_inf)
    res = jsonify(data)
    return lab, img, loc, res

# if __name__ == '__main__':
#     pathIn = './static/images/test1.jpg'
#     im = cv2.imread('./static/images/test2.jpg')
#     lab, img, loc = yolo_detect(pathIn=pathIn)
#     print(lab)

使用:在主目录下执行

python web.py

结果:

以下是使用Flask框架进行YOLOv8模型部署的示例代码: ```python from flask import Flask, request, jsonify import cv2 import numpy as np app = Flask(__name__) # 加载YOLOv8模型 net = cv2.dnn.readNetFromDarknet('yolov8.cfg', 'yolov8.weights') layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # 定义目标类别 classes = ['class1', 'class2', 'class3'] @app.route('/predict', methods=['POST']) def predict(): # 获取上传的图片 image = request.files['image'] image.save('input.jpg') # 进行目标检测 img = cv2.imread('input.jpg') height, width, channels = img.shape blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) # 绘制边界框和标签 indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) font = cv2.FONT_HERSHEY_PLAIN colors = np.random.uniform(0, 255, size=(len(classes), 3)) for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[class_ids[i]] cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) cv2.putText(img, label, (x, y + 30), font, 3, color, 3) cv2.imwrite('output.jpg', img) # 返回结果 result = { 'image': 'output.jpg', 'detections': len(boxes) } return jsonify(result) if __name__ == '__main__': app.run() ``` 请确保已经安装了Flask和OpenCV库,并将YOLOv8的配置文件(yolov8.cfg)和权重文件(yolov8.weights)放在同一目录下。运行上述代码后,可以通过发送POST请求到`http://localhost:5000/predict`来进行目标检测。请求中需要包含一个名为`image`的文件字段,值为待检测的图片文件。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

学术菜鸟小晨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值