Aumkeshchy2003 commited on
Commit
4fa263e
·
verified ·
1 Parent(s): f54253a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -35
app.py CHANGED
@@ -2,63 +2,59 @@ import torch
2
  import cv2
3
  import numpy as np
4
  import gradio as gr
 
5
  import random
6
 
7
  # Load YOLOv5 model
8
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
- model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device)
10
- model.eval()
11
 
12
- # Use half-precision if CUDA is available
13
- if device.type == 'cuda':
14
- model.half()
15
-
16
- # Get class names
17
  CLASS_NAMES = model.names
18
 
19
- # Assign random colors for each class
 
20
  CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
21
 
22
- def detect_objects(image):
23
- """Detect objects in an image using YOLOv5 with optimized inference speed."""
24
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Convert to BGR for OpenCV
25
- img_resized = cv2.resize(image, (640, 640)) # Resize for faster processing
26
- img_tensor = torch.from_numpy(img_resized).to(device).float() / 255.0 # Normalize
27
- img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0) # Convert to batch format
28
-
29
- if device.type == 'cuda':
30
- img_tensor = img_tensor.half() # Use half precision for speed
31
 
32
- # Run model inference
33
- with torch.no_grad():
34
- results = model(img_tensor)
35
-
36
- detections = results.xyxy[0].cpu().numpy()
37
 
38
- for x1, y1, x2, y2, conf, cls in detections:
39
- x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
40
- class_name = CLASS_NAMES[int(cls)]
41
- confidence = conf * 100
42
 
43
- color = CLASS_COLORS[class_name]
44
 
45
  # Draw bounding box
46
- cv2.rectangle(image, (x1, y1), (x2, y2), color, 3)
47
 
48
- # Label
49
  label = f"{class_name} ({confidence:.1f}%)"
50
- cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
 
 
 
51
 
52
- return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert back to RGB for Gradio
53
 
54
- # Gradio Interface
55
  iface = gr.Interface(
56
  fn=detect_objects,
57
  inputs=gr.Image(type="numpy", label="Upload Image"),
58
  outputs=gr.Image(type="numpy", label="Detected Objects"),
59
- title="Fast Object Detection with YOLOv5",
60
- description="Use webcam or upload an image for object detection results.",
61
- allow_flagging="never"
 
62
  )
63
 
64
  # Launch the app
 
2
  import cv2
3
  import numpy as np
4
  import gradio as gr
5
+ from PIL import Image
6
  import random
7
 
8
  # Load YOLOv5 model
9
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
10
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device)
 
11
 
12
+ # Get class names from the model
 
 
 
 
13
  CLASS_NAMES = model.names
14
 
15
+ # Generate consistent colors for each class
16
+ random.seed(42) # Fix the seed for consistent colors
17
  CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
18
 
19
+ def preprocess_image(image):
20
+ """Convert numpy image to PIL format for YOLOv5 processing."""
21
+ image = Image.fromarray(image)
22
+ image = image.convert("RGB")
23
+ return image
 
 
 
 
24
 
25
+ def detect_objects(image):
26
+ """Detect objects in the image and draw bounding boxes with consistent colors."""
27
+ image = preprocess_image(image)
28
+ results = model([image]) # YOLOv5 inference
29
+ image = np.array(image) # Convert PIL image back to numpy for OpenCV
30
 
31
+ for *box, conf, cls in results.xyxy[0]:
32
+ x1, y1, x2, y2 = map(int, box)
33
+ class_name = CLASS_NAMES[int(cls)]
34
+ confidence = conf.item() * 100
35
 
36
+ color = CLASS_COLORS[class_name] # Use pre-generated consistent color
37
 
38
  # Draw bounding box
39
+ cv2.rectangle(image, (x1, y1), (x2, y2), color, 4)
40
 
41
+ # Display class label with confidence score
42
  label = f"{class_name} ({confidence:.1f}%)"
43
+ cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
44
+ 1, color, 3, cv2.LINE_AA)
45
+
46
+ return image
47
 
 
48
 
49
+ # Create Gradio Interface
50
  iface = gr.Interface(
51
  fn=detect_objects,
52
  inputs=gr.Image(type="numpy", label="Upload Image"),
53
  outputs=gr.Image(type="numpy", label="Detected Objects"),
54
+ title="Object Detection with YOLOv5",
55
+ description="Use webcam or upload an image to detect objects.",
56
+ allow_flagging="never",
57
+ examples=["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
58
  )
59
 
60
  # Launch the app