บทนำ - why Edge AI?
Cloud vs Edge Computing
Cloud Computing ส่งข้อมูลทั้งหมดไปประมวลผลที่ Server ทำให้มี Latency สูงและต้องการ Bandwidth มาก
Edge Computing ประมวลผลทันที trênอุปกรณ์ ลด Latency, เพิ่ม Privacy และทำงานได้แม้ไม่มี Internet
TensorFlow Lite คืออะไร?
TensorFlow Lite เป็น Lightweight Version ของ TensorFlow ออกแบบมาเฉพาะสำหรับ Mobile และ Edge Devices มีขนาดเล็ก, ความเร็วสูง และสามารถใช้งานได้กับ Raspberry Pi, Android, iOS, และ Microcontrollers
ข้อดีของ Edge AI
Low Latency
ไม่มีการส่งข้อมูลไป Server ทำให้ Response ใกล้เคียง Real-time
Privacy & Security
ข้อมูลอยู่ที่เครื่อง ไม่ถูกส่งออกภายนอกช่วยรักษาความเป็นส่วนตัว
Offline Capability
ทำงานได้แม้ไม่มี Internet Connection สมบูรณ์
สิ่งที่ต้องเตรียม - Prerequisites
ฮาร์ดแวร์ที่แนะนำ
Raspberry Pi 4 Model B
- CPU: Broadcom BCM2711, Quad-core Cortex-A72 1.5GHz
- RAM: 4GB / 8GB LPDDR4
- FPS: ~30 FPS dengan MobileNet SSD v2
Raspberry Pi 5
- CPU: Broadcom BCM2712, Quad-core Cortex-A76 2.4GHz
- RAM: 4GB / 8GB LPDDR4X
- FPS: ~40-50 FPS dengan optimizations
ซอฟต์แวร์ที่ต้องติดตั้ง
Raspberry Pi OS (64-bit)
ต้องเป็นเวอร์ชัน 64-bit สำหรับ Raspberry Pi 4/5 Download at: raspberrypi.com/software
Python 3.8+ และ TensorFlow Lite
sudo apt-get update
sudo apt-get install -y python3 python3-pip python3-venv
pip3 install tensorflow-lite
Node.js 16+ และ tflite-node (ตัวอย่าง)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
Raspberry Pi Camera Module
Raspberry Pi Camera Module V2 หรือ USB Webcam
สำหรับ Real-time Object Detection
หมายเหตุสำคัญ
- Raspberry Pi 5 ต้องใช้ Python 3.10+ เพื่อรองรับ TensorFlow Lite
- สำหรับ Raspberry Pi 4 สามารถใช้ Python 3.8-3.11 ได้
- ใช้ 64-bit OS เสมอเพื่อประสิทธิภาพที่ดีที่สุด
- เปิด Camera Interface ผ่าน `sudo raspi-config` ก่อนใช้งาน
การเปลี่ยนรูปแบบโมเดล - Model Conversion
architectures ที่แนะนำสำหรับ Edge Devices
MobileNet SSD v2
Lightweightvisual detection model,balances speed and accuracy
EfficientDet-Lite
EfficientDet adapted for edge devices with better accuracy
SSD MobileNet v3
Latest MobileNet with better efficiency
ขั้นตอนการ convert โมเดลจาก TensorFlow เป็น TensorFlow Lite
Train or Download Pre-trained Model
สามารถใช้ Pre-trained Models จาก TensorFlow Hub หรือ Train โมเดลด้วยตัวเอง
# Downloadpre-trained models from TensorFlow Hub
import tensorflow_hub as hub
model = hub.load('https://tfhub.dev/tensorflow/ssd_mobilenet_v2/2')
concrete_func = model.signatures['serving_default']
concrete_func.inputs[0].set_shape([1, 320, 320, 3])
Convert to TFLite
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_concrete_functions(
[concrete_func])
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# 4-bit quantization for even smaller size
converter.quantistic = True
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Add Metadata (Optional but Recommended)
Metadata ช่วยให้โมเดลมีข้อมูล input/output tensor format, labels, และ normalization parameters
from tflite_support import flatbuffers
from tflite_support import metadata_schema_py_generated as schema
# Add metadata to TFLite model
populator = metadata.MetadataPopulator.with_model_file('model.tflite')
populator.load_metadata_buffer(metadata_buf)
populator.load_associated_files(['labels.txt'])
populator.populate()
Architecture Design - Model Conversion Flow
Real-time Object Detection - การตรวจจับวัตถุแบบเรียลไทม์
Object Detection คือเทคโนโลยีที่สามารถระบุและ locate วัตถุในภาพหรือวิดีโอได้ ด้วย TensorFlow Lite บน Raspberry Pi เราสามารถทำ Real-time Object Detection ได้อย่างมีประสิทธิภาพ
Python Implementation - OpenCV + TensorFlow Lite
ขั้นตอนการทำงาน
- 1. โหลดโมเดล TensorFlow Lite
- 2. initialize camera (Picamera2 หรือ OpenCV)
- 3. Capture frame และ Preprocess
- 4. Run inference พร้อม Draw bounding boxes
- 5. Display และ Save results
#!/usr/bin/env python3
"""
Real-time object detection using TensorFlow Lite on Raspberry Pi
"""
import cv2
import numpy as np
from tflite_runtime.interpreter import Interpreter
from picamera2 import Picamera2
import time
class ObjectDetector:
def __init__(self, model_path, label_path, threshold=0.5):
"""Initialize TensorFlow Lite interpreter and load labels"""
self.threshold = threshold
self.interpreter = Interpreter(model_path=model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
with open(label_path, 'r') as f:
self.labels = [line.strip() for line in f.readlines()]
self.input_shape = self.input_details[0]['shape']
self.height = self.input_shape[1]
self.width = self.input_shape[2]
def detect_objects(self, frame):
"""Run object detection on a frame"""
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (self.width, self.height))
input_data = np.expand_dims(frame_resized, axis=0)
self.interpreter.set_tensor(self.input_details[0]['index'], input_data)
self.interpreter.invoke()
boxes = self.interpreter.get_tensor(self.output_details[0]['index'])[0]
classes = self.interpreter.get_tensor(self.output_details[1]['index'])[0]
scores = self.interpreter.get_tensor(self.output_details[2]['index'])[0]
return boxes, classes, scores
def draw_detections(self, frame, boxes, classes, scores):
"""Draw bounding boxes and labels on frame"""
h, w = frame.shape[:2]
for i in range(len(scores)):
if scores[i] > self.threshold:
ymin, xmin, ymax, xmax = boxes[i]
left = int(xmin * w)
top = int(ymin * h)
right = int(xmax * w)
bottom = int(ymax * h)
label = self.labels[int(classes[i])]
score = scores[i]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.rectangle(frame, (left, top - 20), (left + 100, top), (0, 255, 0), -1)
cv2.putText(frame, f"{label}: {score:.2f}", (left, top - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
return frame
def main():
MODEL_PATH = "models/detect.tflite"
LABEL_PATH = "models/coco_labels.txt"
detector = ObjectDetector(MODEL_PATH, LABEL_PATH, threshold=0.5)
picam2 = Picamera2()
config = picam2.create_preview_configuration(
main={"size": (640, 480), "format": "RGB888"}
)
picam2.configure(config)
picam2.start()
frame_count = 0
start_time = time.time()
try:
while True:
frame = picam2.capture_array()
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
boxes, classes, scores = detector.detect_objects(frame)
frame = detector.draw_detections(frame, boxes, classes, scores)
frame_count += 1
if frame_count % 30 == 0:
fps = frame_count / (time.time() - start_time)
print(f"FPS: {fps:.1f}, Objects: {sum(scores > 0.5)}")
cv2.imshow("Object Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
picam2.stop()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
ตัวอย่าง Output และ Performance
ผลลัพธ์ detection
FPS: 24.5, Objects: 3 detected - person: 0.92 - laptop: 0.85 - cell phone: 0.78
Performance Comparison
Node.js Deployment - Web-based Edge AI Server
เพื่อใช้ Edge AI ใน Web Application เราสามารถสร้าง REST API server ด้วย Node.js ที่ทำ object detection และส่ง results ผ่าน WebSocket หรือ HTTP
Node.js Edge AI Server Setup
{
"name": "edge-ai-server",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5",
"node-fetch": "^3.3.2",
"socket.io": "^4.7.2"
}
}
Edge AI Server Code
const express = require('express');
const cors = require('cors');
const http = require('http');
const { Server } = require('socket.io');
const tflite = require('tflite-node');
const app = express();
app.use(cors());
app.use(express.json());
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: "*" }
});
const port = process.env.PORT || 3000;
const MODEL_PATH = process.env.MODEL_PATH || "/home/pi/edgeai/models/detect.tflite";
const LABEL_PATH = process.env.LABEL_PATH || "/home/pi/edgeai/models/coco_labels.txt";
let interpreter = null;
let labels = [];
let isModelLoaded = false;
let lastFPS = 0;
// Health endpoint
app.get('/health', (req, res) => {
res.json({
status: 'ok',
modelLoaded: isModelLoaded,
fps: lastFPS || 0,
uptime: process.uptime()
});
});
// Detection API endpoint
app.post('/api/detect', async (req, res) => {
if (!isModelLoaded) {
return res.status(503).json({ error: 'Model not loaded' });
}
try {
const { image } = req.body;
const results = await runDetection(image);
res.json(results);
} catch (error) {
console.error('Detection error:', error);
res.status(500).json({ error: error.message });
}
});
// WebSocket for real-time streaming
io.on('connection', (socket) => {
console.log('New client connected');
socket.emit('modelStatus', { loaded: isModelLoaded });
socket.on('disconnect', () => console.log('Client disconnected'));
});
server.listen(port, () => {
console.log(`Edge AI Server running on port ${port}`);
loadModel();
});
async function loadModel() {
try {
interpreter = await tflite.loadSession(MODEL_PATH);
const labelResponse = await fetch(LABEL_PATH);
const labelText = await labelResponse.text();
labels = labelText.trim().split('\n');
isModelLoaded = true;
console.log('Model loaded successfully');
io.emit('modelStatus', { loaded: true });
} catch (error) {
console.error('Failed to load model:', error);
}
}
async function runDetection(imageData) {
const buffer = Buffer.from(imageData.replace(/^data:image\/[a-z]+;base64,/, ''), 'base64');
const results = await interpreter.run(buffer);
return results.map(r => ({
label: labels[r.classId] || 'unknown',
confidence: r.confidence.toFixed(2),
boundingBox: r.boundingBox
}));
}
API Endpoints
GET /health
{
"status": "ok",
"modelLoaded": true,
"fps": 24.5,
"uptime": 3600
}
POST /api/detect
Body: { "image": "data:image/jpeg;base64,..." }
Response: [
{ "label": "person", "confidence": "0.92" }
]
Power Optimization Techniques - techniques เพื่อเพิ่มประสิทธิภาพ
Hardware Acceleration
- Coral USB Accelerator (Edge TPU): เพิ่มความเร็ว 10-30x ใช้สำหรับโมเดลที่ compile แล้ว
- GPU Delegate: ใช้ GPU ของ Raspberry Pi สำหรับ inference ที่ซับซ้อน
- NNAPI Delegate: Android Neural Networks API สำหรับ Android-based edge devices
Software Optimization
- Quantization: ลดขนาดโมเดล 75% โดยใช้ int8 แทน float32
- Pruning: ตัด weights ที่ไม่สำคัญออก
- Resolution Tuning: ปรับ input size ตามความสามารถของ CPU
CPU Frequency Scaling & Thermal Management
ตั้งค่า CPU Frequency
# View current CPU frequency
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
# Set to performance mode (maximum frequency)
echo performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
# Set to powersave mode (minimum frequency)
echo powersave | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
# View available frequencies
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
Thermal Management Script
#!/bin/bash
# Raspberry Pi Thermal Management Script
TEMP_FILE="/sys/class/thermal/thermal_zone0/temp"
get_temp() {
cat $TEMP_FILE | awk '{printf "%.1f°C\n", $1/1000}'
}
# Check temperature and adjust CPU frequency
TEMP=$(get_temp)
echo "Current temperature: $TEMP"
if [ "$TEMP" > "70°C" ]; then
echo "warning: High temperature! Setting powersave mode."
echo powersave | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
elif [ "$TEMP" < "60°C" ]; then
echo "Normal temperature. Setting balanced mode."
echo balanced | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
fi
Power Saving Tips (Power Saving Tips)
Disable Unused Services
sudo systemctl stop bluetooth sudo systemctl disable bluetooth
Reduce WiFi Power
echo 'options rtl8723cs rtw_power_mgnt=0' | sudo tee /etc/modprobe.d/rtl8723cs.conf
Screen Power Management
xset s off xset -dpms xset s noblank
โครงการตัวอย่าง - Real-world Applications
Smart Surveillance System
ระบบรักษาความปลอดภัยอัจฉริยะที่ใช้ Raspberry Pi + Camera ตรวจจับบุคคลและวัตถุ suspicious แบบ Real-time พร้อมส่งแจ้งเตือนผ่าน Telegram
Features:
- ✓ Real-time object detection
- ✓ Motion alerts to Telegram
- ✓ Local storage with Pi Camera
- ✓ Low power consumption
Smart Agriculture
ระบบเกษตรอัจฉริยะสำหรับไทย ใช้ Raspberry Pi ตรวจจับศัตรูพืช และวัชพืชด้วย TensorFlow Lite พร้อมส่งข้อมูลผ่าน LoRa
Features:
- ✓ Pesticide identification
- ✓ Crop health monitoring
- ✓ LoRa for remote areas
- ✓ Offline capable
Food Quality Checker
ระบบตรวจสอบคุณภาพอาหารสำหรับตลาดไทย ตรวจจับความสุกของผลไม้ และตรวจหาสิ่งปนเปื้อนด้วย Edge AI
Features:
- ✓ Fruit ripeness detection
- ✓ Contamination check
- ✓ Local database storage
- ✓ QR code integration
Face Entry System
ระบบควบคุมเข้าออกด้วยใบหน้าสำหรับสำนักงานหรือบ้าน ใช้ TensorFlow Lite สำหรับ face detection และ recognition
Features:
- ✓ Real-time face detection
- ✓ Access control
- ✓ Local face database
- ✓ GPIO control relay
สรุป - Conclusion
คำแนะนำหลัก
- สำหรับ Raspberry Pi 4: เริ่มต้นด้วย MobileNet SSD v2 ที่มีความเร็วสูงและขนาดเล็ก
- สำหรับ Raspberry Pi 5: ใช้ EfficientDet-Lite หรือ Coral USB Accelerator เพื่อความเร็วสูงสุด
- Python vs Node.js: Python สำหรับ standalone processing, Node.js สำหรับ Web-based UI
- Optimization: ใช้ quantization, pruning และ CPU frequency scaling เพื่อประสิทธิภาพสูงสุด
Resources ที่เป็นประโยชน์
ขั้นตอนต่อไป
- 1 ทดลองติดตั้ง TensorFlow Lite บน Raspberry Pi จริง
- 2 ทดลอง run ตัวอย่าง object detection ด้วยโค้ด Python
- 3 สร้าง REST API server ด้วย Node.js สำหรับ Web UI
- 4
เริ่มต้น Edge AI วันนี้!
ปัญญาประดิษฐ์บนอุปกรณ์Edge ไม่ใช่เรื่องที่ซับซ้อนอีกต่อไป ด้วย TensorFlow Lite และ Raspberry Pi คุณสามารถสร้าง AI solutions ที่รวดเร็ว ประหยัด และเป็นส่วนตัวได้ง่ายๆ
กลับหน้าแรกคำถามที่พบบ่อย - FAQ
TensorFlow Lite แตกต่างจาก TensorFlow ยังไง?
TensorFlow Lite เป็นเวอร์ชัน Lightweight สำหรับ Mobile และ Edge Devices มีขนาดเล็กกว่า, ความเร็วสูงกว่าในอุปกรณ์ที่มี resource จำกัด ในขณะที่ TensorFlow ใช้สำหรับ training และมีฟีเจอร์ครบถ้วนกว่า
เทรนโมเดลเองกับใช้ Pre-trained ดีที่สุด?
สำหรับมือใหม่หรือ prototyping ควรใช้ Pre-trained models จาก TensorFlow Hub (เช่น MobileNet SSD) ส่วนถ้ามีข้อมูลเฉพาะและต้องการความแม่นยำสูง ควร train โมเดลเองด้วย TensorFlow Lite Model Maker
ต้องใช้ GPU หรือ Coral USB Accelerator ไหม?
อุปกรณ์เหล่านี้ไม่จำเป็นสำหรับการเริ่มต้น แต่จะincrease performance Raspberry Pi 4/5 สามารถ run โมเดลง่ายๆ ได้ด้วย CPU อยู่แล้ว (20-30 FPS) การใช้ Coral USB Accelerator เพิ่มจะทำให้เร็วขึ้น 10-30x
ถ้าเกิด error "Failed to load model" แก้ยังไง?
ตรวจสอบให้แน่ใจว่า:
1. โมเดลถูก convert ให้เป็น .tflite แล้ว
2. รุ่นของ TensorFlow Lite ที่ติดตั้งตรงกับเวอร์ชันที่ใช้ในการ train
3. มี memory พอ (ลองลด resolution ดู)
4. ใช้ 64-bit OS สำหรับ Raspberry Pi 4/5