hailo device reset

We’re trying to get object recognition through our code. The device in use is a raspberry pi 5 and a hailo accelerator, and the conversion has been completed up to the hef file, and now an error occurs in the part of continuously initializing the device in executing the code. I would like to ask if you can modify the code in this part. I’m working on a college student project and it’s really important, so I’d appreciate it if you could help

our code

import cv2
import numpy as np
from gpiozero import PWMLED
from time import sleep
import hailort as hp

.hef 파일 경로

hef_file_path = ‘/home/pi/yolov5/yolov5n_seg.hef’

Hailo 장치 초기화 및 모델 로드

try:
# Hailo 장치 초기화
print(“Hailo 장치 연결 중…”)
devices = hp.Device.get_devices() # 장치 목록 가져오기
if not devices:
raise Exception(“Hailo 장치를 찾을 수 없습니다.”)

device = devices[0]  # 첫 번째 장치 선택
print("Hailo 장치 초기화 성공")

# Hailo 모델 로드
print("Hailo 모델 로딩 중...")
network = device.load_network(hef_file_path)  # .hef 파일 로드
print("Hailo 모델 로드 성공")

except Exception as e:
print(f"장치 초기화 또는 모델 로드 실패: {e}")
exit()

웹캠 연결

cam = cv2.VideoCapture(0)

웹캠이 정상적으로 열리지 않으면 종료

if not cam.isOpened():
print(“웹캠을 열 수 없습니다.”)
exit()

부저 및 LED 설정

BUZZER_PIN = 17 # 부저 핀
LED_PIN = 27 # LED 핀

buzzer = PWMLED(BUZZER_PIN)
led = PWMLED(LED_PIN)

IoU(Intersection over Union) 계산 함수

def compute_iou(box1, box2):
x1, y1, x2, y2 = box1
x1_, y1_, x2_, y2_ = box2

# 교차 영역 계산
inter_x1 = max(x1, x1_)
inter_y1 = max(y1, y1_)
inter_x2 = min(x2, x2_)
inter_y2 = min(y2, y2_)

inter_area = max(0, inter_x2 - inter_x1) * max(0, inter_y2 - inter_y1)

# 각 박스의 면적 계산
box1_area = (x2 - x1) * (y2 - y1)
box2_area = (x2_ - x1_) * (y2_ - y1_)

# IoU 계산
iou = inter_area / float(box1_area + box2_area - inter_area)
return iou

추론 및 객체 감지

try:
while True:
ret, image = cam.read()

    if not ret:
        print("프레임을 읽을 수 없습니다.")
        break

    # 이미지를 Hailo 모델에 맞는 형태로 변환 (예시: 크기 조정 및 전처리)
    input_image = cv2.resize(image, (320, 320))  # 모델에 맞는 입력 크기 (예시: 320x320)
    input_image = np.transpose(input_image, (2, 0, 1))  # 채널 차원 변경 (HWC -> CHW)
    input_image = np.expand_dims(input_image, axis=0)  # 배치 차원 추가

    # 모델 추론 실행
    try:
        results = network.infer(input_image)  # Hailo에서 추론 실행
    except Exception as e:
        print(f"추론 오류: {e}")
        continue

    # 바운딩 박스 좌표 가져오기
    bboxes = results[0]  # 예시: 결과에서 바운딩 박스 가져오기 (결과 형식에 맞춰 변경 필요)

    # 위험 감지 여부 확인
    danger_detected = False
    for i in range(len(bboxes)):
        for j in range(i + 1, len(bboxes)):  # 서로 다른 박스 비교
            box1 = bboxes[i][:4]
            box2 = bboxes[j][:4]
            iou = compute_iou(box1, box2)

            if iou > 0.01:  # IoU 값이 0.01 이상이면 위험 감지
                danger_detected = True
                break

        if danger_detected:
            break

    # 결과 이미지 렌더링
    img_with_boxes = image.copy()

    # 위험 감지 시 경고
    if danger_detected:
        cv2.putText(img_with_boxes, "DANGER!!!!!!!", (50, 100), cv2.FONT_HERSHEY_SIMPLEX,
                    3, (0, 0, 255), 8, cv2.LINE_AA)  # 큰 글자로 표시
       
        # 🔊 부저 ON & LED ON (경고)
        print("🔊 부저 및 LED ON")
        buzzer.value = 0.5  # 50% 강도로 PWM 신호 출력
        led.value = 1  # LED 최대 밝기
        sleep(1)  # 1초 동안 유지
        buzzer.off()  # 부저 OFF
        led.off()  # LED OFF
        print("🔇 부저 및 LED OFF")

    # 결과 이미지 표시
    cv2.imshow('YOLOv5 Object Detection', img_with_boxes)

    # 'q' 키를 누르면 종료
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

finally:
# 종료 처리
cam.release()
cv2.destroyAllWindows()
buzzer.off() # 프로그램 종료 시 부저 OFF
led.off() # 프로그램 종료 시 LED OFF