我有一个看法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 %}
它基于模板/检测/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
,我使用 view 显示相机输出cam_feed
:
def cam_feed(request):
return StreamingHttpResponse(gen(VideoCamera(), content_type="multipart/x-mixed-replace;boundary=frame")
它使用VideoCamera
作为 openCV 类的类来显示相机并输出prediction
变量get_frame
:
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')
如何prediction
将从上面的类返回的变量VideoCamera
(最好每次接收到新帧并进行预测时)发送到 template home.html
,以便我可以将其输出给用户查看。我知道我通常可以将字典传递给context
,home.html
但我看不到将它从函数传递gen
到视图的方法,因为它在StreamingHttpResponsehome
内部被调用,在.<img>
home.html