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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -25
app.py CHANGED
@@ -2,52 +2,64 @@ import torch
2
  import cv2
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
-
10
- # Use a smaller model for faster inference
11
- model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
12
  model.eval()
13
 
 
 
 
 
 
14
  CLASS_NAMES = model.names
15
- random.seed(42)
16
- CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
17
 
18
- def preprocess_image(image):
19
- image = Image.fromarray(image).convert("RGB").resize((640, 640))
20
- return image
21
 
22
  def detect_objects(image):
23
- image = preprocess_image(image)
 
 
 
 
24
 
25
- results = model([image]) # Batch processing for efficiency
 
26
 
27
- image = np.array(image)
28
-
29
- for *box, conf, cls in results.xyxy[0]:
30
- x1, y1, x2, y2 = map(int, box)
31
- class_name = CLASS_NAMES[int(cls)]
32
- confidence = conf.item() * 100
 
 
 
 
33
 
34
  color = CLASS_COLORS[class_name]
35
 
36
- cv2.rectangle(image, (x1, y1), (x2, y2), color, 4)
 
 
 
37
  label = f"{class_name} ({confidence:.1f}%)"
38
- cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
39
- 1, color, 3, cv2.LINE_AA)
40
 
41
- return image
42
 
 
43
  iface = gr.Interface(
44
  fn=detect_objects,
45
  inputs=gr.Image(type="numpy", label="Upload Image"),
46
  outputs=gr.Image(type="numpy", label="Detected Objects"),
47
- title="Object Detection with YOLOv5",
48
- description="Use webcam or upload an image to detect objects.",
49
- allow_flagging="never",
50
- examples=["examples/spring_street_after.jpg", "examples/pexels-hikaique-109919.jpg"]
51
  )
52
 
 
53
  iface.launch()
 
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
65
  iface.launch()