转载自:https://www.jianshu.com/p/7ef5490fbef7css
这里使用的是树莓派的官方摄像头,使用普通的 USB 摄像头也能够,但前提是你可以搞的定它的驱动。html
大概张这个样子:python
在关机状态下,将软排线插入到树莓派的 CAMERA 接口上,开机。运行树莓派配置工具来激活摄像头模块:git
$ sudo raspi-config
移动光标至菜单中的 "Enable Camera(启用摄像头)",将其设为Enable(启用状态)。完成以后重启树莓派。github
在重启完树莓派后,咱们就可使用Pi Cam了。要用它来拍摄照片的话,能够从命令行运行raspistill:web
$ raspistill -o pic.jpg -t 2000
使用 Flask 框架发布Python Web服务,用户能够得到实时视频流数据。flask
首先要作的是在你的树莓派上安装Flask。以前已经讨论过如何安装 Flask了,在此再也不赘述。浏览器
因为此项目涉及到比较多的文件,咱们要创建一个工做目录。服务器
切换到咱们以前建立的 myPiCar 文件夹,使他成为当前工做目录。网络
如今,在这个文件夹上,咱们将建立两个子文件夹:静态的CSS、最终的JavaScript文件以及HTML文件的模板。 转到你的新建立的文件夹。
建立2个新的子文件夹:
mkdir static mkdir templates
最终的目录“树”,以下所示:
├── myPiCar
├── templates
└── static
下载 Miguel Grinberg 的树莓派相机软件包 camera_pi.py 并将其保存在建立的目录myPiCar上。 这是咱们项目的核心,Miguel 的安装包至关的不错。
如今,使用Flask,让咱们调整原始的 Miguel 的 web 服务器应用程序(app.py),建立一个特定的python脚原本渲染咱们的视频。 咱们能够命名为appCam.py。
from flask import Flask, render_template, Response # Raspberry Pi camera module (requires picamera package, developed by Miguel Grinberg) from camera_pi import Camera app = Flask(__name__) @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html') def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', port =8000, debug=True, threaded=True)
以上脚本将你的摄像机视频流式传输到 index.html 页面上,在 templates 目录下新建 index.html 文件,写入如下内容:
<html> <head> <title>Live Streaming</title> <link rel="stylesheet" href='../static/style.css'/> </head> <body> <h1>Live Streaming</h1> <h3><img src="{{ url_for('video_feed') }}" width="90%"></h3> <hr> </body> </html>
index.html 最重要的一行是:
<img src="{{ url_for('video_feed') }}" width="50%">
视频将会在这里“反馈”到咱们的网页上。
在静态目录中需包含style.css文件,这是网页正常显示所必须的样式文件。到目前为止,咱们的文件树结构以下。
├── myPiCar ├── camera_pi.py ├── appCam.py ├── templates | ├── index.html └── static ├── style.css
全部文件均可以从个人GitHub仓库下载得到:myPiCar。
如今,在终端上运行python脚本:
sudo python appCam.py