当前位置:   article > 正文

YOLOV5对接微信小程序_微信小程序连接yolov7

微信小程序连接yolov7

在计算机视觉领域,YOLOv5是一种常用的目标检测模型,用于快速而准确地识别图像中的目标。本文将介绍如何将YOLOv5模型应用于小程序,并展示了使用Flask框架实现的示例代码。

首先,我们需要从本地加载自定义的YOLOv5模型。示例代码中,使用了PyTorch库加载模型:

  1. model_path = str(ROOT)
  2. weight_path = str(ROOT / "dataset" / "best.pt")
  3. model = torch.hub.load(model_path, "custom", weight_path, source="local", force_reload=True)

接下来,我们需要创建一个Flask应用,并定义一个路由用于接收上传的图像,并对图像进行目标识别:

  1. @app.route('/upload', methods=['POST'])
  2. def recognize_image():
  3. if 'file' not in request.files:
  4. return '未选择文件'
  5. # 读取上传的图像文件
  6. file = request.files['file']
  7. if file.filename == '':
  8. return '未选择文件'
  9. # 保存文件到本地
  10. save_path = model_path+'/dataset/upload/'
  11. file.save(save_path + file.filename)
  12. imgs = [str(save_path) + file.filename]
  13. img_path = str(save_path) + file.filename
  14. results = model(imgs)
  15. ...
  16. # 对预测结果进行处理
  17. ...
  18. return jsonify({'code': 200, 'msg': msg})

在这个示例中,我们使用了Flask的request模块来处理上传的图像文件。图像文件保存在服务器上并传递给YOLOv5模型进行目标识别。然后,我们可以根据预测结果进行进一步的处理和返回。

除了上传图像进行目标识别外,我们还可以通过另一个路由来进行测试,读取本地图片文件并进行目标识别:

  1. @app.route('/test', methods=['GET'])
  2. def test_detect_objects():
  3. imgs = [str(model_path) + '/dataset/t_1.jpg']
  4. results = model(imgs)
  5. ...
  6. # 对预测结果进行处理
  7. ...
  8. return '识别完成物体为:' + tagname + '的可信度:' + confidence

最后,我们需要在Flask应用的if __name__ == '__main__':部分添加代码来启动Web应用:

  1. if __name__ == '__main__':
  2. app.run(host='0.0.0.0')

现在,你可以将以上代码填充到你的博客中,并根据实际情况进行适当的调整和说明。此示例提供了一个简单的Web应用程序,可以上传图像并使用YOLOv5模型进行目标识别。你可以根据实际需求进行扩展和优化。

下面是接口文件的带代码

  1. import torch
  2. import sys
  3. import os
  4. from pathlib import Path
  5. from flask import Flask, request,jsonify
  6. from PIL import Image, ImageDraw
  7. import matplotlib.pyplot as plt
  8. app = Flask(__name__)
  9. # 从本地加载自定义的YOLOv5模型
  10. FILE = Path(__file__).resolve()
  11. ROOT = FILE.parents[0] # YOLOv5 root directory
  12. if str(ROOT) not in sys.path:
  13. sys.path.append(str(ROOT)) # add ROOT to PATH
  14. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  15. model_path = str(ROOT) # yolov5根目录,需要转换为字符串类型
  16. weight_path = str(ROOT / "dataset" / "best.pt") # 设置正确的权重文件路径
  17. model = torch.hub.load(model_path, "custom", weight_path, source="local", force_reload=True)
  18. # results.show() # 这两句用于看一下模型检测结果
  19. @app.route('/upload', methods=['POST'])
  20. def recognize_image():
  21. # 检查是否存在图像文件
  22. if 'file' not in request.files:
  23. return '未选择文件'
  24. file = request.files['file']
  25. if file.filename == '':
  26. return '未选择文件'
  27. # 保存文件到本地
  28. save_path = model_path+'/dataset/upload/'
  29. file.save(save_path + file.filename)
  30. imgs = [str(save_path) + file.filename] # 设置正确的图像文件路径
  31. img_path = str(save_path) + file.filename
  32. results = model(imgs)
  33. results.print()
  34. results.save(save_path + 'detections')
  35. res = results.pandas().xyxy
  36. confidence = 0
  37. tagname = ''
  38. img = Image.open(img_path)
  39. draw = ImageDraw.Draw(img)
  40. for i, boxes in enumerate(res):
  41. print(f"第 {i + 1} 个结果:")
  42. for _, row in boxes.iterrows():
  43. if row['confidence'] > 0.5:
  44. # 计算模型准确率
  45. confidence = '{:.2%}'.format(row['confidence'])
  46. tagname = row['name']
  47. print(row['confidence'])
  48. # 打印预测结果
  49. print(f"预测标签: {row['name']}")
  50. # 计算模型准确率
  51. # accuracy = calculate_accuracy([(img, pred_index)]) # 使用辅助函数计算准确率
  52. # print("模型准确率: {:.2%}".format(accuracy))
  53. # 处理检测结果并返回
  54. # TODO: 返回处理后的检测结果
  55. if confidence == 0:
  56. msg = '当前没有脉动'
  57. else:
  58. msg = '识别完成物体为:'+tagname+'的可信度:' + confidence
  59. return jsonify({'code': 200, 'msg': msg})
  60. def get_image_path(image_folder, image_file):
  61. # 获取当前脚本文件的路径
  62. script_dir = Path(__file__).resolve().parent
  63. # 构建图片文件的完整路径
  64. image_path = script_dir / image_folder / image_file
  65. return image_path
  66. @app.route('/test', methods=['GET'])
  67. def test_detect_objects():
  68. # 读取本地图片文件
  69. imgs = [str(model_path) + '/dataset/t_1.jpg'] # 设置正确的图像文件路径
  70. results = model(imgs)
  71. results.print()
  72. res = results.pandas().xyxy
  73. confidence = 0;
  74. for i, boxes in enumerate(res):
  75. print(f"第 {i + 1} 个结果:")
  76. for _, row in boxes.iterrows():
  77. if row['confidence']>0.5:
  78. confidence = '{:.2%}'.format(row['confidence'])
  79. print(row['confidence'])
  80. # 打印预测结果
  81. print(f"预测标签: {row['name']}")
  82. # 计算模型准确率
  83. # accuracy = calculate_accuracy([(img, pred_index)]) # 使用辅助函数计算准确率
  84. # print("模型准确率: {:.2%}".format(accuracy))
  85. # 处理检测结果并返回
  86. # TODO: 返回处理后的检测结果
  87. return '识别完成物体为:的可信度:'+confidence
  88. if __name__ == '__main__':
  89. app.run(host='0.0.0.0')

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/480812
推荐阅读
相关标签
  

闽ICP备14008679号