Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

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 

defto_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
defto_data_uri(pil_img):
    data = BytesIO()
    img.save(data, "JPEG") # pick your format
    data64 = base64.b64encode(data.getvalue())
    returnu'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

<imgsrc={{image_uri }} />

Based on that we could change your function as follows:

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

Post a Comment for "Show Numpy Array As Image In Django"