【发布时间】:2021-06-07 05:35:53
【问题描述】:
我有观点home:
def home(request):
return render(request, 'detection/home.html')
这是它的模板templates/detection/home.html:
{% extends "detection/base.html" %}
{% block content %}
<h1>Camera View</h1>
<img src="{% url 'cam-feed' %}"></img>
{% endblock content %}
基于 templates/detection/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
在此页面中,从home.html 可以看出,我使用视图cam_feed 显示相机输出:
def cam_feed(request):
return StreamingHttpResponse(gen(VideoCamera(), content_type="multipart/x-mixed-replace;boundary=frame")
它使用类VideoCamera,这是一个openCV类来显示相机,并在get_frame中输出一个prediction变量:
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
_, image = self.video.read()
### All the detections
# Person Existence Classification
# RGB_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
im = Image.fromarray(image)
im = im.resize((128, 128))
img_array = np.array(im)
img_array = np.expand_dims(img_array, axis=0)
prediction = int(model.predict(img_array)[0][0])
_, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
cam_feed 还使用函数gen 以适当的形式传递相机输出:
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')
如何将上面VideoCamera类返回的变量prediction(最好每次接收到新帧并进行预测)发送到模板home.html,以便我可以为用户输出查看。我知道我通常可以将字典 context 传递给 home.html 但我看不到将它从函数 gen 传递到查看 home 的方法,因为它在 StreamingHttpResponse 内部调用,在 <img> 的标签中调用home.html.
【问题讨论】:
标签: django django-views video-streaming streaminghttpresponse