Aumkeshchy2003 commited on
Commit
b5a364c
·
verified ·
1 Parent(s): ab96246

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -10
app.py CHANGED
@@ -2,49 +2,86 @@ import torch
2
  import numpy as np
3
  import gradio as gr
4
  from PIL import Image
 
5
 
 
6
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 
 
7
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
8
 
 
9
  model.conf = 0.5
10
  if device.type == 'cuda':
11
  model.half()
12
 
13
- def process_frame(image):
14
- if image is None:
15
- print("No image received!")
 
 
 
16
  return None
17
-
 
 
 
 
 
 
 
18
  try:
19
  print("Processing frame...")
20
- image_pil = Image.fromarray(image)
21
 
22
  with torch.no_grad():
23
  results = model(image_pil)
24
 
25
  rendered_images = results.render()
26
- processed_image = np.array(rendered_images[0]) if rendered_images else image
27
  print("Frame processed successfully!")
28
  return processed_image
29
 
30
  except Exception as e:
31
  print(f"Processing error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  return image
33
 
 
34
  with gr.Blocks(title="Real-Time Object Detection") as app:
35
  gr.Markdown("# Real-Time Object Detection with Dual Input")
36
-
37
  with gr.Tabs():
 
38
  with gr.TabItem("📷 Live Camera"):
39
  with gr.Row():
40
- webcam_input = gr.Image(source="webcam", streaming=True, label="Live Feed") # ✅ FIXED
41
  live_output = gr.Image(label="Processed Feed")
42
- webcam_input.stream(process_frame, inputs=webcam_input, outputs=live_output) # ✅ FIXED
43
 
 
44
  with gr.TabItem("🖼️ Image Upload"):
45
  with gr.Row():
46
  upload_input = gr.Image(type="numpy", label="Upload Image")
 
47
  upload_output = gr.Image(label="Detection Result")
48
- upload_input.change(process_frame, upload_input, upload_output)
 
49
 
50
  app.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)
 
2
  import numpy as np
3
  import gradio as gr
4
  from PIL import Image
5
+ import cv2
6
 
7
+ # Device configuration
8
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
+
10
+ # Load optimized YOLOv5s model
11
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
12
 
13
+ # Set model confidence threshold
14
  model.conf = 0.5
15
  if device.type == 'cuda':
16
  model.half()
17
 
18
+ def process_frame(video):
19
+ """Reads a frame from the webcam video stream and applies YOLOv5 detection."""
20
+ cap = cv2.VideoCapture(video) # Open the webcam stream
21
+
22
+ if not cap.isOpened():
23
+ print("Error: Could not open video stream.")
24
  return None
25
+
26
+ ret, frame = cap.read()
27
+ cap.release()
28
+
29
+ if not ret:
30
+ print("Error: Could not read frame.")
31
+ return None
32
+
33
  try:
34
  print("Processing frame...")
35
+ image_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
36
 
37
  with torch.no_grad():
38
  results = model(image_pil)
39
 
40
  rendered_images = results.render()
41
+ processed_image = np.array(rendered_images[0]) if rendered_images else frame
42
  print("Frame processed successfully!")
43
  return processed_image
44
 
45
  except Exception as e:
46
  print(f"Processing error: {e}")
47
+ return frame
48
+
49
+ def process_uploaded_image(image):
50
+ """Processes the uploaded image and applies YOLOv5 object detection."""
51
+ if image is None:
52
+ return None
53
+
54
+ try:
55
+ image_pil = Image.fromarray(image)
56
+ with torch.no_grad():
57
+ results = model(image_pil)
58
+
59
+ rendered_images = results.render()
60
+ return np.array(rendered_images[0]) if rendered_images else image
61
+
62
+ except Exception as e:
63
+ print(f"Error processing image: {e}")
64
  return image
65
 
66
+ # Create Gradio UI
67
  with gr.Blocks(title="Real-Time Object Detection") as app:
68
  gr.Markdown("# Real-Time Object Detection with Dual Input")
69
+
70
  with gr.Tabs():
71
+ # 📷 Live Webcam Tab
72
  with gr.TabItem("📷 Live Camera"):
73
  with gr.Row():
74
+ webcam_input = gr.Video(label="Live Feed")
75
  live_output = gr.Image(label="Processed Feed")
76
+ webcam_input.stream(process_frame, inputs=webcam_input, outputs=live_output)
77
 
78
+ # 🖼️ Image Upload Tab (With Submit Button)
79
  with gr.TabItem("🖼️ Image Upload"):
80
  with gr.Row():
81
  upload_input = gr.Image(type="numpy", label="Upload Image")
82
+ submit_button = gr.Button("Submit")
83
  upload_output = gr.Image(label="Detection Result")
84
+
85
+ submit_button.click(process_uploaded_image, inputs=upload_input, outputs=upload_output)
86
 
87
  app.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)