问题描述
我正在尝试使用树莓派从USB摄像头捕获图像并使用Django框架进行流式处理我尝试使用StreamingHttpResponse从Opencv2流帧.但是,它只显示1帧,而不替换图像.
I'm trying to use raspberry pi capture the image from USB camera and stream it with Django frameworkI have tried to use StreamingHttpResponse to stream the frame from Opencv2.However, it just shows 1 frame and not replacing the image.
如何实时替换图像?
这是我的代码.
from django.shortcuts import render
from django.http import HttpResponse,StreamingHttpResponse
import cv2
import time
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
ret,image = self.video.read()
ret,jpeg = cv2.imencode('.jpg',image)
return jpeg.tobytes()
def gen(camera):
while True:
frame = camera.get_frame()
yield(frame)
time.sleep(1)
def index(request):
# response = HttpResponse(gen(VideoCamera())
return StreamingHttpResponse(gen(VideoCamera()),content_type="image/jpeg")
推荐答案
@Ritwick我所做的是将 gen 和 index 函数更改为
@Ritwick What I have done is by changing the gen and index function to below
def gen(camera):
while True:
frame = camera.get_frame()
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@gzip.gzip_page
def index(request):
try:
return StreamingHttpResponse(gen(VideoCamera()),content_type="multipart/x-mixed-replace;boundary=frame")
except HttpResponseServerError as e:
print("aborted")
我使用python生成器生成每个摄像机帧,并使用StreamingHttpResponse替换边界标记为 frame
I use the python generator to generate every camera frame and using the StreamingHttpResponse to replace the multipart/x-mixed-replace which the boundary tagged as frame
在django中,有一个gzip装饰器功能.
In django there is a gzip decorator function.
from django.views.decorators import gzip
提高流式传输的速度.我使用django gzip装饰器方法对框架进行gzip处理.
To improve the speed of Streaming. I used the django gzip decorator method to gzip the frame.
这篇关于如何使用django框架实时流式传输opencv框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!