-
Notifications
You must be signed in to change notification settings - Fork 1
/
object_detection.py
64 lines (47 loc) · 1.59 KB
/
object_detection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import torch
import cv2
import tkinter as tk
from PIL import Image, ImageTk
# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
# OpenCV capture for camera stream
cap = cv2.VideoCapture(0) # Change 0 to the camera index if you have multiple cameras
# Create Tkinter window
root = tk.Tk()
root.title("Object Detection with YOLOv5")
# Create a label to display the video stream
label = tk.Label(root)
label.pack()
def update():
ret, frame = cap.read()
if ret:
# Inference
results = model(frame)
# Draw bounding boxes on the frame
frame_with_boxes = results.render()[0]
# Convert OpenCV image to ImageTk format
img = cv2.cvtColor(frame_with_boxes, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
img_tk = ImageTk.PhotoImage(image=img)
count = 0
# Check detected objects for cell phone
for obj in results.xyxy[0]:
if int(obj[5]) == 67: # Class ID for cell phone is 67
print("Cell phone detected!")
if int(obj[5] == 0):
count += 1
if count == 0:
print("No person detected")
elif count > 1:
print("More than one person detected")
# Update label with the new image
label.img = img_tk
label.config(image=img_tk)
# Schedule the update function to be called after 10 milliseconds
root.after(4, update)
# Call the update function to start the video stream
update()
# Run the Tkinter event loop
root.mainloop()
# Release the capture when the Tkinter window is closed
cap.release()