python将图片实时写在本地并在html上实时显示
时间: 2023-06-01 10:03:45 浏览: 91
要在Python中实时写入图像并在HTML上实时显示,可以使用OpenCV和Flask。下面是一个简单的示例代码:
```python
import cv2
from flask import Flask, render_template, Response
app = Flask(__name__)
camera = cv2.VideoCapture(0) # 打开摄像头
@app.route('/')
def index():
return render_template('index.html') # 返回HTML模板
def gen():
while True:
success, frame = camera.read() # 读取摄像头帧
if not success:
break
ret, buffer = cv2.imencode('.jpg', frame) # 将帧编码为JPEG格式
frame = buffer.tobytes() # 转换为字节串
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # 返回MJPEG流
@app.route('/video_feed')
def video_feed():
return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') # 返回MJPEG流的响应
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True) # 运行Flask应用程序
```
在此示例中,我们使用Flask创建一个Web应用程序,并使用OpenCV从摄像头读取帧。然后,我们将每个帧编码为JPEG格式,并将其作为MJPEG流发送到HTML模板中的img标签。最后,我们使用Flask的Response对象将MJPEG流作为响应发送回客户端。
在HTML模板中,我们可以使用以下代码来显示视频流:
```html
<!DOCTYPE html>
<html>
<head>
<title>Video Streaming with Flask</title>
</head>
<body>
<h1>Video Streaming with Flask</h1>
<img src="{{ url_for('video_feed') }}" />
</body>
</html>
```
这将从Flask应用程序的/video_feed路由中获取MJPEG流,并将其作为img标签的src属性。当我们运行Python脚本并访问http://localhost:5000时,我们应该能够在HTML页面上实时看到摄像头的视频流。
阅读全文
相关推荐
















