操作系统:Mac os
开发环境:python3.7, opencv2,django
这几天正在了解用python基于django的web开发,学习新的语言或框架,第一个应用,自然是hello world,在django框架下完成一个hello world后,回想之前写过用opencv获取摄像头实时视频的例子,就想能不能把那个程序整合到现有的web中显示,经过一番折腾,终于小有成就,完成一个简单的实例。以下是主要代码:
videocapture.py 打开摄像头,并实时获取视频信息
from django.shortcuts import render
from django.http import HttpResponse, StreamingHttpResponse
import sys
import cv2
import time
import threading
from .netinfo import get_host_ip
if 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 = True
def Camera_isOpened():
global stream, cap
cap = cv2.VideoCapture(stream)
c = 80
width, height = c*4, c*3
width,height = 640,480
resolution = str(width) + "x" + str(height)
orgFrame = None
Running = True
ret = False
stream = 0 #摄像头
try:
Camera_isOpened()
cap = cv2.VideoCapture(stream)
except:
print('Unable to detect camera! \n')
orgFrame = None
ret = False
Running = True
def 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 socket
def 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 admin
from django.urls import path
from views import videocapture
urlpatterns = [
path('',videocapture.home),
path('getVideo',videocapture.getVideo)
]
最新源码:https://github.com/ScottFan/webvideo
支持多浏器访问