1.依赖源项目代码
我在网上找了一圈没找到模型是怎么应用的,也许是找到姿势不对,索性自己再源项目中抽离出来了一份代码,如下结构
其中需要修改原detect文件为所需要的,可以通过函数直接调用即可
2.flask接口代码
记得将训练好的base.pt和最开始的data.yaml放到model目录下,开启服务即可
from flask import Flask,request
import io,base64
from my_detect import Detect
app = Flask(__name__)
weights = "./model/best.pt"
data = "./model/data.yaml"
detect = Detect(weights=weights,data=data)
# 预测
@app.route("/prediction",methods=["POST"])
def prediction():
code = 100
data = None
msg = ""
try:
body = request.values.to_dict()
image_64_str = body.get("image","").strip()
if not image_64_str:
raise RuntimeError(f"空数据")
image_byte = io.BytesIO(base64.b64decode(image_64_str))
data = detect.detect(sources=[image_byte])
code = 200
except Exception as e:
msg = f"预测失败:{e}"
return {
"code":code,
"data":data,
"msg":msg,
}
if __name__ == '__main__':
app.run(host="0.0.0.0",port=5056)
3.接口测试
import requests,base64
import cv2
# 验证
def verify(file,box):
img = cv2.imread(file)
cv2.rectangle(img,box[:2],box[2:],(0,0,255),2)
cv2.circle(img,(int(box[0] + (box[2]-box[0])/2),int(box[1] + (box[3]-box[1])/2)),2,(0,0,255))
cv2.imshow("image",img)
cv2.waitKey()
def main(file):
with open(file,"rb") as r1:
image_byte = r1.read()
url = "http://127.0.0.1:5056/prediction"
data = {
"image":base64.b64encode(image_byte).decode("utf-8")
}
resp = requests.post(url=url,data=data)
resp_json = resp.json()
print(resp_json)
verify(file=file,box=tuple(resp_json["data"][0]["xyxy"]))
import os
path = r"img"
for i in os.listdir(path):
print(i)
main(f"{path}\\{i}")
3.接口返回结果如下
{
"code": 200,
"data":
[
{
"size": # 图片大小
[
300,
200
],
"xywh": # 中心点坐标和宽高 归一化后的值
[
0.721666693687439,
0.7099999785423279,
0.16333332657814026,
0.25
],
"xyxy": # 图片左上角xy坐标和右下角坐标xy坐标
[
192,
117,
241,
167
]
}
],
"msg": "-"
}
4.计算滑块的滑动距离
得到返回结果计算一下中心点的坐标,横坐标就是滑动距离了,不过网页上的验证码图片可能会有缩放,实际可能要 *80%,需要按情况测试了,自此结束!
补一下打包的项目代码,需要的自取:项目代码