一、基于Flask创建流媒体服务器的方式
参考GitHub上面Marcelo Rovai的项目(项目地址)
Python代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# camera_pi.py
#
#
#
import time
import io
import threading
import picamera
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
last_access = 0 # time of last client access to the camera
def initialize(self):
if Camera.thread is None:
# start background frame thread
Camera.thread = threading.Thread(target=self._thread)
Camera.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
Camera.last_access = time.time()
self.initialize()
return self.frame
@classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# camera setup
camera.resolution = (320, 240)
camera.hflip = True
camera.vflip = True
# let camera warm up
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# store frame
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
# if there hasn't been any clients asking for frames in
# the last 10 seconds stop the thread
if time.time() - cls.last_access > 10:
break
cls.thread = None
#flask
#app.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 =80, debug=True, threaded=True)
运行效果:
二、基于block Pi的方式
block Pi是专门为树莓派设计的图形化编程软件,与Mixly类似,都是基于Google Blockly的二次开发,而且作者将其完全开源,供大家学习、使用、开发。作者的知乎专栏:https://zhuanlan.zhihu.com/BlockPi
Block Pi代码块及对应的python代码:
运行效果:
三、基于IP摄像头和OpenCV的方式
这种方式我个人认为是非常理想的,因为手机的前置或后置摄像头基本上都要比树莓派CSI接口、USB接口摄像头要好的多,而且相较于web传输,该方式的画面流畅度要好得多,且免去了树莓派连接摄像头的麻烦。
首先需要下载IP摄像头APP:
树莓派运行OpenCV测试代码:
#!/usr/bin/env python
'''
Waveshare OpenCV Tutorial
01_IP_Camera.py
A demo to show whether The OpenCV and IP camera is well installed
'''
import numpy as np
import cv2
def main():
print("OpenCV Version:{}".format(cv2.__version__))
# 0: use CSI camera,1:use USB camera
ip_camera_url = 'http://admin:admin@192.168.10.215:8081'
cap = cv2.VideoCapture(ip_camera_url)
if(not cap.isOpened()):
print("can't open this camera")
while(True):
ret, FrameImage = cap.read()
if ret == True:
cv2.imshow('Camera Capture',FrameImage)
#Press Q to quit
if (cv2.waitKey(1)) == ord('q'):
cap.release()
break
else:
break
if __name__ == '__main__':
print(__doc__)
main()
# Release resource
cv2.destroyAllWindows()
运行效果: