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
结果: