2

我有一个看法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,以便我可以将其输出给用户查看。我知道我通常可以将字典传递给contexthome.html但我看不到将它从函数传递gen到视图的方法,因为它在StreamingHttpResponsehome内部被调用,在.<img>home.html

4

1 回答 1

1

如果您只想获得一帧的预测,您不能只为预测添加一个方法并像这样在模板视图中调用该方法吗?:

# where VideoCamera is defined:
class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __del__(self):
        self.video.release()

    def get_frame(self):
        # unchanged...

    def get_prediction(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])
        return prediction

# in views.py:
def home(request):
    cam = VideoCamera()
    prediction = cam.get_prediction()
    return render(request, 'detection/home.html', context={'prediction': prediction})

你也可能想看看django-channels

于 2021-03-17T02:33:40.810 回答