简体   繁体   English

无法在使用 flask web 服务制作的站点中提交图像文件

[英]Can't submit image file in site made with flask web services

<!DOCTYPE html>
<html>
<head>
    <title>dog or cat huh</title>
    <style>
        *{
            font-size: :30px;
        }
    </style>
</head>
<body>

    <input id='input_image', type='file'/>
    <button id='submit_button'>Submit</button>
    <p style='font-weight: bold'>Predicions</p>
    <p>Dog <span id='Dog_prediction'></span></p>
    <p>Cat <span id='Cat_prediction'></span></p>
    <img id='selected_image' src=''/>

    <script href="http://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
        let base64Image;
        $('#input_image').change(function(){
            let reader = new FileReader();
            reader.onload = function(e){
                let dataUrl = reader.result;
                $('#selected_image').attr('src', dataUrl);
                base64Image = dataUrl.replace("data:image/png;base64","")
            }
            reader.readAsDataURL($('#input_image')[0].files[0])
            $("#Dog_prediction").text("");
            $("#Cat_prediction").text("");
        });

        $('#submit_button').click(function(event){
            let message={
                image: base64Image
            }
            console.log(message);
            $.post('http://192.168.1.106:5000/predict', JSON.stringify(message), function(response){
                $("#Dog_prediction").text(response.prediction.dog.toFixed(6));
                $("#Cat_prediction").text(response.prediction.cat.toFixed(6));
                console.log(response);
            })
        });

    </script>
</body>
</html>

import base64
import numpy as np
import keras
from keras import backend as k
import io
from PIL import Image
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.models import Sequential
from keras.models import load_model
from flask import Flask
from flask import request
from flask import jsonify
from flask import render_template

app = Flask(__name__)

def get_model():
    global model
    model = load_model('VGG_cats_and_dogs.h5')
    print('Model loaded!')

def preprocess(image, image_size):
    if image.mode != 'RGB':
        image = image.convert('RGB')
    image = image.resize(target_size)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    return image

get_model()
print('Model is loading.........')

@app.route('/predict', methods=["GET","POST"])
def predict():
    if request.method=='POST':
        message = request.get_json(force=True)
        encoded = message['image']
        decoded = base64.b64code(encoded)
        image = Image.open(io.BytesIO(encoded))
        processed_image = preprocess(image, target_size=(224, 224))

        prediction = model.predict(image).toList()
        response = {
                'predictions':{
                    'dog': prediction[0][0],
                    'cat': prediction[0][1]
                }
        }
        return jsonify(response)
    else:
        return render_template("predict.html")

if __name__ == "__main__":
    app.run(debug=True)

I'm trying to create a web application using flask to classify images using VGG16.我正在尝试使用 flask 创建一个 web 应用程序,以使用 VGG16 对图像进行分类。 The website loads fine I can select the file but can't submit the image.该网站加载正常我可以 select 文件但无法提交图像。 After clicking the submit button, nothing happens.单击提交按钮后,没有任何反应。 In the original tutorial GET was not added in methods but without it my website wouldn't load so I had to add the if else statement for POST and GET which loaded the website.在原始教程中,方法中没有添加 GET,但没有它,我的网站将无法加载,因此我必须为加载网站的 POST 和 GET 添加 if else 语句。 Anyone?任何人? 页面图片

Your javascript is failing, check the developer console of your browser.您的 javascript 失败,请检查浏览器的开发者控制台。

Uncaught ReferenceError: $ is not defined
    at predict:23

You weren't loading jQuery properly.您没有正确加载 jQuery 。

You need to do this:你需要这样做:

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>

not this:不是这个:

<script href="http://code.jquery.com/jquery-3.3.1.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM