Я новичок в мире Python и программирования.У меня есть код, который преобразует изображение в массив NumPy.Я хочу научиться обращать его, т. Е. Преобразовать массив numpy в изображение.
У меня есть код API отдыха, который берет изображение из метода post, конвертирует его в массив numpy, выполняет некоторую обработку и возвращает некоторые результаты.,Однако я пытаюсь изменить код, чтобы я мог взять два изображения в качестве входных данных из метода post, преобразовать его в массив numpy, объединить эти изображения в одно и отправить это окончательное изображение в виде ответа json.
Я успешно изменил код, так что он принимает два изображения в качестве входных данных.Позже я добавлю код для объединения двух изображений в одно.В настоящее время я пытаюсь отправить изображение в ответ JSON.Для этого я просто пытаюсь отправить изображение, полученное методом post, как есть.Но я получаю сообщение об ошибке «Объект типа ndarray не является сериализуемым JSON».Итак, я подумал, что мне следует преобразовать объект ndarray (созданный ранее), который необходимо преобразовать обратно в изображение, чтобы его можно было сериализовать с помощью json.Как это сделать?
# 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
Конвертировать изображение (объект ndarray), чтобы оно могло быть сериализовано в json.