Gkisi27
Gkisi27

Reputation: 177

How to convert image(ndarray object) to image object so that it can be JSON serialized?

I am new to python and programming world. I have a code which converts image into numpy array. I want to learn how to reverse it i.e. convert the numpy array into image.

I have an rest api code, which takes an image from post method, convert it to numpy array, do some processing and return some results. However, I am trying to modify the code, so that, I can take two image as input from post method, convert it to numpy array, combine those images as one and send that final image as json response.

I have successfully modified the code, so that, it accepts two images as input. I will add later the Code for combining two image into one. Currently, I am trying to send image as json response. For that, I am just trying to send the image I got from post method, as it is. But I am receiving an error of "Object of type 'ndarray' is not JSON serializable". So, I thought, I should convert the ndarray object(Previously created) must be convert back into image so that it can be json serialized. How to do that?

# import the necessary packages
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import numpy as np
import urllib.request
import json
import cv2
import os


@csrf_exempt
def detect(request):
# initialize the data dictionary to be returned by the request
data = {"success":False}

# check to see if this is a post request
if request.method == "POST":
    # check to see if an image was uploaded
    if request.FILES.get("image1", None) and request.FILES.get("image2", None) is not None:
        # grab the uploaded image
        image1 = _grab_image1(stream=request.FILES["image1"])
        image2 = _grab_image2(stream=request.FILES["image2"])

    # otherwise, assume that a URL was passed in
    else:
        # grab the URL from the request
        url = request.POST.get("url", None)

        # if the URL is None, then return an error
        if url is None:
            data["error"] = "No URL provided."
            return JsonResponse(data)

        # load the image and convert
        image1 = _grab_image1(url=url)
        image2 = _grab_image2(url=url)

    # Code for combining two image

    data.update({"final1": image1,"final2": image2, "success": True})

# return a JSON response
return JsonResponse(data)

def _grab_image1(path=None, stream=None, url=None):
# if the path is not None, then load the image from disk
if path is not None:
    image1 = cv2.imread(path) #loads the image


# otherwise, the image does not reside on disk
else:   
    # if the URL is not None, then download the image
    if url is not None:
        resp = urllib.request.urlopen(url)
        data = resp.read()

    # if the stream is not None, then the image has been uploaded
    elif stream is not None:
        data = stream.read()

    # convert the image to a NumPy array and then read it into
    # OpenCV format
    image1 = np.asarray(bytearray(data), dtype="uint8")
    image1 = cv2.imdecode(image1, cv2.IMREAD_COLOR)

# return the image
return image1

def _grab_image2(path=None, stream=None, url=None):
# if the path is not None, then load the image from disk
if path is not None:
    image2 = cv2.imread(path) #loads the image


# otherwise, the image does not reside on disk
else:   
    # if the URL is not None, then download the image
    if url is not None:
        resp = urllib.request.urlopen(url)
        data = resp.read()

    # if the stream is not None, then the image has been uploaded
    elif stream is not None:
        data = stream.read()

    # convert the image to a NumPy array and then read it into
    # OpenCV format
    image2 = np.asarray(bytearray(data), dtype="uint8")
    image2 = cv2.imdecode(image2, cv2.IMREAD_COLOR)

# return the image
return image2

Convert image(ndarray object) so that, it could be json serialized.

Upvotes: 1

Views: 1093

Answers (1)

alexdefelipe
alexdefelipe

Reputation: 197

I don't think it's possible to do what you are trying to do in that way... maybe yo could try two things:

  1. Store it somewhere in the server and serialize its URL.
  2. Encode the image, put the coded image in the JSON and decoded it later. You could try base64 python's library.

If choosing the second option, simply encode the ndarray like this:

coded_image = base64.b64encode(image)

And for decoding:

decoded_image = base64.decodestring(coded_image)

Upvotes: 1

Related Questions