from ultralytics import YOLO
import RPi.GPIO as GPIO
import time
# LED pin number (BCM)
led = 12
# Set GPIO mode
GPIO.setmode(GPIO.BCM)
# Set up GPIO for LED
GPIO.setup(led, GPIO.OUT)
# Create YOLO object
model = YOLO("/home/esp/sharefolder/best.onnx")
while True:
class_names = [] # Clear class names list for each iteration
results = model.predict(source='0', show=True, imgsz=[320, 320])
for result in results:
clist = result.boxes.cls
print(clist)
cls = set()
print(cls)
for cno in clist:
cls.add(model.names[int(cno)])
print(cls)
# Add class names to list
class_names += list(cls)
print(class_names) # Print class names
if 'person' in class_names or 'vehicle' in class_names:
print("Detected person or vehicle, turning on LED...")
# Write code to turn on the LED
GPIO.output(led, GPIO.HIGH)
time.sleep(1)
GPIO.output(led, GPIO.LOW)
else:
print("No person or vehicle detected.")
time.sleep(1)
1/1: 0... Success ✅ (inf frames of shape 640x480 at 30.00 FPS)
WARNING ⚠️ stream/video/webcam/dir predict source will accumulate results in RAM unless `stream=True` is passed,
causing potential out-of-memory errors for large sources or long-running streams/videos.
Usage:
results = model(source=..., stream=True) # generator of Results objects
for r in results:
boxes = r.boxes # Boxes object for bbox outputs
masks = r.masks # Masks object for segment masks outputs
probs = r.probs # Class probabilities for classification outputs
0: 320x320 (no detections), 222.4ms
0: 320x320 1 vehicle, 322.7ms
0: 320x320 1 vehicle, 264.0ms
0: 320x320 1 person, 1 vehicle, 276.3ms
This is my code. It uses a webcam to perform real-time object detection, saves only the class names of the detected objects in the "results" variable, and activates the LED if the "person" and "vehicle" classes are both present in the "results" variable.
Although the real-time detection results are displayed well, the subsequent actions are not being executed.
while True:
class_names = [] # Clear class names list for each iteration
results = model.predict(source='0', show=True, imgsz=[320, 320])
for result in results:
clist = result.boxes.cls
print(clist)
cls = set()
print(cls)
for cno in clist:
cls.add(model.names[int(cno)])
print(cls)
# Add class names to list
class_names += list(cls)
print(class_names) # Print class names
I tried putting "class_names=[]" inside the while loop to reset it every time, and I also added a print statement to check the information of each variable during the code execution. However, nothing was printed.
The execution environment is Raspberry Pi 4B 4G.