目的
用python提供一个web服务,实时显示摄像头的拍摄内容
准备
用python开发,主要是用flask和opencv的库,先安装
pip3 install flask
pip3 install opencv-python
代码及说明
直接在代码里进行注释说明
python代码:
import numpy as np
import cv2
import time
import keyboard
import os
from flask import Flask, render_template, Response
print("start")
cap = cv2.VideoCapture(0)
if cap.isOpened() == False:
print("can't open camera")
quit()
print("open camera ok")
# 分辨率设置 4:3 3840*2160 1920*1080 1280*720 等
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
# 帧率配置
cap.set(cv2.CAP_PROP_FPS, 24)
# 这里配置一下 template_folder为当前目录,不然可以找不到 index.html
app = Flask(__name__, template_folder='.')
print("index")
# index
@app.route('/')
def index():
return render_template('index.html')
# 获取码流
def gen(cap):
while True:
retgrab = cap.grab()
if retgrab == True:
print("Grab true")
ret1, frame = cap.retrieve()
ret1, jpeg = cv2.imencode('.jpg', frame)
jpg_frame = jpeg.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jpg_frame + b'\r\n')
# 视频处理
@app.route('/video_feed')
def video_feed():
return Response(gen(cap), mimetype='multipart/x-mixed-replace;boundary=frame')
# 执行web服务, 端口号可自行修订
print("app run now!!!")
app.run(host='0.0.0.0', port=65432, debug=True, threaded=True)
# 应该是跑不到这里了
print("release")
cap.release()
cv2.destroyAllWindows()
print("quit")
index.html:
<html>
<head>
</head>
<body>
<h1>Multi-camera with YOLOv5</h1>
<img src="{{ url_for('video_feed') }}" width="50%">
</body>
</html>
测试
执行时会看到如下LOG
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://127.0.0.1:65432
* Running on http://192.168.9.153:65432 (Press CTRL+C to quit)
* Restarting with watchdog (windowsapi)
WEB上直接访问http://192.168.9.153:65432/
或http://192.168.9.153:65432/video_feed
都可以看摄像头拍到的视频了