🚩필수 설치
git clone <https://github.com/ultralytics/yolov5>
cd yolov5
pip install -r requirements.txt
import torch
import cv2
import RPi.GPIO as GPIO
import time
from pathlib import Path
# ========== 라즈베리파이 GPIO 설정 ==========
MOTOR_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(MOTOR_PIN, GPIO.OUT)
def stop_car():
GPIO.output(MOTOR_PIN, GPIO.LOW)
def move_car():
GPIO.output(MOTOR_PIN, GPIO.HIGH)
# ========== 모델 불러오기 ==========
model_path = Path("best.pt") # 학습한 모델
model = torch.hub.load('ultralytics/yolov5', 'custom', path=model_path, force_reload=False)
model.conf = 0.5 # confidence threshold
model.iou = 0.45 # NMS threshold
# ========== 카메라 실행 ==========
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("❌ Camera not found.")
exit()
print("✅ Starting YOLO-based traffic light detection...")
try:
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame)
labels = results.pandas().xyxy[0]['name'].tolist()
if 'red' in labels:
print("🟥 RED DETECTED – STOP")
stop_car()
elif 'green' in labels:
print("🟩 GREEN DETECTED – GO")
move_car()
else:
print("⚪ No signal – STOP for safety")
stop_car()
# 디버깅용 시각화
annotated = results.render()[0]
cv2.imshow("Traffic Light Detection", annotated)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()
GPIO.cleanup()