Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tensorflow.lite.python.interpreter import Interpreter
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Define paths to your model and label files
|
| 8 |
+
MODEL_PATH = "custom_model_lite/detect.tflite"
|
| 9 |
+
LABEL_PATH = "custom_model_lite/labelmap.txt"
|
| 10 |
+
|
| 11 |
+
# Function to load the TFLite model and labels
|
| 12 |
+
def load_model():
|
| 13 |
+
interpreter = Interpreter(model_path=MODEL_PATH)
|
| 14 |
+
interpreter.allocate_tensors()
|
| 15 |
+
input_details = interpreter.get_input_details()
|
| 16 |
+
output_details = interpreter.get_output_details()
|
| 17 |
+
height = input_details[0]['shape'][1]
|
| 18 |
+
width = input_details[0]['shape'][2]
|
| 19 |
+
|
| 20 |
+
with open(LABEL_PATH, 'r') as f:
|
| 21 |
+
labels = [line.strip() for line in f.readlines()]
|
| 22 |
+
|
| 23 |
+
print(f"Model loaded. Input shape: {input_details[0]['shape']}")
|
| 24 |
+
return interpreter, input_details, output_details, height, width, labels
|
| 25 |
+
|
| 26 |
+
# Function to preprocess the image for the model
|
| 27 |
+
def preprocess_image(image, input_details, height, width):
|
| 28 |
+
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 29 |
+
image_resized = cv2.resize(image_rgb, (width, height))
|
| 30 |
+
input_data = np.expand_dims(image_resized, axis=0)
|
| 31 |
+
|
| 32 |
+
if input_details[0]['dtype'] == np.float32:
|
| 33 |
+
input_data = (np.float32(input_data) - 127.5) / 127.5
|
| 34 |
+
|
| 35 |
+
print(f"Image preprocessed: shape {input_data.shape}, dtype {input_data.dtype}")
|
| 36 |
+
return input_data
|
| 37 |
+
|
| 38 |
+
# Function to perform object detection and draw bounding boxes
|
| 39 |
+
def detect_objects(image, interpreter, input_details, output_details, labels):
|
| 40 |
+
input_data = preprocess_image(image, input_details, height, width)
|
| 41 |
+
interpreter.set_tensor(input_details[0]['index'], input_data)
|
| 42 |
+
interpreter.invoke()
|
| 43 |
+
|
| 44 |
+
boxes = interpreter.get_tensor(output_details[1]['index'])[0] # bounding box coordinates
|
| 45 |
+
classes = interpreter.get_tensor(output_details[3]['index'])[0] # class index
|
| 46 |
+
scores = interpreter.get_tensor(output_details[0]['index'])[0] # confidence scores
|
| 47 |
+
|
| 48 |
+
print(f"Detections: {len(scores)} objects detected")
|
| 49 |
+
|
| 50 |
+
for i in range(len(scores)):
|
| 51 |
+
if scores[i] > 0.1: # confidence threshold
|
| 52 |
+
ymin, xmin, ymax, xmax = boxes[i]
|
| 53 |
+
ymin = int(max(1, ymin * image.shape[0]))
|
| 54 |
+
xmin = int(max(1, xmin * image.shape[1]))
|
| 55 |
+
ymax = int(min(image.shape[0], ymax * image.shape[0]))
|
| 56 |
+
xmax = int(min(image.shape[1], xmax * image.shape[1]))
|
| 57 |
+
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
|
| 58 |
+
label = f'{labels[int(classes[i])]}: {scores[i] * 100:.2f}%'
|
| 59 |
+
cv2.putText(image, label, (xmin, ymin - 10),
|
| 60 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
|
| 61 |
+
print(f"Object {i}: {label} at [{xmin}, {ymin}, {xmax}, {ymax}]")
|
| 62 |
+
|
| 63 |
+
return image
|
| 64 |
+
|
| 65 |
+
# Initialize the Flask app
|
| 66 |
+
app = Flask(__name__, static_folder='static')
|
| 67 |
+
|
| 68 |
+
# Load the TFLite model and labels
|
| 69 |
+
interpreter, input_details, output_details, height, width, labels = load_model()
|
| 70 |
+
|
| 71 |
+
@app.route('/', methods=['GET', 'POST'])
|
| 72 |
+
def upload_and_detect():
|
| 73 |
+
if request.method == 'POST':
|
| 74 |
+
if 'file' not in request.files:
|
| 75 |
+
print("No file part in the request")
|
| 76 |
+
return redirect(request.url)
|
| 77 |
+
file = request.files['file']
|
| 78 |
+
if file.filename == '':
|
| 79 |
+
print("No selected file")
|
| 80 |
+
return redirect(request.url)
|
| 81 |
+
|
| 82 |
+
# Read the image file
|
| 83 |
+
image = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
|
| 84 |
+
if image is None:
|
| 85 |
+
print("Failed to read image")
|
| 86 |
+
return redirect(request.url)
|
| 87 |
+
|
| 88 |
+
print(f"Image uploaded: {file.filename}, shape: {image.shape}")
|
| 89 |
+
|
| 90 |
+
# Perform object detection
|
| 91 |
+
processed_image = detect_objects(image, interpreter, input_details, output_details, labels)
|
| 92 |
+
|
| 93 |
+
# Ensure the static directory exists
|
| 94 |
+
if not os.path.exists(app.static_folder):
|
| 95 |
+
os.makedirs(app.static_folder)
|
| 96 |
+
|
| 97 |
+
# Save processed image
|
| 98 |
+
save_path = os.path.join(app.static_folder, 'detected.jpg')
|
| 99 |
+
cv2.imwrite(save_path, processed_image)
|
| 100 |
+
print(f"Processed image saved at: {save_path}")
|
| 101 |
+
|
| 102 |
+
# Send back the path to the processed image
|
| 103 |
+
return jsonify({'image_url': url_for('static', filename='detected.jpg')})
|
| 104 |
+
|
| 105 |
+
return render_template('upload.html')
|
| 106 |
+
|
| 107 |
+
if __name__ == '__main__':
|
| 108 |
+
app.run(host='0.0.0.0', port=8000)
|