flask+python 实时视频流输出到前台
生活随笔
收集整理的這篇文章主要介紹了
flask+python 实时视频流输出到前台
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
flask+python 實時視頻流輸出到前臺
二、問題描述:
1。調用攝像頭獲取視頻流
2。將視頻流處理并傳遞給瀏覽器
3。不是錄制后處理,而是邊錄制邊處理,邊傳遞
4。 flash后臺進行處理,而不是在前端處理
三、程序
1、后端處理程序
server.py
from flask import Flask, render_template, Response import cv2 import timeclass VideoCamera(object):def __init__(self):# 通過opencv獲取實時視頻流self.video = cv2.VideoCapture(0)def __del__(self):self.video.release()def get_frame(self):success, image = self.video.read()# 在這里處理視頻幀cv2.putText(image, "hello", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0))## 因為opencv讀取的圖片并非jpeg格式,因此要用motion JPEG模式需要先將圖片轉碼成jpg格式圖片ret, jpeg = cv2.imencode('.jpg', image)return jpeg.tobytes()app = Flask(__name__)@app.route('/') # 主頁 def index():# jinja2模板,具體格式保存在index.html文件中return render_template('index.html')def gen(camera):while True:start_t=time.time()frame = camera.get_frame()#print('{0}'.format(time.time()-start_t))# 使用generator函數輸出視頻流, 每次請求輸出的content類型是image/jpegyield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')@app.route('/video_feed') # 這個地址返回視頻流響應 def video_feed():return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')if __name__ == '__main__':app.run(host='0.0.0.0', debug=True, port=5000)2、前端html
templates/index.html
<html><head><title>Video Streaming Demonstration</title></head><body><h1>Video Streaming Demonstration</h1><img src="{{ url_for('video_feed') }}"></body> </html>注:在py文件同目錄下,新建一個templates,然后新建一個index.html的文件,將上面內容復制進去即可
四、運行結果展示
總結
以上是生活随笔為你收集整理的flask+python 实时视频流输出到前台的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA实验七 图形用户界面的设计与实现
- 下一篇: task3- python与word