Description
Search before asking
- I have searched the YOLOv5 issues and discussions and found no similar questions.
Question
this is code :
import cv2
import math
import torch
import pygame
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
Initialize Pygame and Pygame Mixer
pygame.init()
pygame.mixer.init()
Sound = pygame.mixer.Sound(r"C:\Users\ITC\Downloads\mixkit-alert-alarm-1005.wav")
Initialize YOLOv5
device = select_device('')
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, force_reload=True)
model = attempt_load(r'C:\Users\ITC\Downloads\best.pt', map_location=device)
stride = int(model.stride.max()) # model stride
names = model.module.names if hasattr(model, 'module') else model.names
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
img = frame.copy()
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Inference
img = torch.from_numpy(img).to(device)
img = img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Predict
pred = model(img)[0]
pred = non_max_suppression(pred, 0.5, 0.4)
for i, det in enumerate(pred):
if len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
for *xyxy, conf, cls in reversed(det):
c = int(cls)
confidence = conf.item() * 100
if confidence > 50 and names[c] == 'person': # Change to 'human' if that's your class name
x1, y1, x2, y2 = [int(i) for i in xyxy]
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 5)
cv2.putText(frame, f'{names[c]} {confidence:.2f}%', (x1 + 8, y1 + 100), cv2.FONT_HERSHEY_SIMPLEX,
1, (255, 0, 0), 2)
# Add your Pygame sound logic here
pygame.mixer.Sound.play(Sound)
# You might need to add logic to stop sound when there's no detection
cv2.imshow("command", frame)
if cv2.waitKey(1) == ord('a'):
break
cap.release()
cv2.destroyAllWindows()
and this is the error in juputer
ModuleNotFoundError Traceback (most recent call last)
Cell In[7], line 5
3 import torch
4 import pygame
----> 5 from models.experimental import attempt_load
6 from utils.general import non_max_suppression, scale_coords
7 from utils.torch_utils import select_device
ModuleNotFoundError: No module named 'models'
Additional
No response