Rezuwan commited on
Commit
58e5869
·
verified ·
1 Parent(s): a5c9fc5

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +54 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import torch
3
+ import cv2
4
+ import numpy as np
5
+ import gradio as gr
6
+ from PIL import Image
7
+
8
+ # Load YOLOv8 model
9
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
10
+ model = YOLO("yolov8x.pt") # Load a more powerful YOLOv8 model
11
+ model.to(device)
12
+ model.eval()
13
+
14
+ # Load COCO class labels
15
+ CLASS_NAMES = model.names # YOLO's built-in class names
16
+
17
+ def preprocess_image(image):
18
+ image = Image.fromarray(image)
19
+ image = image.convert("RGB")
20
+ return image
21
+
22
+ def detect_objects(image):
23
+ image = preprocess_image(image)
24
+ results = model.predict(image) # Run YOLO inference
25
+
26
+ # Convert results to bounding box format
27
+ image = np.array(image)
28
+ for result in results:
29
+ for box, cls, conf in zip(result.boxes.xyxy, result.boxes.cls, result.boxes.conf):
30
+ x1, y1, x2, y2 = map(int, box[:4])
31
+ class_name = CLASS_NAMES[int(cls)] # Get class name
32
+ confidence = conf.item() * 100 # Convert confidence to percentage
33
+
34
+ # Draw a bolder bounding box
35
+ cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 4) # Increased thickness
36
+
37
+ # Larger text for class label
38
+ label = f"{class_name} ({confidence:.1f}%)"
39
+ cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
40
+ 1, (0, 255, 0), 3, cv2.LINE_AA) # Larger text
41
+
42
+ return image
43
+
44
+ # Gradio UI with Submit button
45
+ iface = gr.Interface(
46
+ fn=detect_objects,
47
+ inputs=gr.Image(type="numpy", label="Upload Image"),
48
+ outputs=gr.Image(type="numpy", label="Detected Objects"),
49
+ title="Object Detection",
50
+ description="Use webcam or Upload an image to detect objects.",
51
+ allow_flagging="never" # Disables unwanted flags
52
+ )
53
+
54
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ultralytics
2
+ torch
3
+ torchvision
4
+ opencv-python
5
+ pillow
6
+ gradio