Django将opencv直方图显示到模板中



我使用Python 3.6Django 1.11以及opencv

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

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) 

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

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

有人知道如何做到这一点吗?

提前感谢!

选项1:

您可以先保存直方图:

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

然后修改你的相册/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])

希望它能有所帮助。

最新更新