gpt4 book ai didi

python - 在 Django 中将 numpy 数组显示为图像

转载 作者:行者123 更新时间:2023-12-02 00:04:11 28 4
gpt4 key购买 nike

我是 Django 框架的新手。我正在建立一个网站,从用户那里获取图像,然后处理图像并返回到一个 numpy 数组(处理过的图像)。我想将 numpy 数组显示为图像。我怎样才能做到这一点?感谢您的阅读和帮助?

index.html

<form name="image" method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>

索引 View

def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
model = MyDeepLearningModel.get_instance()
file_name = request.FILES['file']

processed_image = model.run_png(file_name) #processed_image is an numpy array

#how to show the processed_image in index.html?
return render(request, 'lowlighten/index.html')
else:
form = UploadFileForm()
return render(request, 'lowlighten/index.html', {'form': form})

最佳答案

好吧,让我们首先就一件事达成一致:要在前端显示图像,您需要有该图像的 url,该图像应该存在于已知的某个地方,以便前端可以从中加载它。

所以我假设您不愿意将这张图片保存在任何地方——比如 imgur 之类的——所以最好的办法是从这张图片中创建一个数据 uri。

首先我们需要将您的 numpy 数组转换为图像:

from PIL import Image 

def to_image(numpy_img):
img = Image.fromarray(data, 'RGB')
return img

然后为了从这个图像中得到一个 uri,我们需要进一步处理它:

import base64
from io import BytesIO
def to_data_uri(pil_img):
data = BytesIO()
img.save(data, "JPEG") # pick your format
data64 = base64.b64encode(data.getvalue())
return u'data:img/jpeg;base64,'+data64.decode('utf-8')

现在您已将图像编码为数据 uri,您可以将该数据 uri 传递到前端并在 img 标签中使用它

<img src={{ image_uri }} />

在此基础上,我们可以按如下方式更改您的功能:

def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
model = MyDeepLearningModel.get_instance()
file_name = request.FILES['file']

processed_image = model.run_png(file_name) #processed_image is an numpy array
pil_image = to_image(processed_image)
image_uri = to_data_uri(pil_image)

#how to show the processed_image in index.html?
return render(request, 'lowlighten/index.html', {'image_uri': image_uri})
else:
form = UploadFileForm()
return render(request, 'lowlighten/index.html', {'form': form})

关于python - 在 Django 中将 numpy 数组显示为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61150860/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com