NumPy array is not JSON serializable

在利用django将后端算法处理过的图像显示在前端界面的过程中,后端向前端的传输接口如下:

# 接口函数
def post(request):
    if request.method == 'POST':  # 当提交表单时
        dic = {}
        #data={'name':"服务器正常运转!"}  # 返回客户端的数据
        # 判断是否传参
        if request.POST:
            #print(request.POST) # 查看客户端发来的请求内容
            image_path = request.POST.get('a', 0)
            #b = request.POST.get('b', 0)
            # 判断参数中是否含有a
            if image_path :
                #res = add_args(a, b)
                image,result=main(image_path=image_path)
                if isinstance(image, np.ndarray):
                     image=image.tolist()
                dic['result'] = image
                dic = json.dumps(dic)      #,cls=NumpyEncoder)
                return HttpResponse(dic)    #,JsonResponse(data)
            else:
                return HttpResponse('输入错误!')
        else:
            return HttpResponse('输入为空')
    else:
        return HttpResponse('请输入红外图像路径!')

上面红色部分代码报错:    NumPy array is not JSON serializable

解决办法,参考:https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
            np.int16, np.int32, np.int64, np.uint8,
            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32, 
            np.float64)):
            return float(obj)
        elif isinstance(obj,(np.ndarray,)): #### This is the fix
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

dumped = json.dumps(data, cls=NumpyEncoder)

with open(path, 'w') as f:
    json.dump(dumped, f)

根据上述部分的代码,修改原来的代码为:

# 接口函数
def post(request):
    if request.method == 'POST':  # 当提交表单时
        dic = {}
        #data={'name':"服务器正常运转!"}  # 返回客户端的数据
        # 判断是否传参
        if request.POST:
            #print(request.POST) # 查看客户端发来的请求内容
            image_path = request.POST.get('a', 0)
            #b = request.POST.get('b', 0)
            # 判断参数中是否含有a
            if image_path :
                #res = add_args(a, b)
                image,result=main(image_path=image_path)
                if isinstance(image, np.ndarray):
                     image=image.tolist()
                dic['result'] = image
                dic = json.dumps(dic,cls=NumpyEncoder)     # 修改的部分!
                return HttpResponse(dic)    #,JsonResponse(data)
            else:
                return HttpResponse('输入错误!')
        else:
            return HttpResponse('输入为空')
    else:
        return HttpResponse('请输入红外图像路径!')

 

你可能感兴趣的:(机器学习)