主页

安装支持库(默认你已安装opencv)

sudo pip install flask

python代码:

from flask import Flask, render_template, Response
import cv2

class 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()
        # 因为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:
        frame = camera.get_frame()
        # 使用generator函数输出视频流, 每次请求输出的content类型是image/jpeg
        yield (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) 

index.html(用于显示视频):

<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

在python文件同目录下新建一个文件夹,命名为“templates”,将index.html放入这个文件夹里面

运行python后使用手机连接到同一局域网,在浏览器访问ip就可了

例如树莓派ip:192.168.1.102

则可在手机浏览器访问192.168.1.102:5000/

测试结果:
Screenshot_2020-06-25-18-38-48-090_com.quark.brow.jpg

树莓派 python

版权属于:Asnull
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
0
查看目录

目录

来自 《树莓派+Flask实现视频流媒体WEB服务器》
评论

博主很懒,啥都没有
43 文章数
5,254 评论量
5 分类数
48 页面数
已在风雨中度过 54年116天9小时44分