Я пытаюсь развернуть мою модель ml, которая классифицирует изображения растений, но я получаю файл, который не найден, хотя его путь указан правильно - PullRequest
0 голосов
/ 28 апреля 2020

ошибка cmd error snip на картинке выше показана ошибка, с которой я сталкиваюсь в cmd

в каталоге файлов

templates
--->index.html   
uploads  
venv  
app.py  
cnn_model.pkl  
index.py  
main.py

app.py


    from flask import Flask

    UPLOAD_FOLDER = "/uploads"

    app = Flask(__name__)
    app.secret_key = "secret key"
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

index.py


    from flask import Flask, render_template, request, redirect, flash, url_for
    import main
    import urllib.request
    from app import app
    from werkzeug.utils import secure_filename
    from main import getPrediction
    import os


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


    @app.route('/', methods=['POST'])
    def submit_file():
        if request.method == 'POST':
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
            file = request.files['file']
            if file.filename == '':
                flash('No file selected for uploading')
                return redirect(request.url)
            if file:
                filename = secure_filename(file.filename)
                print(filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
                label = getPrediction(filename)
                flash(label)
                return redirect('/')


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

index. html


    <!doctype html>
    <title>Plant Classifier</title>
    <h2>Select a file to upload</h2>
    <p>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            Label: {{ messages[0] }}

          {% endif %}
        {% endwith %}
    </p>
    <form method="post" action="/" enctype="multipart/form-data">
        <dl>
        <p>
            <input type="file" name="file" autocomplete="off" required>
        </p>
        </dl>
        <p>
        <input type="submit" value="Submit">
        </p>
    </form>

main.py



    labels=['Pepper__bell___Bacterial_spot','Pepper__bell___healthy',
    'Potato___Early_blight','Potato___Late_blight','Potato___healthy',
    'Tomato_Bacterial_spot','Tomato_Early_blight','Tomato_Late_blight',
    'Tomato_Leaf_Mold','Tomato_Septoria_leaf_spot',
    'Tomato_Spider_mites_Two_spotted_spider_mite','Tomato__Target_Spot',
    'Tomato__Tomato_YellowLeaf__Curl_Virus','Tomato__Tomato_mosaic_virus',
    'Tomato_healthy']

    def convert_image_to_array(image_dir):
        try:
            image = cv2.imread(image_dir)
            if image is not None :
                image = cv2.resize(image, default_image_size)   
                return img_to_array(image)
            else :
                return np.array([])
        except Exception as e:
            print(f"Error : {e}")
            return None

    default_image_size = tuple((256, 256))


    def getPrediction(filename):
        file_object = 'cnn_model.pkl'
        model=pickle.load(open(filename, 'rb'))

        #model = pickle.load(file_object)
        #imgpath='/content/drive/My Drive/Final Project files/TEST.JPG'
        lb = preprocessing.LabelBinarizer()

        imar = convert_image_to_array(filename) 
        npimagelist = np.array([imar], dtype=np.float16)/225.0 
        PREDICTEDCLASSES2 = model.predict_classes(npimagelist) 
        num=np.asscalar(np.array([PREDICTEDCLASSES2]))
        return labels[num]

сначала я загружаю файл pi c через html, и этот загруженный файл передается в мой сохраненный файл cnn модель, которая будет использоваться для прогнозирования заболевания растений и будет отображаться в виде выходных данных.

https://medium.com/@arifulislam_ron / flask -web-application-to-классифицировать-image-using- vgg16-d9c46f29c4cd im ссылка на код сверху ссылка

1 Ответ

1 голос
/ 28 апреля 2020

Либо добавьте вот так:

import os

basedir = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(basedir, '/uploads')

или

UPLOAD_FOLDER = os.getcwd() + '/uploads'
...