TaQuangTu
TaQuangTu

Reputation: 2343

Show numpy array as image in Django

I am new to Django framework. I am building a website that take an image from user, then process the image and return to a numpy array (processed image). I want to show the numpy array as image. How can I do that? Thank you for reading and helps?

index.html

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

Index 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})

Upvotes: 3

Views: 2404

Answers (1)

kareem_emad
kareem_emad

Reputation: 1183

Ok, let's first agree on something: to show an image in the frontend, you need to have a url to that image, this image should exist somewhere known so the frontend could load it from.

So I'm assuming you are not willing to save this image anywhere -like imgur or something-, so the best thing to do is to make a data uri out of this image.

First we need to convert your numpy array into an image:

from PIL import Image 

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

Then to get a uri out of this image we need to further process it:

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') 

Now you have your image encoded as a data uri, you can pass that data uri to the frontend and use it in an img tag

<img src={{ image_uri }} />

Based on that we could change your function as follows:

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})

Upvotes: 7

Related Questions