【问题标题】:Django show opencv histogram into templateDjango将opencv直方图显示为模板
【发布时间】:2019-01-08 13:53:20
【问题描述】:

我将 Python 3.6Django 1.11opencv 一起使用。

我想要实现的是,用户将上传一张照片,然后在基于新功能的操作上,我将在渲染模板上显示上传的图像直方图。到目前为止,我已经完成了以下操作:

import cv2
import numpy as np
from matplotlib import pyplot as plt

def show(request, id=None):
  instance = get_object_or_404(Album, id=id)
  img = cv2.imread(instance.photo.path)
  color = ('b', 'g', 'r')
  for i, col in enumerate(color):
    histr = cv2.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(histr, color=col)
    plt.xlim([0, 256])

  # here plt.show() will open a new window with the histogram.
  # but I want to show that plt histogram to the below rendered 
  # show.html template
  context = {
    'title': 'Detail',
    'instance': instance,
    'histogram': # here i want to pass the histogram as image
  }
  return render(request, 'album/show.html', context) 

在我的 album/show.html 中,我想显示如下直方图:

<img class="card-img-top" src="{{ --define histogram src here-- }}"
               alt="Card image cap">

有人知道如何实现吗?

提前致谢!

【问题讨论】:

    标签: python django opencv histogram


    【解决方案1】:

    选项 1:

    你可以先保存直方图:

    plt.savefig("album/temp_histogram.png")
    

    然后修改你的album/show.html,你可以把src改成临时的直方图像:

    <img class="card-img-top" src="temp_histogram.png" alt="Card image cap">
    

    选项 2: 还有另一种方法可以做到这一点。您可以先绘制图形,然后将图像转换为字符串,并将其传递给您的 HTML:

    fig = plt.figure()
    fig.canvas.draw()
    
    # convert canvas to image
    histogram_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    histogram_img = histogram_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    # img is rgb, convert to opencv's default bgr
    histogram_img = cv2.cvtColor(histogram_img,cv2.COLOR_RGB2BGR)
    import base64
    img_str = base64.b64encode(cv2.imencode('.jpg', histogram_img)[1])
    

    希望对您有所帮助。

    【讨论】:

    • 它在文件夹中创建一个图像,然后我需要获取图像(我不想保存图像)。我不能在每次函数调用期间动态创建图像并重新创建吗?
    • 当然。但是由于我没有完整的代码来测试,我会添加一些代码供您调试或测试:)
    • 我添加了您编辑的代码。有一个错误main thread is not in main loop。你可以在这里看到我的更新代码:repl.it/repls/FunnyFirmMode
    • 很奇怪,第一种方案你试过了吗?直方图图像是否保存正确?
    • 是的,图片保存正确。我应该在我的代码中添加您以前的代码 + 编辑的代码吗?你看过包含我当前代码的 repl 链接吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2019-07-21
    • 2016-12-13
    • 1970-01-01
    • 2014-07-08
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多