Use yolov5s.pt weights, combined with opencv, to achieve real-time detection
1. Load the target detection model
- load model function
- Notice
torch.hub.load('./yolov5', 'custom',path='./yolov5/pretrained/yolov5s.pt', source='local')
2. Read the camera video and detect it in real time
1.open cv2 read camera video
- open cv2 reads the camera information and displays it
import cv2
cap = cv2.VideoCapture(0)
while True:
rec, frame = cap.read()
frame = cv2.flip(frame, 1)
cv2.imshow('demo', frame)
if cv2.waitKey(10) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
2. Read yolov5s.pt weight information
- View the official reading in github
3. Read yolov5s.pt weight information person class
results = self.yolo_detector(img_rgb)
pd = results.pandas().xyxy[0]
person_list = pd[pd['name'] == 'person'].to_numpy()
3. Class implementation refactoring code
import torch
import cv2
class yolo_demo:
def __init__(self):
self.yolo_detector = torch.hub.load('./yolov5', 'custom',
path='./yolov5/pretrained/yolov5s.pt',
source='local')
self.yolo_detector.conf = 0.5
def main(self):
cap = cv2.VideoCapture(0)
while True:
rec, frame = cap.read()
img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = self.yolo_detector(img_rgb)
pd = results.pandas().xyxy[0]
person_list = pd[pd['name'] == 'person'].to_numpy()
for person in person_list:
l, t, r, b = person[:4].astype('int')
cv2.rectangle(frame, (l, t), (r, b), (0, 255, 0), 4)
cv2.imshow('demo', frame)
if cv2.waitKey(10) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
plate_demo = yolo_demo()
plate_demo.main()
4. Display the results