Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django <;HttpResponse状态“U代码=200”;图片/png“&燃气轮机;JSON不可序列化_Django_Httpresponse - Fatal编程技术网

Django <;HttpResponse状态“U代码=200”;图片/png“&燃气轮机;JSON不可序列化

Django <;HttpResponse状态“U代码=200”;图片/png“&燃气轮机;JSON不可序列化,django,httpresponse,Django,Httpresponse,我建立了一个CNN模型,能够很好地分类。但是我想尝试在url中传递图像时使用Django对图像的类进行分类。以下是我尝试过的几件事。my apps.py中的预测功能 def prediction(image_loc): image_path = 'D:/' image = cv2.imread(os.path.join(image_path,image_loc)) print("image in matrix is ", image) output = image

我建立了一个CNN模型,能够很好地分类。但是我想尝试在url中传递图像时使用Django对图像的类进行分类。以下是我尝试过的几件事。my apps.py中的预测功能

def prediction(image_loc):
    image_path = 'D:/'
    image = cv2.imread(os.path.join(image_path,image_loc))
    print("image in matrix is ", image)
    output = image.copy()

    # Pre-Process the image for classification
    image = cv2.resize(image, (96, 96))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    # Load the trained convolutional neural network and the label binarizer
    print("[INFO] Loading Model...")
    model_RP = load_model(os.path.join(os.getcwd(), "model\cnn_model_RP.hdf5"))
    lb_path = os.path.join(os.getcwd(),"model\labelbin_RP")
    lb_RP = pickle.loads(open(lb_path, "rb").read())
    print("[INFO] Model Loading Complete.")

    # Classify the input image
    print("[INFO] classifying image...")
    proba = model_RP.predict(image)[0]
    idx = np.argmax(proba)
    label = lb_RP.classes_[idx]

    #we will mark our prediction as "correct" of the input image filename contains the predicted label text 
    #(obviously this makes the assumption that you have named your testing image files this way)

    filename = image_loc[image_loc.rfind(os.path.sep) + 1:]
    correct = "correct" if filename.rfind(label) != -1 else "incorrect"

    # Build the label and draw the label on the image
    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    output = imutils.resize(output, width=400)
    cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    # show the output image
    print("[INFO] {}".format(label))
    #plt.imshow(output)
    #plt.show()

    #return(plt.show())
    return(label) #- WORKING

    #return HttpResponse(output, content_type = 'image/png')  
    #resp = HttpResponse("", content_type = 'image/png')
    #resp.write('output')
    #return resp

  • 如果我只返回它工作的标签,下面是我的apps.py中的代码片段
  • 问题就在这里。我试图返回的图像以及标签上。我没有成功

        label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
        output = imutils.resize(output, width=400)
        cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) 
    
        return HttpResponse(output, content_type = 'image/png')
    
    2.b这里是返回图像的第二种方法,不幸失败

         label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
         output = imutils.resize(output, width=400)
         cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)      
         resp = HttpResponse("", content_type = 'image/png')
         resp.write('output')
         return resp
    
  • 这是我的观点
  • 在浏览器上运行以下命令时,堆栈跟踪错误

    http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
    
    /model/img处的类型错误 JSON不可序列化 请求方法:获取 请求URL:http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png Django版本:2.2.12 异常类型:TypeError 异常值: JSON不可序列化 异常位置:默认情况下为C:\Anaconda3\envs\tf35\lib\json\encoder.py,第179行 Python可执行文件:C:\Anaconda3\envs\tf35\Python.exe Python版本:3.5.5 Python路径: ['D:\\discreen\\Term 3\\deploy', 'C:\\Anaconda3\\envs\\tf35\\python35.zip', 'C:\\Anaconda3\\envs\\tf35\\DLLs', 'C:\\Anaconda3\\envs\\tf35\\lib', 'C:\\Anaconda3\\envs\\tf35', 'C:\\Users\\prade\\AppData\\Roaming\\Python\\Python35\\site packages', 'C:\\Anaconda3\\envs\\tf35\\lib\\site packages', 'C:\\Anaconda3\\envs\\tf35\\lib\\site packages\\win32', 'C:\\Anaconda3\\envs\\tf35\\lib\\site packages\\win32\\lib', 'C:\\Anaconda3\\envs\\tf35\\lib\\site packages\\Pythonwin'] 服务器时间:2020年5月29日星期五04:35:18+0000 试图查看类似的帖子,但它们与文本相关,因此无法解决我的问题


    有人能帮忙吗。

    看起来
    resp
    是一个
    HttpResponse
    对象(说不出更多,您没有为
    预测提供代码)

    您必须在
    Response()
    构造函数中使JSON可序列化(通常是一个dict或一个列表,只有string/int/boolean)


    (顺便说一句,Django Rest框架的
    @api_视图
    装饰器已经过时,
    @action
    更倾向于使用最新版本)

    请提供错误的堆栈跟踪以及在响应中返回的JSON示例。添加了错误跟踪,将预测函数添加到主后请不要使用DRF之类的首字母缩略词。你是说Django restframework@Swift,并不想含糊其辞。我编辑了我的帖子:-)如果你想做得更好,你也应该给他发送链接到文档页面上的锚:)
    @api_view(['GET'])  # Decorator
    def call_model(request):
        #if request.method == 'GET':
    
                # sentence is the query we want to get the prediction for
        params =  request.GET.get('image_loc')
    
                # predict method used to get the prediction
        resp = prediction(image_loc = params)
    
                # returning JSON response
        return Response(resp) 
    
    http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
    
    TypeError at /model/img
    <HttpResponse status_code=200, "image/png"> is not JSON serializable
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
    Django Version: 2.2.12
    Exception Type: TypeError
    Exception Value:    
    <HttpResponse status_code=200, "image/png"> is not JSON serializable
    Exception Location: C:\Anaconda3\envs\tf35\lib\json\encoder.py in default, line 179
    Python Executable:  C:\Anaconda3\envs\tf35\python.exe
    Python Version: 3.5.5
    Python Path:    
    ['D:\\Discern\\Term 3\\deploy',
     'C:\\Anaconda3\\envs\\tf35\\python35.zip',
     'C:\\Anaconda3\\envs\\tf35\\DLLs',
     'C:\\Anaconda3\\envs\\tf35\\lib',
     'C:\\Anaconda3\\envs\\tf35',
     'C:\\Users\\prade\\AppData\\Roaming\\Python\\Python35\\site-packages',
     'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages',
     'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32',
     'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32\\lib',
     'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\Pythonwin']
    Server time:    Fri, 29 May 2020 04:35:18 +0000