Mac平台,python3.7实时获取摄像头数据,通过django框架输出到web实时播放简单实例

操作系统: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 模板页,用于显示视频

<html>
<head>
</head>
<body>
<p>{{Title}}</p>
<p>Local IP:{{LocalIP}}</p>
<img src={{url}} >
</body>
<html>

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 

支持多浏器访问

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值