python - 将 cv2 框架从 View 传递到模板

标签 python django

基本上,我的 django 应用程序需要在 View 中创建图像,并将其传递给模板。这对于字符串来说很容易,但我找不到用图像来实现的方法。我读过很多堆栈溢出线程,但没有一个像我的那样,这令人惊讶。

我正在尝试这种变化作为我的观点:

views.py:

def index(request):
  while (True):

    #video_capture = cv2.VideoCapture(0)
    #ret, frame = video_capture.read()

    img = "D:/Desktop/Tap/bsnsFaces.jpg"
    frame = cv2.imread(img)
    facesNumber ="Found {0} faces!".format(len(faces))

    return render(request, 'result.html', {'p': facesNumber}, {'img': frame})`

最后的 {'img':frame} 部分并不接近右侧。我尝试了一些在 SO 上找到的东西,但到目前为止没有任何效果。我知道图像是静态的,但最终我希望这是从网络摄像头捕获的帧,因此我无法通过使用模型来解决这个问题(或者我可以吗?)。

预先感谢您的任何建议!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Face detection with Django</title>
    <p>{{ p }}</p>
    <img src="data:image/jpg;base64, {{ img }}"></img>
</head>
<body>

</body>
</html>

最佳答案

我建议对帧进行 Base64 编码并传递该字符串。这样您就可以将动态生成的图像从 View 传递到 result.html 进行渲染。然后您可以在 result.html 中显示 base64 图像。

views.py

import cv2
import base64

def index(request):
  #while (True): #Note: This loop is pointless, it will break when you return.

    #video_capture = cv2.VideoCapture(0)
    #ret, frame = video_capture.read()

    img = "D:/Desktop/Tap/bsnsFaces.jpg"
    frame = cv2.imread(img)
    ret, frame_buff = cv2.imencode('.jpg', frame) #could be png, update html as well
    frame_b64 = base64.b64encode(frame_buff)
    facesNumber ="Found {0} faces!".format(len(faces))

    # Note this was fixed to be one dict with the context variables
    return render(request, 'result.html', {'p': facesNumber, 'img': frame_b64})

结果.html

   <img src="data:image/jpeg;base64, {{img}}"></img>

只是基于 while 循环的注释,如果您想从网络摄像头不断更新页面,这应该在客户端完成。否则,您将需要不断刷新页面才能看到图像更新。客户端 (result.html) 可以使用 AJAX 轮询服务器以获取图像更新,并刷新自身,而无需实际重新加载整个 result.html 页面。

关于python - 将 cv2 框架从 View 传递到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373163/

相关文章:

python - 如何处理 Django 的 Queryset 效率低下?

python - 将 3 列合并为一列 pandas

python - 将函数与笔记本目录中其他 python 文件中的变量一起使用

Python命令行: ignore indentation

javascript - 类似于 Wufoo 的 Web 界面(可拖动元素、记住状态)

css - 仅当从 Windows 查看实时站点时,Webapp Roboto 字体异常

python - 使用 xml.etree.ElementTree 解析 XML 文件时出现问题

python - 遍历字典列表并与其他字典进行比较

database - Heroku Django : Running a Worker

python - ImportError : cannot import name simplejson. 我正在使用 django v1.8 和 django-Select2 v4.3.1