当前位置:   article > 正文

python-flask+opencv -摔倒监测-计算机视觉_python摔倒图片样本

python摔倒图片样本

首先,先理清楚文件的结构,flask的静态渲染文件template,以及运行的app.py的位置一定要位于文件的根目录上

 先来看一下效果

 

 

 

 app.py文件如下

  1. from importlib import import_module
  2. import os
  3. from flask import Flask, render_template, Response, request, redirect, url_for
  4. import cv2
  5. import numpy as np
  6. import time
  7. from PIL import Image, ImageDraw, ImageFont
  8. # import main2
  9. if os.environ.get('CAMERA'):
  10. Camera = import_module('camera_' + os.environ['CAMERA']).Camera
  11. else:
  12. from camera import Camera
  13. import main2
  14. app = Flask(__name__)
  15. NAME = ""
  16. FILE_FLAG = False
  17. # CAMERA_FLAG=False
  18. @app.route('/')
  19. def index():
  20. """Video streaming home page."""
  21. return render_template('show.html')
  22. def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
  23. if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
  24. img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  25. # 创建一个可以在给定图像上绘图的对象
  26. draw = ImageDraw.Draw(img)
  27. # 字体的格式
  28. fontStyle = ImageFont.truetype(
  29. "font/simsun.ttc", textSize, encoding="utf-8")
  30. # 绘制文本
  31. draw.text((left, top), text, textColor, font=fontStyle)
  32. # 转换回OpenCV格式
  33. return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  34. def video_gen(name):
  35. """Video streaming generator function."""
  36. cam = cv2.VideoCapture(NAME) #读取文件路径
  37. cam.set(3, 640) # set video widht
  38. cam.set(4, 480) # set video height
  39. scale=0
  40. fg = cv2.createBackgroundSubtractorMOG2()
  41. while True:
  42. time.sleep(0.02)
  43. ret,img = cam.read()
  44. if not ret:break
  45. #canny 边缘检测
  46. image= img.copy()
  47. blurred = cv2.GaussianBlur(image, (3, 3), 0)
  48. gray = cv2.cvtColor(blurred, cv2.COLOR_RGB2GRAY)
  49. xgrad = cv2.Sobel(gray, cv2.CV_16SC1, 1, 0) #x方向梯度
  50. ygrad = cv2.Sobel(gray, cv2.CV_16SC1, 0, 1) #y方向梯度
  51. edge_output = cv2.Canny(xgrad, ygrad, 50, 150)
  52. #背景减除
  53. fgmask = fg.apply(edge_output)
  54. # cv2.imshow("fgmask", fgmask)
  55. #闭运算
  56. hline = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 4), (-1, -1)) #定义结构元素,卷积核
  57. vline = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 1), (-1, -1))
  58. result = cv2.morphologyEx(fgmask,cv2.MORPH_CLOSE,hline)#水平方向
  59. result = cv2.morphologyEx(result,cv2.MORPH_CLOSE,vline)#垂直方向
  60. # cv2.imshow("result", result)
  61. # erodeim = cv2.erode(th,cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)),iterations=1) # 腐蚀
  62. dilateim = cv2.dilate(result,cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4,4)),iterations=1) #膨胀
  63. #查找轮廓
  64. contours, hier = cv2.findContours(dilateim, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  65. for c in contours:
  66. if cv2.contourArea(c) > 1200:
  67. (x,y,w,h) = cv2.boundingRect(c)
  68. if scale==0:scale=-1;break
  69. scale = w/h
  70. cv2.putText(image, "scale:{:.3f}".format(scale), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  71. cv2.drawContours(image, [c], -1, (255, 0, 0), 1)
  72. cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),1)
  73. image = cv2.fillPoly(image, [c], (255, 255, 255)) #填充
  74. #根据人体比例判断
  75. if scale >0 and scale <0.8:
  76. img = cv2ImgAddText(img, "Walking 行走中", 10, 20, (255, 0 , 0), 30)#行走中
  77. # cv2.putText(img, "Walking 行走中", (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)#行走中
  78. if scale >0.8 and scale <1.2:
  79. img = cv2ImgAddText(img, "Falling 中间过程", 10, 20, (255, 0 , 0), 30)#跌倒中
  80. # cv2.putText(img, "Falling 跌倒中", (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)#跌倒中
  81. if scale >1.2:
  82. img = cv2ImgAddText(img, "Falled 跌倒了", 10, 20, (255, 0 , 0), 30)#跌倒了
  83. jpeg = cv2.imencode('.jpg', img)[1].tobytes()
  84. yield (b'--frame\r\n'
  85. b'Content-Type: image/jpeg\r\n\r\n' + jpeg + b'\r\n')
  86. @app.route('/video', methods=['POST','GET'])
  87. def upload():
  88. f = request.files['file']
  89. basepath = os.path.dirname(__file__) # 当前文件所在路径
  90. upload_path = './static/uploads'
  91. if not os.path.exists(upload_path):
  92. os.mkdir(upload_path)
  93. upload_file_path = os.path.join(basepath, upload_path, (f.filename)) # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
  94. upload_file_path=upload_file_path.replace('\\','/')
  95. upload_file_path=upload_file_path.replace('./','')
  96. f.save(upload_file_path)
  97. global NAME, FILE_FLAG
  98. # NAME记录了选择文件的路径
  99. NAME = upload_file_path
  100. FILE_FLAG = True
  101. # CAMERA_FLAG = False
  102. print(NAME)
  103. # return render_template('show.html')
  104. next_url = request.values.get('next', url_for('video_feed'))
  105. return redirect(next_url)
  106. # return redirect(url_for("show"))
  107. @app.route('/video_start', methods=['POST','GET'])
  108. def video_feed():
  109. """Video streaming route. Put this in the src attribute of an img tag."""
  110. if FILE_FLAG:
  111. return Response(video_gen(NAME),mimetype='multipart/x-mixed-replace; boundary=frame')
  112. if __name__ == '__main__':
  113. app.run(host='127.0.0.1', threaded=True, port=5001,debug=True)

运行成功的终端界面如下

 

 

show.html界面如下,使用了在线bootstrap,调用了在线样式

 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  8. <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
  9. <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  10. <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
  11. <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  12. <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  13. <style>
  14. *{
  15. margin: 0;
  16. text-align: center;
  17. }
  18. #input{
  19. margin-left: 780px;
  20. }
  21. #all{
  22. margin-top: 150px;
  23. }
  24. #top{
  25. margin-top:50px;
  26. }
  27. </style>
  28. <title>摔倒监测</title>
  29. </head>
  30. <body>
  31. <div id="all" class="container-xxl">
  32. <h1 class="fw-bolder">摔倒监测</h1>
  33. <h1>检测文件上传</h1>
  34. <form action="/video" enctype='multipart/form-data' method='POST' class="row g-3">
  35. <input style="width:200px" type="file" name="file" class="form-control" id="input">
  36. <button type="submit" class="btn btn-primary mb-3" id="top" >上传</button>
  37. </form>
  38. <img src="url_for={{('video_feed') }}" alt="">
  39. </div>
  40. </body>
  41. </html>

本来想用pyqt完成界面的展示,后来觉得以后可能用flask搭建网页框架比较多,所以选择了使用flask,就当是入门的练手吧。最后因为调试跳转路由出现了bug,加上身体不舒服而错过了上午的答辩,感觉还是很可惜,毕竟是自己一点一点查资料挤出来的 ,不过最终还是赶在今天完成了,希望能给你一点启发,如果觉得还可以就点个赞吧^o^

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

闽ICP备14008679号