csprojectworkspace commited on
Commit
bcdc54a
·
verified ·
1 Parent(s): 5ac9b3d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -8
app.py CHANGED
@@ -2,26 +2,48 @@ import gradio as gr
2
  from ultralytics import YOLO
3
  import numpy as np
4
  from PIL import Image
 
5
 
6
  # load model
7
  model = YOLO("best.pt")
8
 
9
  def predict(image):
10
  results = model(image)
11
-
12
  r = results[0]
13
-
14
- output_image = r.plot() # YOLO annotated image
15
-
16
- return Image.fromarray(output_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  demo = gr.Interface(
19
  fn=predict,
20
  inputs=gr.Image(type="pil"),
21
- outputs=gr.Image(type="pil"),
 
 
 
22
  title="YOLOv8 Detection",
23
  description="Upload an image and detect objects"
24
  )
25
 
26
- demo.launch()
27
- print(model.names)
 
2
  from ultralytics import YOLO
3
  import numpy as np
4
  from PIL import Image
5
+ import json
6
 
7
  # load model
8
  model = YOLO("best.pt")
9
 
10
  def predict(image):
11
  results = model(image)
 
12
  r = results[0]
13
+
14
+ # Get detection results
15
+ detections = []
16
+ if len(r.boxes) > 0:
17
+ for box in r.boxes:
18
+ class_id = int(box.cls[0])
19
+ class_name = model.names[class_id]
20
+ confidence = float(box.conf[0])
21
+ detections.append({
22
+ "class": class_name,
23
+ "confidence": round(confidence * 100, 2)
24
+ })
25
+
26
+ # Sort by confidence and get the top detection
27
+ if detections:
28
+ detections.sort(key=lambda x: x["confidence"], reverse=True)
29
+ top_detection = detections[0]
30
+ result_text = f"{top_detection['class']}: {top_detection['confidence']}%"
31
+ else:
32
+ result_text = "No detection"
33
+
34
+ # Return annotated image AND the detection text
35
+ output_image = r.plot()
36
+ return Image.fromarray(output_image), result_text
37
 
38
  demo = gr.Interface(
39
  fn=predict,
40
  inputs=gr.Image(type="pil"),
41
+ outputs=[
42
+ gr.Image(type="pil", label="Detection"),
43
+ gr.Textbox(label="Result")
44
+ ],
45
  title="YOLOv8 Detection",
46
  description="Upload an image and detect objects"
47
  )
48
 
49
+ demo.launch()