데보션앱 소개페이지 바로가기
로그인 선택

신고하기

CLOSE
신고사유 (대표 사유 1개)
상세내용 (선택)
0/200
  • 신고한 게시글은 더 이상 보이지 않습니다.
  • 이용약관과 운영정책에 따라 신고사유에 해당하는지 검토 후 조치됩니다.
  • 허위 신고인 경우, 신고자의 서비스 이용이 제한될 수 있으니 유의하시어 신중하게 신고해 주세요.
(이 회원이 작성한 모든 댓글과 커뮤니티 게시물이 보이지 않고, 알림도 오지 않습니다.)

미리보기

커뮤니티

      1,234

      badge 23.06.15

      글 등록

      카테고리를 선택해주세요.

      DEVOTEE를 활성화 시키면
      지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.

      버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.

      임시저장함에 저장되었습니다. 저장일시 : 2022.5.17 14:29:08

      임시저장함

      제목을 선택하시면 이어서 작성이 가능하며,
      최대 20건까지 저장합니다.
      컨텐츠 유형, 제목, 저장일시, 삭제로 이뤄진 임시저장 목록
      컨텐츠 유형 제목 저장일 삭제

      데보션 블로그 게재 요청

      CLOSE
      • *
      • *

      본인인증

      효율적인 데보션 서비스 이용 및
      고객님의 소중한 개인정보보호를 위해
      본인인증을 진행해주세요. 본인인증 미 진행 시 로그인이 제한됩니다.
      본인인증 실패

      본인인증 로그인에 실패하였습니다.
      회원이 아니시거나 본인인증 등록이
      완료되지 않은 사용자입니다.

      회원정보 연결

      EfficientDet-Lite0 모델을 활용한 실시간 객체 탐지 (Raspberry Pi 5)

      xipert 26.04.29
      1,897 2 1
      DEVOTEE 요약
      본 블로그는 TensorFlow Lite 모델을 Raspberry Pi 5에 활용한 실시간 객체 탐지 샘플 코드와 그 배경 기술을 소개합니다. TensorFlow Lite는 스마트폰, 라즈베리파이 등 엣지 디바이스를 위한 경량 딥러닝 프레임워크로, 제한된 자원에서 AI 모델을 효율적으로 실행합니다. 이는 온디바이스 AI를 구현하여 네트워크 의존성을 줄이고 실시간 처리, 프라이버시 보호, 저전력 환경에 최적화된 추론을 가능하게 하며, 양자화 등의 기술로 모델을 경량화하는 것이 특징입니다.
      DEVOTEE 추천 블로그

      안녕하세요.

      SK AX 의 송영목 입니다.


      TensorFlow Lite 모델로 경량화하여 Raspberry Pi 5 로 손쉽게 할 수 있는 객체 탐지 샘플 코드를 작성하였습니다.


      TensorFlow Lite는 Google에서 개발한 엣지 디바이스(Edge Device) 전용 경량 딥러닝 프레임워크입니다.

      스마트폰, 임베디드 시스템, 그리고 Raspberry Pi 5와 같은 소형 컴퓨팅 환경에서도 AI 모델을 효율적으로 실행할 수 있도록 설계되었습니다.


      기존의 TensorFlow가 서버나 GPU 기반 환경에서 높은 성능을 발휘하는 데 초점을 맞췄다면,

      TensorFlow Lite는 제한된 CPU, 메모리, 전력 환경에서도 빠르게 동작하도록 최적화된 것이 특징입니다.


      왜 요즘 TensorFlow Lite를 사용하는가?

      최근에는 AI가 클라우드가 아니라 디바이스 자체에서 동작하는 “온디바이스 AI(On-device AI)”가 중요한 트렌드가 되었습니다.

      TensorFlow Lite는 이러한 흐름에서 다음과 같은 이유로 널리 사용됩니다.

      • 네트워크 의존성 감소

        인터넷 없이도 로컬에서 바로 추론 가능 (지연 시간 ↓)

      • 실시간 처리 성능 향상

        영상 스트리밍, 객체 탐지 등에서 빠른 응답 가능

      • 프라이버시 보호

        데이터가 외부 서버로 전송되지 않음

      • 저전력 환경 최적화

        배터리 기반 장치(드론, IoT 센서 등)에 적합

      특히 Raspberry Pi 같은 환경에서는 클라우드보다 로컬 추론이 훨씬 실용적이기 때문에 TFLite가 많이 사용됩니다.


      장점과 단점

      • 장점

        . 경량화된 모델 구조 (양자화 등 지원)

        . 빠른 추론 속도 (CPU만으로도 실시간 처리 가능)

        . 다양한 플랫폼 지원 (Android, iOS, Linux, MCU 등)

        . 하드웨어 가속 지원 (GPU, Edge TPU 등)

      • 단점

        . 정확도 손실 가능성 (경량화/양자화 과정에서 발생)

        . 모델 변환 과정 필요 (TensorFlow → TFLite)

        . 복잡한 모델은 제한적 (대형 모델은 성능 저하)


      TensorFlow Lite (TFLite) 란?

      개요

      TensorFlow Lite는 Google이 개발한 엣지 디바이스(Edge Device) 전용 경량 딥러닝 프레임워크입니다.

      스마트폰, 라즈베리파이, 마이크로컨트롤러 등 연산 자원이 제한된 환경에서 AI 모델을 실행할 수 있도록 설계되었습니다.


      TensorFlow vs TensorFlow Lite 비교

      항목

      TensorFlow (일반)

      TensorFlow Lite

      주요 용도

      모델 학습 + 추론

      추론(Inference) 전용

      실행 환경

      PC, 서버, GPU

      모바일, 임베디드, IoT

      파일 형식

      SavedModel, HDF5

      .tflite (FlatBuffer)

      파일 크기

      수백 MB ~ GB

      수 MB 이하

      연산 속도

      빠름 (GPU 활용)

      최적화된 경량 연산

      메모리 사용

      많음

      매우 적음


      TFLite 동작 원리

      [학습 서버 / PC]                        [엣지 디바이스 / Raspberry Pi]
      ─────────────────────                   ──────────────────────────────
      TensorFlow 모델 학습                     .tflite 파일 로드
            ↓                                       ↓
      TFLite Converter로 변환          →     Interpreter 생성
            ↓                                       ↓
      .tflite 파일 생성                        allocate_tensors()
                                                    ↓
                                          입력 텐서에 데이터 주입
                                          set_tensor()
                                                    ↓
                                          추론 실행
                                          invoke()
                                                    ↓
                                          출력 텐서에서 결과 추출
                                          get_tensor()


      .tflite 파일 구조

      .tflite 파일은 FlatBuffer 포맷으로 저장된 이진 파일입니다.

      구성 요소

      설명

      모델 그래프

      연산(Op)들의 연결 구조

      가중치(Weights)

      학습된 파라미터 값

      텐서 정보

      입출력 shape, dtype

      메타데이터

      버전, 라벨 정보 등


      양자화 (Quantization)

      TFLite의 핵심 경량화 기법으로, 모델의 가중치와 연산을 낮은 정밀도로 변환합니다.

      방식

      데이터 타입

      파일 크기

      속도

      정확도

      원본 (Full Precision)

      float32 (32bit)

      기준

      기준

      기준

      동적 양자화

      int8 (8bit)

      약 1/4

      빠름

      약간 낮음

      전체 정수 양자화

      uint8 (8bit)

      약 1/4

      가장 빠름

      약간 낮음

      부동소수점 16bit

      float16 (16bit)

      약 1/2

      빠름

      거의 동일

      이 실습에서 사용하는 EfficientDet-Lite0 모델의 입력 타입이 uint8인 이유가 바로 전체 정수 양자화 적용 때문입니다.

      코드에서 input_dtype을 확인하여 uint8 / float32를 자동 분기하는 것도 이 때문입니다.


      TFLite Interpreter (인터프리터)

      코드에서 사용하는 핵심 객체로, 모델 실행의 전 과정을 담당합니다.

      # 1. 인터프리터 생성 및 메모리 할당
      interpreter = tf.lite.Interpreter(model_path=MODEL_PATH)
      interpreter.allocate_tensors()
      
      # 2. 입출력 텐서 정보 조회
      input_details  = interpreter.get_input_details()   # 입력 텐서 목록
      output_details = interpreter.get_output_details()  # 출력 텐서 목록
      
      # 3. 입력 데이터 주입
      interpreter.set_tensor(input_details[0]['index'], input_tensor)
      
      # 4. 추론 실행
      interpreter.invoke()
      
      # 5. 결과 추출
      boxes = interpreter.get_tensor(output_details[0]['index'])

      메서드

      역할

      Interpreter(model_path)

      .tflite 파일 로드

      allocate_tensors()

      입출력 텐서 메모리 할당 (한 번만 호출)

      get_input_details()

      입력 텐서의 index, shape, dtype 조회

      get_output_details()

      출력 텐서의 index, shape, dtype 조회

      set_tensor(index, data)

      입력 텐서에 데이터 주입

      invoke()

      실제 추론 실행

      get_tensor(index)

      출력 텐서에서 결과 읽기


      XNNPACK 가속

      Raspberry Pi에서 실행 시 아래 메시지가 출력됩니다:

      INFO: Created TensorFlow Lite XNNPACK delegate for CPU.

      XNNPACK은 ARM CPU(Raspberry Pi 포함)에서 부동소수점 연산을 최적화하는 가속 라이브러리입니다.

      자동으로 활성화되며, 추론 속도를 크게 향상시킵니다.


      지원 플랫폼

      플랫폼

      지원 여부

      Android

      O

      iOS

      O

      Raspberry Pi (Linux ARM)

      O

      Windows / macOS / Linux (x86)

      O

      Arduino / Microcontroller

      O (TFLite Micro)


      필요 파일

      파일

      설명

      test_tflite6.py

      메인 실행 스크립트

      lite-model_efficientdet_lite0_detection_default_1.tflite

      TFLite 객체 탐지 모델

      COCO2017_classes.txt

      COCO 91개 클래스 레이블 (쉼표 구분)


      환경 설정

      환경: Raspberry Pi 5 + PiCamera2목적: TFLite 모델을 이용한 실시간 객체 탐지 (Object Detection) 실습

      패키지 설치

      pip install picamera2 opencv-python tensorflow numpy

      하드웨어 요구사항

      • Raspberry Pi 5

      • PiCamera2 (CSI 카메라 모듈)


      실행 방법

      python test_tflite6.py

      종료 방법

      • 화면에서 q 키

      • 터미널에서 Ctrl+C


      설정값 (코드 상단에서 수정)

      IMG_SIZE        = 320    # 모델 입력 해상도 (320x320 고정)
      SCORE_THRESHOLD = 0.5    # 탐지 신뢰도 기준 (0.0 ~ 1.0)
      MODEL_PATH      = './lite-model_efficientdet_lite0_detection_default_1.tflite'
      LABEL_PATH      = './COCO2017_classes.txt'
      BOX_COLOR       = (0, 255, 0)   # 박스 색상 (BGR, 초록)
      TEXT_COLOR      = (0, 255, 0)   # 텍스트 색상 (BGR, 초록)

      설정값

      설명

      SCORE_THRESHOLD 낮추기

      더 많이 탐지 (오탐 증가)

      SCORE_THRESHOLD 높이기

      더 엄격하게 탐지 (미탐 증가)


      소스 구조

      test_tflite6.py
      ├── 1. 설정값
      ├── 2. load_labels()      레이블 파일 로드
      ├── 3. load_model()       TFLite 모델 로드
      ├── 4. init_camera()      PiCamera2 초기화
      ├── 5. preprocess()       프레임 전처리
      ├── 6. draw_detections()  탐지 결과 시각화
      ├── 7. FPSCounter 클래스  FPS 측정
      └── 8. main()             메인 루프


      주요 함수 설명

      load_labels(label_path) — 레이블 로드

      • COCO2017_classes.txt를 읽어 클래스 이름 리스트 반환

      • 파일 형식: 쉼표(,) 구분, 1줄로 작성

      • 반환 예: ['person', 'bicycle', 'car', ...]

      load_model(model_path) — 모델 로드

      • TFLite 인터프리터를 초기화하고 텐서 메모리 할당

      • 입력 텐서 타입 자동 감지 (uint8 또는 float32)

      • 반환값: (interpreter, input_details, output_details, input_dtype)

      init_camera(img_size) — 카메라 초기화

      • PiCamera2를 img_size × img_size 해상도, RGB888 포맷으로 설정

      • 워밍업을 위해 1초 대기 후 반환

      preprocess(frame, input_dtype) — 전처리

      • PiCamera2 프레임 (H, W, 3) → 모델 입력 (1, H, W, 3) 배치 차원 추가

      • 입력 타입에 따라 자동 변환:

        • uint8: 그대로 사용 (0 ~ 255)

        • float32: 정규화 (0.0 ~ 1.0)

      draw_detections(image, boxes, classes, scores, labels, threshold, img_size) — 시각화

      • 신뢰도 기준(threshold) 이상인 탐지 결과만 표시

      • 신뢰도 높은 순으로 정렬하여 처리

      • 각 탐지 객체에 바운딩 박스 + 클래스명 + 신뢰도 표시

      • 박스 좌표: 비율값(0~1) → 픽셀 좌표 변환 (ymin, xmin, ymax, xmax)

      FPSCounter 클래스 — FPS 측정

      • update(): 매 프레임마다 호출, 1초마다 FPS 갱신

      • draw(image): 이미지 좌측 상단에 FPS 표시 (노란색)


      메인 루프 처리 순서

      while True:
        Step 1  프레임 캡처          picam2.capture_array()
        Step 2  전처리               preprocess()
        Step 3  모델 추론            interpreter.invoke()
        Step 4  결과 추출            boxes / classes / scores
        Step 5  탐지 결과 그리기     draw_detections()
        Step 6  FPS 표시             fps_counter.draw()
        Step 7  탐지 수 표시         cv2.putText()
        Step 8  화면 출력            cv2.imshow()
        Step 9  콘솔 로그            탐지된 경우만 출력
        Step 10 종료 키 확인         'q' 입력 시 break


      모델 출력 텐서 구성

      EfficientDet-Lite0 모델은 4개의 출력 텐서를 반환합니다.

      인덱스

      내용

      shape

      output_details[0]

      바운딩 박스 좌표 (ymin, xmin, ymax, xmax)

      [1, 25, 4]

      output_details[1]

      클래스 ID

      [1, 25]

      output_details[2]

      신뢰도 (score)

      [1, 25]

      output_details[3]

      유효 탐지 수 (count)

      [1]

      최대 25개 객체까지 탐지 결과를 반환하며, SCORE_THRESHOLD 이상인 것만 화면에 표시합니다.


      화면 표시 항목

      항목

      위치

      색상

      FPS

      좌측 상단 (10, 25)

      노란색

      탐지 수 (Detected: N)

      좌측 상단 (10, 50)

      하늘색

      바운딩 박스

      객체 위치

      초록색

      클래스명 + 신뢰도

      박스 상단

      초록색 (검정 배경)


      탐지 가능한 클래스 (COCO 80개)

      person, bicycle, car, motorcycle, airplane, bus, train, truck, boat,

      traffic light, fire hydrant, stop sign, parking meter, bench,

      bird, cat, dog, horse, sheep, cow, elephant, bear, zebra, giraffe,

      backpack, umbrella, handbag, tie, suitcase, frisbee, skis, snowboard,

      sports ball, kite, baseball bat, baseball glove, skateboard, surfboard,

      tennis racket, bottle, wine glass, cup, fork, knife, spoon, bowl,

      banana, apple, sandwich, orange, broccoli, carrot, hot dog, pizza,

      donut, cake, chair, couch, potted plant, bed, dining table, toilet,

      tv, laptop, mouse, remote, keyboard, cell phone,

      microwave, oven, toaster, sink, refrigerator, book, clock, vase,

      scissors, teddy bear, hair drier, toothbrush


      자원 해제

      프로그램 종료 시 finally 블록에서 항상 실행됩니다.

      picam2.stop()           # 카메라 스트림 중단
      cv2.destroyAllWindows() # OpenCV 윈도우 닫기

      <샘플 코드>

      # ============================================================
      # EfficientDet-Lite0 + Raspberry Pi 5 + PiCamera2
      #
      # [실행 전 준비]
      #   pip install picamera2 opencv-python tensorflow numpy
      #   모델 파일: lite-model_efficientdet_lite0_detection_default_1.tflite
      #   레이블 파일: COCO2017_classes.txt
      #
      # [실행 방법]
      #   python test_tflite.py
      #
      # [종료 방법]
      #   화면에서 'q' 키를 누르거나 Ctrl+C
      # ============================================================
      
      from picamera2 import Picamera2
      import cv2
      import numpy as np
      import tensorflow as tf
      import time
      import sys
      import os
      
      
      # ──────────────────────────────────────────
      # 1. 설정값 (한 곳에서 수정하기 쉽게 분리)
      # ──────────────────────────────────────────
      IMG_SIZE        = 320          # 모델 입력 해상도 (320x320 고정)
      SCORE_THRESHOLD = 0.5          # 탐지 신뢰도 기준 (0.0 ~ 1.0)
                                     #   낮추면 → 더 많이 탐지 (오탐 증가)
                                     #   높이면 → 더 엄격하게 탐지 (미탐 증가)
      MODEL_PATH      = './lite-model_efficientdet_lite0_detection_default_1.tflite'
      LABEL_PATH      = './COCO2017_classes.txt'
      BOX_COLOR       = (0, 255, 0)  # 박스 색상 (BGR 순서: 초록)
      TEXT_COLOR      = (0, 255, 0)  # 레이블 텍스트 색상
      FONT            = cv2.FONT_HERSHEY_SIMPLEX
      
      
      # ──────────────────────────────────────────
      # 2. 레이블 로드 함수
      # ──────────────────────────────────────────
      def load_labels(label_path: str) -> list:
          """
          COCO 클래스 레이블 파일을 읽어 리스트로 반환합니다.
          예: ['person', 'bicycle', 'car', ...]
      
          Args:
              label_path: 레이블 파일 경로
          Returns:
              labels: 클래스 이름 리스트
          """
          if not os.path.exists(label_path):
              print(f"[ERROR] Label file not found: {label_path}")
              sys.exit(1)
      
          labels = []
          with open(label_path, 'r') as f:
              for line in f:
                  for word in line.split(','):
                      labels.append(word.strip().lower())
      
          print(f"[INFO] Loaded {len(labels)} labels successfully")
          return labels
      
      
      # ──────────────────────────────────────────
      # 3. TFLite 모델 로드 함수
      # ──────────────────────────────────────────
      def load_model(model_path: str):
          """
          TensorFlow Lite 모델을 로드하고 인터프리터를 반환합니다.
          입력/출력 텐서 정보도 함께 반환합니다.
      
          Args:
              model_path: TFLite 모델 파일 경로
          Returns:
              interpreter   : TFLite 인터프리터 객체
              input_details : 입력 텐서 정보
              output_details: 출력 텐서 정보
              input_dtype   : 입력 데이터 타입 (uint8 또는 float32)
          """
          if not os.path.exists(model_path):
              print(f"[ERROR] Model file not found: {model_path}")
              sys.exit(1)
      
          interpreter = tf.lite.Interpreter(model_path=model_path)
          interpreter.allocate_tensors()
      
          input_details  = interpreter.get_input_details()
          output_details = interpreter.get_output_details()
      
          # 모델의 입력 타입 확인 (uint8 / float32)
          input_dtype = input_details[0]['dtype']
          print(f"[INFO] Model input dtype : {input_dtype.__name__}")
          print(f"[INFO] Model input shape : {input_details[0]['shape']}")
      
          return interpreter, input_details, output_details, input_dtype
      
      
      # ──────────────────────────────────────────
      # 4. 카메라 초기화 함수
      # ──────────────────────────────────────────
      def init_camera(img_size: int) -> Picamera2:
          """
          PiCamera2를 초기화하고 시작합니다.
      
          Args:
              img_size: 캡처 해상도 (정사각형, 예: 320)
          Returns:
              picam2: 초기화된 카메라 객체
          """
          picam2 = Picamera2()
          config = picam2.create_preview_configuration(
              main={"size": (img_size, img_size), "format": "RGB888"}
          )
          picam2.configure(config)
          picam2.start()
          time.sleep(1)  # 카메라 워밍업 대기 (1초)
          print("[INFO] Camera started successfully")
          return picam2
      
      
      # ──────────────────────────────────────────
      # 5. 전처리 함수 (입력 타입에 따라 자동 변환)
      # ──────────────────────────────────────────
      def preprocess(frame: np.ndarray, input_dtype) -> np.ndarray:
          """
          카메라 프레임을 모델 입력 형식으로 변환합니다.
      
          변환 규칙:
              - uint8  모델: 0~255 그대로 사용
              - float32 모델: 0.0~1.0 으로 정규화
      
          Args:
              frame      : 카메라에서 받은 원본 이미지 (H, W, 3)
              input_dtype: 모델이 기대하는 입력 데이터 타입
          Returns:
              img: 모델 입력용 배열 (1, H, W, 3)
          """
          img = np.array(frame)           # (320, 320, 3)
          img = img[np.newaxis, :, :, :]  # (1, 320, 320, 3) 배치 차원 추가
      
          if input_dtype == np.float32:
              img = img.astype(np.float32) / 255.0  # 정규화: 0~255 → 0.0~1.0
          else:
              img = img.astype(np.uint8)
      
          return img
      
      
      # ──────────────────────────────────────────
      # 6. 탐지 결과 그리기 함수
      # ──────────────────────────────────────────
      def draw_detections(
          image: np.ndarray,
          boxes: np.ndarray,
          classes: np.ndarray,
          scores: np.ndarray,
          labels: list,
          threshold: float,
          img_size: int
      ) -> tuple:
          """
          탐지된 객체를 이미지에 박스 + 레이블로 그립니다.
      
          Args:
              image    : 원본 이미지
              boxes    : 탐지 박스 좌표 배열 [(ymin,xmin,ymax,xmax), ...]
              classes  : 탐지된 클래스 ID 배열
              scores   : 탐지 신뢰도 배열
              labels   : 클래스 이름 리스트
              threshold: 신뢰도 최소 기준
              img_size : 이미지 크기 (픽셀)
          Returns:
              out_img        : 박스/레이블이 그려진 이미지
              detected_count : 실제 탐지된 객체 수
          """
          out_img = image.copy()
          detected_count = 0
      
          # scores 기준 내림차순 정렬 (신뢰도 높은 것부터 처리)
          sorted_indices = np.argsort(scores)[::-1]
      
          for idx in sorted_indices:
              score = scores[idx]
      
              # 신뢰도 기준 미달이면 중단
              if score < threshold:
                  break
      
              # 박스 좌표 계산: 비율(0~1) → 픽셀 좌표
              ymin, xmin, ymax, xmax = boxes[idx]
              xmin = int(max(1,        xmin * img_size))
              xmax = int(min(img_size, xmax * img_size))
              ymin = int(max(1,        ymin * img_size))
              ymax = int(min(img_size, ymax * img_size))
      
              # 레이블 텍스트 준비 (영어 클래스명 + 신뢰도)
              class_id   = int(classes[idx])
              label_name = labels[class_id] if class_id < len(labels) else f"id:{class_id}"
              label_text = f"{label_name}: {score:.2f}"
      
              # 박스 그리기
              cv2.rectangle(out_img, (xmin, ymin), (xmax, ymax), BOX_COLOR, 2)
      
              # 텍스트 배경 (가독성을 위한 검정 배경)
              (tw, th), _ = cv2.getTextSize(label_text, FONT, 0.5, 1)
              cv2.rectangle(
                  out_img,
                  (xmin, ymin - th - 6),
                  (xmin + tw, ymin),
                  (0, 0, 0), -1  # -1: 채우기
              )
      
              # 레이블 텍스트 출력 (화면 표시는 영어)
              cv2.putText(
                  out_img, label_text,
                  (xmin, ymin - 4),
                  FONT, 0.5, TEXT_COLOR, 1, cv2.LINE_AA
              )
      
              detected_count += 1
      
          return out_img, detected_count
      
      
      # ──────────────────────────────────────────
      # 7. FPS 측정 클래스
      # ──────────────────────────────────────────
      class FPSCounter:
          """
          초당 프레임 수(FPS)를 측정하고 화면에 표시하는 클래스.
          1초마다 FPS 값을 갱신합니다.
          """
          def __init__(self):
              self._start = time.time()
              self._count = 0
              self.fps    = 0.0
      
          def update(self):
              """프레임이 처리될 때마다 호출"""
              self._count += 1
              elapsed = time.time() - self._start
              if elapsed >= 1.0:              # 1초마다 FPS 갱신
                  self.fps    = self._count / elapsed
                  self._count = 0
                  self._start = time.time()
      
          def draw(self, image: np.ndarray) -> np.ndarray:
              """FPS를 이미지 좌측 상단에 표시 (화면 표시는 영어)"""
              text = f"FPS: {self.fps:.1f}"
              cv2.putText(
                  image, text, (10, 25),
                  FONT, 0.7, (255, 255, 0), 2, cv2.LINE_AA
              )
              return image
      
      
      # ──────────────────────────────────────────
      # 8. 메인 실행 함수
      # ──────────────────────────────────────────
      def main():
          print("=" * 50)
          print("  EfficientDet-Lite0 Real-time Object Detection")
          print(f"  Confidence Threshold : {SCORE_THRESHOLD}")
          print("  Press 'q' to quit")
          print("=" * 50)
      
          # ── 초기화 ──
          labels = load_labels(LABEL_PATH)
          interpreter, input_details, output_details, input_dtype = load_model(MODEL_PATH)
          picam2      = init_camera(IMG_SIZE)
          fps_counter = FPSCounter()
      
          try:
              while True:
                  # Step 1: 프레임 캡처
                  frame = picam2.capture_array()
      
                  # Step 2: 전처리 (모델 입력 타입에 맞게 자동 변환)
                  input_tensor = preprocess(frame, input_dtype)
      
                  # Step 3: 모델 추론 (inference)
                  interpreter.set_tensor(input_details[0]['index'], input_tensor)
                  interpreter.invoke()
      
                  # Step 4: 결과 추출
                  boxes   = interpreter.get_tensor(output_details[0]['index']).squeeze()
                  classes = interpreter.get_tensor(output_details[1]['index']).squeeze()
                  scores  = interpreter.get_tensor(output_details[2]['index']).squeeze()
                  # output_details[3]: count (유효 탐지 수) → draw_detections에서 직접 카운트
      
                  # Step 5: 탐지 결과 이미지에 그리기
                  out_img, det_count = draw_detections(
                      np.array(input_tensor[0]),  # 표시용 이미지 (배치 차원 제거)
                      boxes, classes, scores,
                      labels, SCORE_THRESHOLD, IMG_SIZE
                  )
      
                  # Step 6: FPS 측정 및 화면 표시
                  fps_counter.update()
                  fps_counter.draw(out_img)
      
                  # Step 7: 탐지 수 화면 표시 (영어)
                  cv2.putText(
                      out_img, f"Detected: {det_count}",
                      (10, 50), FONT, 0.7, (0, 200, 255), 2, cv2.LINE_AA
                  )
      
                  # Step 8: 결과 화면 출력
                  cv2.imshow("EfficientDet-Lite0 Detection", out_img)
      
                  # Step 9: 콘솔 로그 (탐지된 경우만 출력, 영어)
                  if det_count > 0:
                      print(f"[DETECT] {det_count} object(s) found | FPS: {fps_counter.fps:.1f}")
      
                  # Step 10: 'q' 키 입력 시 종료
                  if cv2.waitKey(1) & 0xFF == ord('q'):
                      print("[INFO] Quit requested by user.")
                      break
      
          except KeyboardInterrupt:
              print("\n[INFO] Interrupted by Ctrl+C.")
      
          finally:
              # 항상 자원 해제 (카메라 & 윈도우)
              picam2.stop()
              cv2.destroyAllWindows()
              print("[INFO] Camera and windows closed.")
      
      
      # ──────────────────────────────────────────
      # 9. 진입점
      # ──────────────────────────────────────────
      if __name__ == '__main__':
          main()

      댓글 0

      DEVOTEE를 활성화 시키면
      지금 작성한 댓글에 AI가 댓글을 달아줍니다.

      xipert 님의 최신 블로그

      더보기

      관련 블로그

      DEVOTEE 추천 블로그

      동영상 기고하기