Preyanshz commited on
Commit
a300f83
·
verified ·
1 Parent(s): b0fdc1a

Update app.py

Browse files

added image url in inference tool

Files changed (1) hide show
  1. app.py +49 -14
app.py CHANGED
@@ -5,6 +5,9 @@ import numpy as np
5
  import time
6
  from PIL import Image
7
  from ultralytics import YOLO
 
 
 
8
 
9
  def save_uploaded_file(uploaded_file):
10
  """Save an uploaded file to a temporary file and return its path."""
@@ -13,19 +16,41 @@ def save_uploaded_file(uploaded_file):
13
  return tmp_file.name
14
 
15
  def yolo_inference_tool():
16
- """
17
- Single-model, single-image inference subpage (example).
18
- """
19
  st.header("YOLO Model Inference Tool")
20
- st.write("Upload one or more images and a YOLO model (.pt) file to run inference and view detailed results.")
 
 
 
21
 
22
  # Allow multiple images upload
23
- images = st.file_uploader("Upload Images", type=["jpg", "jpeg", "png"], key="inference_images", accept_multiple_files=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  model_file = st.file_uploader("Upload YOLO model (.pt)", type=["pt"], key="inference_model")
25
 
26
  if st.button("Submit (Single-Model Inference)"):
27
  if not images or not model_file:
28
- st.error("Please upload at least one image and a model.")
29
  return
30
 
31
  # Save and load the model file
@@ -60,25 +85,34 @@ def yolo_inference_tool():
60
  try:
61
  pil_img = Image.open(img_file).convert("RGB")
62
  except Exception as e:
63
- st.error(f"Error reading image {img_file.name}: {e}")
64
  continue
65
 
66
  try:
67
  result = model(np.array(pil_img))
68
  except Exception as e:
69
- st.error(f"Inference error on image {img_file.name}: {e}")
70
  continue
71
 
72
  r = result[0]
73
- image_results[img_file.name] = r
74
 
75
- # Collect basic metrics if available (e.g., inference time and detections)
76
  inference_time = r.speed.get('inference', None) if isinstance(r.speed, dict) else None
77
- detection_count = len(r.boxes) if r.boxes is not None else 0
 
 
 
 
 
 
 
 
78
  metrics.append({
79
- "Image": img_file.name,
80
  "Inference Time (ms)": inference_time if inference_time is not None else "N/A",
81
- "Detections": detection_count
 
82
  })
83
 
84
  eta_placeholder.empty()
@@ -89,7 +123,7 @@ def yolo_inference_tool():
89
  df_metrics = pd.DataFrame(metrics)
90
  st.dataframe(df_metrics, use_container_width=True)
91
 
92
- # Display annotated images (using pil=True to ensure RGB output)
93
  st.subheader("Annotated Images")
94
  for img_name, r in image_results.items():
95
  try:
@@ -98,6 +132,7 @@ def yolo_inference_tool():
98
  except Exception as e:
99
  st.error(f"Error generating annotated image for {img_name}: {e}")
100
 
 
101
  def yolo_model_comparison_tool():
102
  """
103
  Multi-model, multi-image comparison subpage,
 
5
  import time
6
  from PIL import Image
7
  from ultralytics import YOLO
8
+ import requests
9
+ from io import BytesIO
10
+
11
 
12
  def save_uploaded_file(uploaded_file):
13
  """Save an uploaded file to a temporary file and return its path."""
 
16
  return tmp_file.name
17
 
18
  def yolo_inference_tool():
 
 
 
19
  st.header("YOLO Model Inference Tool")
20
+ st.write(
21
+ "Upload one or more images and a YOLO model (.pt) file to run inference and view detailed results. "
22
+ "You can either upload images or provide an image URL."
23
+ )
24
 
25
  # Allow multiple images upload
26
+ uploaded_files = st.file_uploader(
27
+ "Upload Images", type=["jpg", "jpeg", "png"], key="inference_images", accept_multiple_files=True
28
+ )
29
+ # Text input for a single image URL (you could expand this to multiple URLs if needed)
30
+ url_input = st.text_input("Enter image URL (optional)", key="inference_url")
31
+
32
+ # Combine uploaded files and URL image into a single list
33
+ images = []
34
+ if uploaded_files:
35
+ images.extend(uploaded_files)
36
+ if url_input and url_input.strip():
37
+ try:
38
+ response = requests.get(url_input)
39
+ if response.status_code == 200:
40
+ image_bytes = BytesIO(response.content)
41
+ # Assign a name attribute for consistency
42
+ image_bytes.name = url_input
43
+ images.append(image_bytes)
44
+ else:
45
+ st.error("Failed to fetch image from URL.")
46
+ except Exception as e:
47
+ st.error(f"Error fetching image from URL: {e}")
48
+
49
  model_file = st.file_uploader("Upload YOLO model (.pt)", type=["pt"], key="inference_model")
50
 
51
  if st.button("Submit (Single-Model Inference)"):
52
  if not images or not model_file:
53
+ st.error("Please upload at least one image (or provide an image URL) and a model.")
54
  return
55
 
56
  # Save and load the model file
 
85
  try:
86
  pil_img = Image.open(img_file).convert("RGB")
87
  except Exception as e:
88
+ st.error(f"Error reading image {getattr(img_file, 'name', 'Unknown')}: {e}")
89
  continue
90
 
91
  try:
92
  result = model(np.array(pil_img))
93
  except Exception as e:
94
+ st.error(f"Inference error on image {getattr(img_file, 'name', 'Unknown')}: {e}")
95
  continue
96
 
97
  r = result[0]
98
+ image_results[getattr(img_file, 'name', 'Unknown')] = r
99
 
100
+ # Get inference time from r.speed, if available
101
  inference_time = r.speed.get('inference', None) if isinstance(r.speed, dict) else None
102
+ # Compute detection count and average confidence if detections exist
103
+ if r.boxes is not None and len(r.boxes) > 0:
104
+ detection_count = len(r.boxes)
105
+ confs = r.boxes.conf.cpu().numpy() if hasattr(r.boxes.conf, "cpu") else r.boxes.conf
106
+ avg_conf = float(np.mean(confs))
107
+ else:
108
+ detection_count = 0
109
+ avg_conf = 0.0
110
+
111
  metrics.append({
112
+ "Image": getattr(img_file, 'name', 'Unknown'),
113
  "Inference Time (ms)": inference_time if inference_time is not None else "N/A",
114
+ "Detections": detection_count,
115
+ "Average Confidence": f"{avg_conf:.2f}"
116
  })
117
 
118
  eta_placeholder.empty()
 
123
  df_metrics = pd.DataFrame(metrics)
124
  st.dataframe(df_metrics, use_container_width=True)
125
 
126
+ # Display annotated images using pil=True (ensuring RGB)
127
  st.subheader("Annotated Images")
128
  for img_name, r in image_results.items():
129
  try:
 
132
  except Exception as e:
133
  st.error(f"Error generating annotated image for {img_name}: {e}")
134
 
135
+
136
  def yolo_model_comparison_tool():
137
  """
138
  Multi-model, multi-image comparison subpage,