test.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from flask import Flask, render_template, Response
  2. import cv2
  3. class VideoCamera(object):
  4. def __init__(self):
  5. # 通过opencv获取实时视频流
  6. self.video = cv2.VideoCapture(0)
  7. def __del__(self):
  8. self.video.release()
  9. def get_frame(self):
  10. success, image = self.video.read()
  11. # 在这里处理视频帧
  12. cv2.putText(image, "hello", (10, 30),
  13. cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0))
  14. # 因为opencv读取的图片并非jpeg格式,因此要用motion JPEG模式需要先将图片转码成jpg格式图片
  15. ret, jpeg = cv2.imencode('.jpg', image)
  16. return jpeg.tobytes()
  17. app = Flask(__name__, static_folder='./static') @ app.route('/')
  18. # 主页
  19. def index():
  20. # jinja2模板,具体格式保存在index.html文件中
  21. return render_template('index.html')
  22. def gen(camera):
  23. while True:
  24. frame = camera.get_frame()
  25. # 使用generator函数输出视频流, 每次请求输出的content类型是image/jpeg
  26. yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @ app.route('/video_feed')
  27. # 这个地址返回视频流响应
  28. def video_feed():
  29. return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')
  30. if __name__ == '__main__':
  31. app.run(host='0.0.0.0', debug=True, port=5000)