SyedNaseem commited on
Commit
372827b
·
verified ·
1 Parent(s): dd13258

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import gradio as gr
3
+ import numpy as np
4
+ import cv2
5
+
6
+ # Load the trained model
7
+ model = YOLO('/content/drive/MyDrive/MS-Thesis/Multi-Class Classification/runs/classify/train4/weights/best.pt') # Replace with the path to your trained model
8
+
9
+ # Prediction function
10
+ def predict_image(image):
11
+ try:
12
+ # Convert the input image to the format expected by the model
13
+ image = np.array(image)
14
+ image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
15
+
16
+ # Make prediction
17
+ results = model.predict(image_bgr)
18
+
19
+ # Get the predicted class and confidence using the correct attributes
20
+ predicted_class = results[0].names[results[0].probs.top1]
21
+ confidence = results[0].probs.top1conf
22
+
23
+ # Annotate image with predicted class and confidence
24
+ annotated_image = image.copy()
25
+ cv2.putText(annotated_image, f"{predicted_class}: {confidence:.2f}",
26
+ (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)
27
+
28
+ # Convert the annotated image back to RGB for display
29
+ annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
30
+
31
+ return annotated_image_rgb, f"Predicted: {predicted_class} with {confidence:.2f} confidence"
32
+
33
+ except Exception as e:
34
+ # Return an error message if something goes wrong
35
+ return None, f"Error: {str(e)}"
36
+
37
+ # Define the Gradio interface
38
+ interface = gr.Interface(
39
+ fn=predict_image,
40
+ inputs=gr.Image(label="Upload an Image"),
41
+ outputs=[gr.Image(label="Annotated Image"), gr.Text(label="Prediction")],
42
+ title="Fruit Freshness Classifier",
43
+ description="Upload an image of a fruit, and the model will predict whether it is Fresh, Mild, or Rotten, and display the result on the image."
44
+ )
45
+
46
+ # Launch the interface
47
+ interface.launch()