本文共 2890 字,大约阅读时间需要 9 分钟。
操作系统:Mac os
开发环境:python3.7, opencv2,django
这几天正在了解用python基于django的web开发,学习新的语言或框架,第一个应用,自然是hello world,在django框架下完成一个hello world后,回想之前写过用opencv获取摄像头实时视频的例子,就想能不能把那个程序整合到现有的web中显示,经过一番折腾,终于小有成就,完成一个简单的实例。以下是主要代码:
videocapture.py 打开摄像头,并实时获取视频信息
from django.shortcuts import renderfrom django.http import HttpResponse, StreamingHttpResponseimport sysimport cv2import timeimport threadingfrom .netinfo import get_host_ipif sys.version_info.major == 2: print('Please run this program with python3!') sys.exit(0)def home(request): context = {} context["Title"] = "Video" context["LocalIP"] = get_host_ip() context["url"] = "http://"+get_host_ip()+":8000/getVideo" return render(request, 'index.html',context) debug = Truedef Camera_isOpened(): global stream, cap cap = cv2.VideoCapture(stream) c = 80width, height = c*4, c*3width,height = 640,480resolution = str(width) + "x" + str(height)orgFrame = NoneRunning = Trueret = Falsestream = 0 #摄像头try: Camera_isOpened() cap = cv2.VideoCapture(stream)except: print('Unable to detect camera! \n') orgFrame = Noneret = FalseRunning = Truedef get_image(): global orgFrame global ret global Running global stream, cap global width, height while True: if Running: try: if cap.isOpened(): ret, orgFrame = cap.read() else: time.sleep(0.01) except: cap = cv2.VideoCapture(stream) else: time.sleep(0.01)th1 = threading.Thread(target = get_image)th1.setDaemon(True)th1.start()def Video(): global orgFrame while True: if Running: try: if cap.isOpened(): _ , encodedImage = cv2.imencode(".jpg",orgFrame) #yield(b'--frame\r\n' b'Content-Type : image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n') yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + encodedImage.tobytes()+ b'\r\n') else: time.sleep(0.01) except: time.sleep(0.01) print("Exception") else: time.sleep(0.01)def getVideo(request): return StreamingHttpResponse(Video(),content_type='multipart/x-mixed-replace; boundary=frame')
netinfo.py 获取IP地址
import socketdef get_host_ip(): """ 查询本机ip地址 :return: """ try: s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.connect(('8.8.8.8',80)) ip=s.getsockname()[0] finally: s.close() return ip
index.html 模板页,用于显示视频
{
{Title}}Local IP:{
{LocalIP}}
urls.py中的配置
from django.contrib import adminfrom django.urls import pathfrom views import videocaptureurlpatterns = [ path('',videocapture.home), path('getVideo',videocapture.getVideo)]
最新源码:
支持多浏器访问
转载地址:http://hgqbi.baihongyu.com/