[Python] How to use images uploaded from a HTML web-page using Python Flask

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to create an image recogniton program and so far I have made the model and all of the actual AI aspect of things. However, when it came to implementing this into a website, I have been having lots of unexpected troubles when I'm trying to display a prediction on another web-page using Python Flask.

    For instance, whenever I click on upload after choosing my image, it just opens a new web-page with the directory of the image and project files where I can navigate the files/folders. It should just be a container with the prediction and some text.

    I am quite new to this style of programming so I'm not sure how to solve the bugs as of now, so any help would be greatly appreciated. I have linked a photo of the current project directory structure.

    [​IMG]

    Here is my Python Flask code

    @app.route('/')
    def index():
    return render_template('html/enter_p.html')

    @app.route('/upload', methods=['POST'])
    def upload_file():
    if 'file' not in request.files:
    return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
    return redirect(request.url)
    if file:
    # Save the file
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    file.save(file_path)
    # Redirect to the prediction page
    return redirect(url_for('predict', filename=file.filename))

    @app.route('/predict/<filename>')
    def predict(filename):
    # Load your model and make a prediction
    result = model.predict(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Replace with your prediction logic
    return render_template('results.html', prediction=result, filename=filename)

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



    Here is my results html code:

    <div class="container">
    <h1>Prediction Result: {{ prediction }}</h1>
    <img src="{{ url_for('static', filename='uploads/' + filename) }}" alt="Uploaded Mole Image" width="300px">
    <br>


    And if necessary, here is my upload form:

    <form action = "../static/uploads/" method = "post" enctype = "multipart/form-data">
    <input type = "file" name = "file" accept = "image/*" required>
    <button type = "submit">Upload</button>
    </form>

    Continue reading...

Compartilhe esta Página