Edge AI - 4. Edge AI 모델 배포 및 최적화 (4-1. 디바이스별 AI 모델 배포)

2025. 3. 10. 18:22AI/AI

📌 4-1. 디바이스별 AI 모델 배포

Edge AI 모델을 배포하려면 각 디바이스(Raspberry Pi, Jetson Nano, Google Coral TPU)에 최적화된 방식으로 모델을 변환하고 실행해야 합니다.
이 과정에서 TensorFlow Lite, TensorRT, Edge TPU 등의 기술을 활용하여 AI 모델을 빠르고 효율적으로 실행할 수 있습니다.


🌟 1. Raspberry Pi + TensorFlow Lite 배포

Raspberry Pi는 소형 저전력 컴퓨터로, Edge AI 모델을 실행하는 데 널리 사용되는 플랫폼입니다.
TensorFlow Lite(TFLite)를 활용하면 AI 모델을 경량화하여 Raspberry Pi에서 실시간 실행할 수 있습니다.

(1) TensorFlow Lite 설치 (Raspberry Pi)

📌 TFLite 런타임 설치 (라즈비안 OS 기준)

pip install tflite-runtime

📌 Raspberry Pi에 OpenCV 설치 (영상 처리용)

sudo apt update
sudo apt install python3-opencv

(2) TFLite 모델 변환 및 실행

📌 TensorFlow 모델을 TensorFlow Lite로 변환

import tensorflow as tf

# 사전 학습된 모델 로드
model = tf.keras.models.load_model('model.h5')

# TensorFlow Lite 변환
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

# 변환된 모델 저장
with open('model.tflite', 'wb') as f:
    f.write(tflite_model)

📌 TFLite 모델 실행 코드 (Raspberry Pi)

import tflite_runtime.interpreter as tflite
import numpy as np
import cv2

# 모델 로드
interpreter = tflite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()

# 카메라 입력
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 이미지 전처리
    img = cv2.resize(frame, (224, 224))
    img = np.expand_dims(img, axis=0).astype(np.float32)

    # AI 모델 실행
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()
    interpreter.set_tensor(input_details[0]['index'], img)
    interpreter.invoke()

    output = interpreter.get_tensor(output_details[0]['index'])
    print("Prediction:", output)

    cv2.imshow("TensorFlow Lite Inference", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

📌 활용 사례

  • Raspberry Pi + 카메라 모듈을 활용한 실시간 이미지 분류
  • 스마트 CCTV를 위한 얼굴 인식 및 객체 탐지
  • IoT 센서 데이터를 분석하여 환경 모니터링 AI 시스템 구축

🌟 2. Jetson Nano + TensorRT 최적화

Jetson Nano는 GPU 기반 AI 가속이 가능한 NVIDIA의 엣지 AI 개발 보드입니다.
TensorRT를 활용하면 딥러닝 모델을 최적화하여 실행 속도를 최대 2~5배 향상시킬 수 있습니다.

(1) TensorRT 설치 (Jetson Nano)

📌 Jetson Nano에 TensorRT 설치

sudo apt install nvidia-tensorrt

📌 CUDA 및 cuDNN 설치 (딥러닝 연산 가속)

sudo apt install nvidia-cuda-toolkit libcudnn8

(2) TensorFlow 모델을 TensorRT로 변환

📌 TensorRT 변환 코드 (FP16 최적화 적용)

import tensorrt as trt

# TensorRT 로거 생성
logger = trt.Logger(trt.Logger.WARNING)

# TensorRT 빌더 및 네트워크 생성
builder = trt.Builder(logger)
network = builder.create_network()

# 모델 변환 및 최적화
config = builder.create_builder_config()
config.set_flag(trt.BuilderFlag.FP16)

engine = builder.build_engine(network, config)

📌 YOLO 모델을 Jetson Nano에서 실행하는 코드

from ultralytics import YOLO
import cv2

# YOLO 모델 로드
model = YOLO("yolov8n.engine")  # TensorRT 최적화된 모델 사용

cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    results = model(frame)

    for r in results:
        for box in r.boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

    cv2.imshow("YOLOv8 Object Detection", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

📌 활용 사례

  • 자율주행 차량에서 실시간 객체 탐지
  • 스마트시티 CCTV에서 보행자 및 차량 인식
  • 산업용 공장 자동화에서 불량 제품 검출

🌟 3. Google Coral TPU에서 AI 모델 실행

Google Coral TPU는 TensorFlow Lite 모델을 초저전력에서 고속으로 실행할 수 있는 AI 가속기입니다.

(1) Coral TPU 드라이버 및 라이브러리 설치

📌 Coral TPU 드라이버 설치

echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list
sudo apt update
sudo apt install libedgetpu1-std

(2) Edge TPU 모델 실행

📌 Edge TPU에서 TensorFlow Lite 모델 실행 코드

import cv2
import numpy as np
import tflite_runtime.interpreter as tflite

# Edge TPU 모델 로드
interpreter = tflite.Interpreter(model_path="mobilenet_v2_edgetpu.tflite")
interpreter.allocate_tensors()

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    img = cv2.resize(frame, (300, 300))
    img = np.expand_dims(img, axis=0).astype(np.float32)

    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()
    interpreter.set_tensor(input_details[0]['index'], img)
    interpreter.invoke()

    output = interpreter.get_tensor(output_details[0]['index'])
    print("Detected Objects:", output)

    cv2.imshow("Edge TPU Object Detection", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

📌 활용 사례

  • 스마트 감시 시스템 (CCTV, 보안 카메라)
  • 공장 자동화 시스템에서 품질 검사
  • 웨어러블 디바이스 및 IoT 시스템에서 실시간 AI 분석

📌 요약 정리

디바이스  주요 기술 활용 사례
Raspberry Pi TensorFlow Lite 배포 IoT, 스마트 CCTV, 환경 모니터링
Jetson Nano TensorRT 최적화 자율주행, 스마트시티, 공장 자동화
Google Coral TPU 초저전력 AI 가속 스마트 감시 시스템, IoT