如何使用 django 帧实时流式传输 opencv 帧? [英] How to stream opencv frame with django frame in realtime?
问题描述
我正在尝试使用 raspberry pi 从 USB 摄像头捕获图像并使用 Django 框架进行流式传输我尝试使用 StreamingHttpResponse 从 Opencv2 流式传输帧.但是,它只显示 1 帧而不替换图像.
如何实时替换图片?
这是我的代码.
from django.shortcuts 导入渲染从 django.http 导入 HttpResponse,StreamingHttpResponse导入 cv2导入时间类 VideoCamera(对象):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)返回 jpeg.tobytes()def gen(相机):而真:frame = camera.get_frame()产量(帧)时间.sleep(1)定义索引(请求):# response = HttpResponse(gen(VideoCamera())返回 StreamingHttpResponse(gen(VideoCamera()),content_type="image/jpeg")
@Ritwick 我所做的是将 gen 和 index 函数更改为下面
def gen(camera):而真:frame = camera.get_frame()yield(b'--frame
'b'内容类型:图像/jpeg
' + frame + b'
')@gzip.gzip_page定义索引(请求):尝试:返回 StreamingHttpResponse(gen(VideoCamera()),content_type="multipart/x-mixed-replace;boundary=frame")除了 HttpResponseServerError 作为 e:打印(中止")
我使用 python 生成器生成每个相机帧,并使用 StreamingHttpResponse 替换边界标记为 frame
multipart/x-mixed-replace>在 django 中有一个 gzip 装饰器功能.
from django.views.decorators import gzip</pre>
提高流式传输速度.我使用了 django gzip 装饰器方法来 gzip 框架.
I'm trying to use raspberry pi capture the image from USB camera and stream it with Django framework I have tried to use StreamingHttpResponse to stream the frame from Opencv2. However, it just shows 1 frame and not replacing the image.
How can I replace the image in real time?
Here is my code.
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 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
'
b'Content-Type: image/jpeg
' + frame + b'
')
@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")
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
In django there is a gzip decorator function.
from django.views.decorators import gzip</pre>
To improve the speed of Streaming. I used the django gzip decorator method to gzip the frame.
这篇关于如何使用 django 帧实时流式传输 opencv 帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!