Commit 5820db55 authored by Upendra-Ihalagedara's avatar Upendra-Ihalagedara

Merge branch 'feature/IT20224820/pest_detection' of...

Merge branch 'feature/IT20224820/pest_detection' of http://gitlab.sliit.lk/2023-113/2023-113 into feature/IT20224820/pest_detection
parents 7d5d2a37 070888f4
class_mapping = {
0: 'Ash weevil',
1: 'Blister Beetle',
2: 'Fruit fly',
3: 'Fruit sucking moth',
4: 'Helicoverpa',
5: 'Hellula Undalis',
6: 'Leaf Webber',
7: 'Leucinodes',
8: 'Mealy Bug',
9: 'Plutella',
10: 'Root Grubs',
11: 'Schizaphis graminum',
12: 'Uroleucon compositae',
13: 'pieris',
14: 'whitefly',
}
\ No newline at end of file
import io
import time
from flask import Flask, request, jsonify
from PIL import Image
import torch
from flask_cors import CORS
import requests
import base64
import numpy as np
app = Flask(__name__)
CORS(app)
CORS(app, resources={r"/*": {"origins": "*"}})
# Load your trained YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='./best.pt')
model.eval()
# Get the class names
class_names = model.names if hasattr(model, 'names') else model.module.names
@app.route('/detect', methods=['POST'])
def detect_objects():
image_file = request.files['image']
image = Image.open(image_file)
# Run inference using your trained model
start_time = time.time()
results = model(image)
end_time = time.time()
# Process the inference results
detections = results.pandas().xyxy[0] # Get the detections as a pandas DataFrame
# Extract the relevant information
image_shape = image.size # Get the shape of the input image
num_objects = len(detections) # Get the number of detected objects
inference_time = end_time - start_time # Calculate the inference time
# Extract class names and confidence scores
class_ids_detected = detections['class'].tolist()
confidence_scores = detections['confidence'].tolist()
# Draw bounding boxes on the image
annotated_image = results.show()
# Prepare the output response
response = {
'image_path': image_file.filename,
'image_shape': image_shape,
'num_objects': num_objects,
'inference_time': inference_time,
'detections': [{'class_name': class_names[class_id], 'confidence': confidence}
for class_id, confidence in zip(class_ids_detected, confidence_scores)],
'annotated_image': annotated_image
}
# Return the response as JSON
return jsonify(response)
@app.route('/link', methods=['POST'])
def detect_objects_link():
# Get the image URL from the request
image_url = request.json['image_url']
# Download the image from the URL
response = requests.get(image_url)
image = Image.open(io.BytesIO(response.content))
# Convert image to numpy array
image_np = np.array(image)
# Run inference using your trained model
results = model(image_np)
# Process the inference results
annotated_image = results.render()[0]
# Convert the annotated image to PIL Image
annotated_image_pil = Image.fromarray(annotated_image)
# Save the annotated image to a file
annotated_image_path = './save/annotated_image.jpg'
annotated_image_pil.save(annotated_image_path)
# Convert the annotated image to base64
with open(annotated_image_path, 'rb') as image_file:
base64_image = base64.b64encode(image_file.read()).decode('utf-8')
# Prepare the output response
response = {
'image_url': image_url,
'num_objects': len(results.pandas().xyxy[0]),
'detections': [{'class_name': class_names[class_id], 'confidence': confidence}
for class_id, confidence in zip(results.pandas().xyxy[0]['class'].tolist(),
results.pandas().xyxy[0]['confidence'].tolist())],
'annotated_image': base64_image
}
# Return the response as JSON
return jsonify(response)
if __name__ == '__main__':
app.run()
\ No newline at end of file
flask==2.3.2
torch==2.0.1
flask_cors==3.0.10
requests==2.30.0
numpy==1.24.3
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment