Aumkeshchy2003 commited on
Commit
6de980c
·
verified ·
1 Parent(s): 3ae993d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -50
app.py CHANGED
@@ -1,53 +1,35 @@
1
  import cv2
2
  import torch
3
- import gradio as gr
4
  from ultralytics import YOLO
5
- import numpy as np
6
-
7
- # Load YOLOv5 model (assuming weights are already downloaded)
8
- model = YOLO("yolov5s.pt") # You can change to 'yolov5m.pt' or 'yolov5l.pt' for better accuracy
9
-
10
- def detect_objects_image(image):
11
- results = model(image)
12
- result_img = results[0].plot() # Render image with bounding boxes
13
- return result_img
14
-
15
- # Video detection function
16
- def detect_objects_video():
17
- cap = cv2.VideoCapture(0) # Capture from default webcam
18
- cap.set(cv2.CAP_PROP_FPS, 30) # Set FPS
19
-
20
- while cap.isOpened():
21
- ret, frame = cap.read()
22
- if not ret:
23
- break
24
-
25
- results = model(frame)
26
- result_img = results[0].plot()
27
-
28
- _, buffer = cv2.imencode(".jpg", result_img)
29
- yield buffer.tobytes()
30
-
31
- cap.release()
32
-
33
- def start_video():
34
- return gr.Video(update=detect_objects_video, streaming=True)
35
-
36
- # Gradio UI
37
- with gr.Blocks() as demo:
38
- gr.Markdown("## Live Object Detection with YOLOv5")
39
-
40
- with gr.Row():
41
- img_input = gr.Image(type="numpy")
42
- img_output = gr.Image()
43
- img_button = gr.Button("Detect Objects in Image")
44
-
45
- img_button.click(detect_objects_image, inputs=img_input, outputs=img_output)
46
-
47
- with gr.Row():
48
- video_button = gr.Button("Start Live Video Detection")
49
- video_output = gr.Video()
50
-
51
- video_button.click(start_video, outputs=video_output)
52
-
53
- demo.launch()
 
1
  import cv2
2
  import torch
 
3
  from ultralytics import YOLO
4
+
5
+ # Load YOLOv5 model with GPU support if available
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
7
+ model = YOLO("yolov5s.pt").to(device) # You can use yolov5m.pt for better accuracy
8
+
9
+ # Initialize video capture (Webcam)
10
+ cap = cv2.VideoCapture(0)
11
+ cap.set(cv2.CAP_PROP_FPS, 30) # Ensure 30+ FPS
12
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Set width
13
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # Set height
14
+
15
+ while cap.isOpened():
16
+ ret, frame = cap.read()
17
+ if not ret:
18
+ break
19
+
20
+ # Perform object detection
21
+ results = model(frame)
22
+
23
+ # Plot the results (draw bounding boxes)
24
+ result_img = results[0].plot()
25
+
26
+ # Display the output in a window
27
+ cv2.imshow("YOLOv5 Live Object Detection", result_img)
28
+
29
+ # Break loop with 'q' key
30
+ if cv2.waitKey(1) & 0xFF == ord("q"):
31
+ break
32
+
33
+ # Release resources
34
+ cap.release()
35
+ cv2.destroyAllWindows()