flask读取摄像头并实时显示

本文介绍了一个基于Python的项目,利用OpenCV和Flask框架实现实时视频流传输。通过创建一个视频摄像头类,从设备0捕获视频帧,并将其编码为JPEG格式,以便在网页上正确显示。Flask应用提供了两个路由,一个用于获取实时视频流,另一个用于展示当前的视频画面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

camera.py

import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')
    
    def __del__(self):
        self.video.release()
    
    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

main.py

import os

from flask import Flask, render_template, Response, make_response
from camera import VideoCamera


app = Flask(__name__)

#相机推流
def gen(camera):
    while True:
        frame = camera.get_frame()
        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')

#当前实时相机画面
@app.route('/cur_camera')
def cur_camera():
    return render_template('cur_camer.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)

cur_camer.html

<html>
  <head>
    <title>指纹监控</title>
  </head>
  <body>
    <h1>监控视频</h1>
    <img id="bg" src="{{ url_for('video_feed') }}">
  </body>
</html>

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值