Aumkeshchy2003 commited on
Commit
248b9ce
·
verified ·
1 Parent(s): e28f214

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -13
app.py CHANGED
@@ -3,13 +3,15 @@ import cv2
3
  import numpy as np
4
  import gradio as gr
5
  from PIL import Image
 
6
 
7
- # Load YOLOv5 model from Ultralytics' official repo
8
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
  model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device) # Load YOLOv5x model
10
 
11
- # Load COCO class labels
12
- CLASS_NAMES = model.names # YOLOv5's built-in class names
 
 
13
 
14
  def preprocess_image(image):
15
  image = Image.fromarray(image)
@@ -19,28 +21,27 @@ def preprocess_image(image):
19
  def detect_objects(image):
20
  image = preprocess_image(image)
21
 
22
- # Run inference using YOLOv5
23
  results = model(image)
24
 
25
- # Convert results to bounding box format
26
  image = np.array(image)
27
 
28
- for *box, conf, cls in results.xyxy[0]: # YOLOv5 format: [x1, y1, x2, y2, conf, class]
29
  x1, y1, x2, y2 = map(int, box)
30
- class_name = CLASS_NAMES[int(cls)] # Get class name
31
- confidence = conf.item() * 100 # Convert confidence to percentage
 
 
32
 
33
- # Draw a bolder bounding box
34
- cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 4) # Increased thickness
35
 
36
- # Larger text for class label
37
  label = f"{class_name} ({confidence:.1f}%)"
38
  cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
39
- 1, (0, 255, 0), 3, cv2.LINE_AA) # Larger text
40
 
41
  return image
42
 
43
- # Gradio UI with Submit button
44
  iface = gr.Interface(
45
  fn=detect_objects,
46
  inputs=gr.Image(type="numpy", label="Upload Image"),
 
3
  import numpy as np
4
  import gradio as gr
5
  from PIL import Image
6
+ import random
7
 
 
8
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
  model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device) # Load YOLOv5x model
10
 
11
+ CLASS_NAMES = model.names
12
+
13
+ random.seed(42)
14
+ CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
15
 
16
  def preprocess_image(image):
17
  image = Image.fromarray(image)
 
21
  def detect_objects(image):
22
  image = preprocess_image(image)
23
 
 
24
  results = model(image)
25
 
 
26
  image = np.array(image)
27
 
28
+ for *box, conf, cls in results.xyxy[0]:
29
  x1, y1, x2, y2 = map(int, box)
30
+ class_name = CLASS_NAMES[int(cls)]
31
+ confidence = conf.item() * 100
32
+
33
+ color = CLASS_COLORS[class_name]
34
 
35
+ cv2.rectangle(image, (x1, y1), (x2, y2), color, 4)
 
36
 
37
+
38
  label = f"{class_name} ({confidence:.1f}%)"
39
  cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
40
+ 1, color, 3, cv2.LINE_AA) # Larger text
41
 
42
  return image
43
 
44
+
45
  iface = gr.Interface(
46
  fn=detect_objects,
47
  inputs=gr.Image(type="numpy", label="Upload Image"),