Aumkeshchy2003 commited on
Commit
8513c99
·
verified ·
1 Parent(s): b86c5b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -42
app.py CHANGED
@@ -3,54 +3,32 @@ import numpy as np
3
  import gradio as gr
4
  from PIL import Image
5
 
6
- # Device configuration
7
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
8
 
9
- # Load YOLOv5 model
10
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
11
 
12
- # Set model confidence threshold
13
- model.conf = 0.5
14
  if device.type == 'cuda':
15
  model.half()
16
 
17
- def process_frame(image):
18
- """Process a video frame or image and apply YOLOv5 object detection."""
19
- if image is None:
20
- return None
21
 
22
- try:
23
- image_pil = Image.fromarray(image)
24
- with torch.no_grad():
25
- results = model(image_pil)
26
-
27
- rendered_images = results.render()
28
- return np.array(rendered_images[0]) if rendered_images else image
29
 
30
- except Exception as e:
31
- print(f"Error processing frame: {e}")
32
- return image
33
-
34
- # Create Gradio UI
35
- with gr.Blocks(title="Real-Time Object Detection") as app:
36
- gr.Markdown("# Real-Time Object Detection")
37
-
38
- with gr.Tabs():
39
- # 📷 Live Webcam Tab
40
- with gr.TabItem("📷 Live Camera"):
41
- with gr.Row():
42
- webcam_input = gr.Video(label="Live Feed")
43
- live_output = gr.Image(label="Processed Feed")
44
-
45
- webcam_input.change(process_frame, inputs=webcam_input, outputs=live_output)
46
-
47
- # 🖼️ Image Upload Tab (With Submit Button)
48
- with gr.TabItem("🖼️ Image Upload"):
49
- with gr.Row():
50
- upload_input = gr.Image(type="numpy", label="Upload Image")
51
- submit_button = gr.Button("Submit")
52
- upload_output = gr.Image(label="Detection Result")
53
-
54
- submit_button.click(process_frame, inputs=upload_input, outputs=upload_output)
55
-
56
- app.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)
 
3
  import gradio as gr
4
  from PIL import Image
5
 
 
6
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
 
 
8
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
9
 
 
 
10
  if device.type == 'cuda':
11
  model.half()
12
 
13
+ def detect_objects(image):
14
+ image_pil = Image.fromarray(image)
 
 
15
 
16
+ with torch.no_grad():
17
+ results = model(image_pil)
 
 
 
 
 
18
 
19
+ rendered_images = results.render()
20
+
21
+ return np.array(rendered_images[0]) if rendered_images else image
22
+
23
+ # Gradio interface
24
+ iface = gr.Interface(
25
+ fn=detect_objects,
26
+ inputs=gr.Image(type="numpy", label="Upload Image"),
27
+ outputs=gr.Image(type="numpy", label="Detected Objects"),
28
+ title="Object Detection with YOLOv5",
29
+ description="Use webcam or upload an image to detect objects.",
30
+ allow_flagging="never",
31
+ examples=["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
32
+ )
33
+
34
+ iface.launch()