yolov5 interface making problem html,css,js and flask

18 views Asked by At

this is my app.py code by flask

from flask import Flask, render_template, request, jsonify
import subprocess
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)

UPLOAD_FOLDER = 'tempimg'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
DETECTION_FOLDER = 'static'


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'jpg', 'jpeg', 'png', 'gif'}


def get_latest_folder():
    dirs = [d for d in os.listdir(DETECTION_FOLDER) if os.path.isdir(os.path.join(DETECTION_FOLDER, d))]
    if not dirs:
        return None

    sorted_dirs = sorted(dirs, reverse=True)
    latest_folder = sorted_dirs[0]
    print("latest= " + latest_folder)
    return latest_folder


def get_images_from_folder(folder):
    folder_path = os.path.join(DETECTION_FOLDER, folder)
    print("Folder Path:", folder_path)
    files_in_folder = os.listdir(folder_path)
    print("Files in Folder:", files_in_folder)
    images = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
    print("Filtered Images:", images)
    return images


def run_detection(image_path):
    command = [
        'python', './yolov5/predict-modifiy.py',
        '--weights', './yolov5/runs/train/exp/weights/best.pt',
        '--img', '640',
        '--conf', '0.1',
        '--source', image_path,
        '--save-txt',
        '--save-conf',
    ]

    try:
        result = subprocess.check_output(command, stderr=subprocess.STDOUT, text=True)
        latest_folder = get_latest_folder()
        folder_images = get_images_from_folder(latest_folder)
        return {'result': result, 'latest_folder': latest_folder, 'images': folder_images}
    except subprocess.CalledProcessError as e:
        return {'error': f'Error running YOLOv5 detection: {e.output}'}


@app.route('/')
def index():
    return render_template('index.html', images=[], latest_folder="No folders found")


@app.route('/detect_objects', methods=['POST'])
def detect_objects():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': 'No selected file'})

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        temp_image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(temp_image_path)

        detection_result = run_detection(temp_image_path)

        os.remove(temp_image_path)

        return render_template('index.html', **detection_result)

    else:
        return jsonify({'error': 'Invalid file format'})


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

this is index.html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>YOLOv5 Object Detection</title>
    <link
      rel="stylesheet"
      href="{{ url_for('static', filename='styles.css') }}"
    />
  </head>
  <body>
    <h1>YOLOv5 Object Detection</h1>

    <input type="file" id="fileInput" onchange="previewImage()" />
    <br />
    <img
      id="imagePreview"
      alt="Input Image Preview"
      style="max-width: 500px; margin-top: 10px; display: none"
    />
    <br />
    <button onclick="performInference()">Detect Objects</button>
    <div id="loader" style="display: none">Loading...</div>
    <div id="result">
      
    </div>
    
    <script>
      function previewImage() {
        var fileInput = document.getElementById("fileInput");
        var imagePreview = document.getElementById("imagePreview");
        if (fileInput.files && fileInput.files[0]) {
          var reader = new FileReader();
          reader.onload = function (e) {
            imagePreview.src = e.target.result;
            imagePreview.style.display = "block";
          };
          reader.readAsDataURL(fileInput.files[0]);
        }
      }

      function performInference() {
        var fileInput = document.getElementById("fileInput");
        var file = fileInput.files[0];

        var formData = new FormData();
        formData.append("file", file);

        // Show loader
        var loader = document.getElementById("loader");
        loader.style.display = "block";
        
        fetch("/detect_objects", {
            method: "POST",
            body: formData,
        })
        .then((response) => response.text())  // Change this line
        .then((data) => {
            loader.style.display = "none";

            // Parse the response as JSON
            var jsonData = JSON.parse(data);
            
            // Display the result path
            var resultContainer = document.getElementById("result");
            resultContainer.innerHTML = "<p>Detection Result saved at: " + jsonData.result + "</p>";

            // Display the latest folder
            resultContainer.innerHTML += "<p>Latest Detection Folder: " + jsonData.latest_folder + "</p>";

            // Display images from the latest detection run folder
            if (jsonData.images.length > 0) {
                resultContainer.innerHTML += "<p>Images from the latest detection run in folder '" + jsonData.latest_folder + "':</p>";

                jsonData.images.forEach((image) => {
                    var resultImage = new Image();
                    // Use the correct path to display the image
                    resultImage.src = '../static/' + jsonData.latest_folder + '/' + image;
                    resultImage.alt = image;
                    resultImage.style.maxWidth = "500px";
                    resultImage.style.marginTop = "10px";
                    resultContainer.appendChild(resultImage);
                });
            } else {
                resultContainer.innerHTML += "<p>No images found in the latest detection run folder.</p>";
            }
        })
        .catch((error) => {
            loader.style.display = "none";
            console.error("Error:", error);
        });
    }
    </script>
  </body>
</html>

i want to show image from latest_folder which i taken from app.py file based on latest createion time.but i will not show it..how can i solve it. my cmd show the result latest= exp9 Folder Path: static\exp9 Files in Folder: ['vitamin.jpg', 'vitamin_0.txt'] Filtered Images: ['vitamin.jpg'] 127.0.0.1 - - [05/Feb/2024 13:51:51] "POST /detect_objects HTTP/1.1" 200 - anyone solve it

i want to show image from latest_folder which i taken from app.py file based on latest createion time.but i will not show it..how can i solve it. my cmd show the result latest= exp9 Folder Path: static\exp9 Files in Folder: ['vitamin.jpg', 'vitamin_0.txt'] Filtered Images: ['vitamin.jpg'] 127.0.0.1 - - [05/Feb/2024 13:51:51] "POST /detect_objects HTTP/1.1" 200 - anyone solve it

i expect the latest_folder image will show in result div.

0

There are 0 answers