Ayanzadeh93 commited on
Commit
8ba32f4
·
verified ·
1 Parent(s): 2e5f1ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -24
app.py CHANGED
@@ -3,15 +3,14 @@ from ultralytics import YOLOWorld
3
  from PIL import Image
4
  import cv2
5
  import pandas as pd
6
- import numpy as np
7
- import io
8
 
9
  # --- Load model ---
10
  def load_model():
11
  last_err = None
12
  for name in ["yolov8s-worldv2.pt", "yolov8s-world.pt"]:
13
  try:
14
- m = YOLOWorld(name) # downloads on first run
15
  return m
16
  except Exception as e:
17
  last_err = e
@@ -20,7 +19,7 @@ def load_model():
20
 
21
  model = load_model()
22
 
23
- # --- Preprocess image ---
24
  def preprocess(img: Image.Image, max_side=960, do_resize=True):
25
  img = img.convert("RGB")
26
  if do_resize:
@@ -29,7 +28,7 @@ def preprocess(img: Image.Image, max_side=960, do_resize=True):
29
  img.thumbnail((max_side, max_side), Image.LANCZOS)
30
  return img
31
 
32
- # --- Inference function ---
33
  def infer(image, prompts, conf, iou, resize):
34
  image = preprocess(image, do_resize=resize)
35
  classes = [c.strip() for c in prompts.split(",") if c.strip()]
@@ -40,33 +39,25 @@ def infer(image, prompts, conf, iou, resize):
40
  results = model(image, conf=conf, iou=iou)[0]
41
 
42
  # Annotated image
43
- plotted = results.plot() # np.ndarray in BGR
44
- plotted = cv2.cvtColor(plotted, cv2.COLOR_BGR2RGB) # convert to RGB
45
  annotated_img = Image.fromarray(plotted)
46
 
47
- # Results table
48
  data = []
49
  for box, cls, conf in zip(results.boxes.xyxy, results.boxes.cls, results.boxes.conf):
50
  x1, y1, x2, y2 = [int(v) for v in box.tolist()]
51
- data.append({
52
- "Class": model.names[int(cls)],
53
- "Confidence": round(float(conf), 3),
54
- "BBox": f"({x1}, {y1}, {x2}, {y2})"
55
- })
56
- df = pd.DataFrame(data)
57
 
58
- # Convert annotated image to downloadable file
59
- buf = io.BytesIO()
60
- annotated_img.save(buf, format="PNG")
61
- buf.seek(0)
62
 
63
- return annotated_img, df, buf
64
 
65
- # --- Gradio interface ---
66
  with gr.Blocks() as demo:
67
- gr.Markdown("# 🦉 YOLO-World Demo (Open-Vocabulary Detection on CPU)")
68
- gr.Markdown("Upload an image, type objects you want to detect, and see results!")
69
-
70
  with gr.Row():
71
  with gr.Column():
72
  image_in = gr.Image(type="pil", label="Upload Image")
@@ -78,7 +69,7 @@ with gr.Blocks() as demo:
78
 
79
  with gr.Column():
80
  img_out = gr.Image(label="Detections")
81
- table_out = gr.Dataframe(headers=["Class", "Confidence", "BBox"], label="Results Table")
82
  file_out = gr.File(label="Download Annotated Image")
83
 
84
  run_btn.click(
 
3
  from PIL import Image
4
  import cv2
5
  import pandas as pd
6
+ import tempfile, os
 
7
 
8
  # --- Load model ---
9
  def load_model():
10
  last_err = None
11
  for name in ["yolov8s-worldv2.pt", "yolov8s-world.pt"]:
12
  try:
13
+ m = YOLOWorld(name)
14
  return m
15
  except Exception as e:
16
  last_err = e
 
19
 
20
  model = load_model()
21
 
22
+ # --- Preprocess ---
23
  def preprocess(img: Image.Image, max_side=960, do_resize=True):
24
  img = img.convert("RGB")
25
  if do_resize:
 
28
  img.thumbnail((max_side, max_side), Image.LANCZOS)
29
  return img
30
 
31
+ # --- Inference ---
32
  def infer(image, prompts, conf, iou, resize):
33
  image = preprocess(image, do_resize=resize)
34
  classes = [c.strip() for c in prompts.split(",") if c.strip()]
 
39
  results = model(image, conf=conf, iou=iou)[0]
40
 
41
  # Annotated image
42
+ plotted = results.plot()
43
+ plotted = cv2.cvtColor(plotted, cv2.COLOR_BGR2RGB)
44
  annotated_img = Image.fromarray(plotted)
45
 
46
+ # Results table (as list of rows)
47
  data = []
48
  for box, cls, conf in zip(results.boxes.xyxy, results.boxes.cls, results.boxes.conf):
49
  x1, y1, x2, y2 = [int(v) for v in box.tolist()]
50
+ data.append([model.names[int(cls)], round(float(conf), 3), f"({x1}, {y1}, {x2}, {y2})"])
 
 
 
 
 
51
 
52
+ # Save annotated image to temp file for download
53
+ tmp_path = os.path.join(tempfile.gettempdir(), "annotated.png")
54
+ annotated_img.save(tmp_path)
 
55
 
56
+ return annotated_img, data, tmp_path
57
 
58
+ # --- Gradio UI ---
59
  with gr.Blocks() as demo:
60
+ gr.Markdown("# 🦉 YOLO-World Demo (CPU • Open-Vocab)")
 
 
61
  with gr.Row():
62
  with gr.Column():
63
  image_in = gr.Image(type="pil", label="Upload Image")
 
69
 
70
  with gr.Column():
71
  img_out = gr.Image(label="Detections")
72
+ table_out = gr.Dataframe(headers=["Class","Confidence","BBox"], datatype=["str","number","str"])
73
  file_out = gr.File(label="Download Annotated Image")
74
 
75
  run_btn.click(