Journal Article

智能嵌入式实训小车:OpenCV + YOLOv5 + TensorFlow Lite 综合平台

基于Android的智能小车综合实训平台,集成OpenCV图像处理、YOLOv5 TFLite目标检测、TensorFlow火灾检测、Tesseract车牌识别、二维码导航、Zigbee无线通信和Socket数据传输等功能模块。

21 min2 views

智能嵌入式实训小车:OpenCV + YOLOv5 + TensorFlow Lite 综合平台

项目地址:GitHub - ACar2024

项目概述

ACar2024 是一个基于 Android 的智能小车综合实训平台,将传统嵌入式开发与 AI 图像识别深度融合。通过 Socket 通信控制小车运动,利用 OpenCV + TensorFlow Lite 实现实时视觉分析,适用于高职院校嵌入式/物联网专业的实践教学和竞赛训练。


系统架构

code
┌─────────────────────────────────────────────────┐
│                 Android 控制端                    │
│  ┌──────────┐ ┌──────────┐ ┌──────────────┐    │
│  │ 摄像头预览│ │ 数据面板  │ │  控制面板     │    │
│  │ Fragment │ │ Fragment  │ │  Fragment    │    │
│  └────┬─────┘ └────┬─────┘ └──────┬───────┘    │
│       │            │              │             │
│  ┌────┴────────────┴──────────────┴───────┐    │
│  │          事件总线 (EventBus)            │    │
│  └────┬───────────────────────────────────┘    │
│       │                                         │
│  ┌────┴──────────────────────────────────┐     │
│  │     ConnectTransport (Socket通信)      │     │
│  │  + 串口通信 (Zigbee)                   │     │
│  └───────────────────────────────────────┘     │
├─────────────────────────────────────────────────┤
│              AI 视觉处理层                       │
│  ┌─────────┐ ┌──────────┐ ┌──────────┐        │
│  │YOLOv5   │ │Tesseract │ │TensorFlow│        │
│  │TFLite   │ │车牌识别   │ │火灾检测   │        │
│  └─────────┘ └──────────┘ └──────────┘        │
│  ┌─────────┐ ┌──────────┐ ┌──────────┐        │
│  │OpenCV   │ │二维码识别 │ │交通标志  │        │
│  │图像处理  │ │(ZXing)   │ │识别      │        │
│  └─────────┘ └──────────┘ └──────────┘        │
├─────────────────────────────────────────────────┤
│              小车硬件层 (Socket/串口)            │
│   摄像头 + 超声波 + 码盘 + 红外 + Zigbee       │
└─────────────────────────────────────────────────┘

核心功能模块

1. Socket 数据通信

ConnectTransport 通过 TCP Socket 与小车通信,自定义二进制协议帧格式:

java
public class ConnectTransport {
    public short TYPE = 0xAA;   // 帧头
    public short MAJOR = 0x00;  // 主指令
    public short FIRST = 0x00;  // 参数1
    public short SECOND = 0x00; // 参数2
    
    // 电机控制
    public void go(int angle, int encoder) { /* 前进 */ }
    public void back(int angle, int encoder) { /* 后退 */ }
    public void left(int speed) { /* 左转 */ }
    public void right(int speed) { /* 右转 */ }
    public void stop() { /* 停止 */ }
}

数据上行(小车 → App):

  • 超声波距离 (mm)
  • 光照强度 (lx)
  • 码盘值(里程)
  • 传感器状态(红外、PS等)

2. 运动控制策略

采用策略模式设计运动指令:

java
public class Commd {
    int wheelSpeed = 80;  // 轮速
    int angle = 50;       // 角度
    int encoder = 20;     // 码盘计数
    
    public void left90() {
        connectTransport.left(wheelSpeed);
        delay(888);         // 精确延时实现90度转弯
        Car_stop();
    }
    
    public void cargo() {
        connectTransport.go(angle, encoder);  // 精确前进
    }
}

AI 视觉识别

3. OpenCV 图像预处理流水线

java
public class Image_processing {
    // Bitmap ↔ Mat 转换
    public static Mat bitmap_mat(Bitmap bitmap) { ... }
    public static Bitmap mat_bitmap(Mat mat) { ... }
    
    // 预处理流水线
    public static void preprocess(Mat mat) {
        cvtColor(mat);           // 灰度化
        GaussianBlur(mat, 3,3,0); // 高斯滤波 3×3
        threshold(mat, 0, 255);   // 自适应阈值二值化
        dilate(mat);              // 膨胀
        erode(mat);               // 腐蚀
    }
    
    // 轮廓检测
    public static List<MatOfPoint> findContours(Mat mat) {
        List<MatOfPoint> contours = new ArrayList<>();
        Imgproc.findContours(mat, contours, ..., Imgproc.RETR_EXTERNAL, ...);
        return contours;
    }
}

4. YOLOv5 TensorFlow Lite 目标检测

使用 TFLite 格式的 YOLOv5 模型进行实时目标检测:

java
public class YoloV5Classifier extends Classifier {
    // 模型加载
    private YoloV5Classifier(Activity activity, Model model, Device device) {
        // 加载 .tflite 模型文件
        tfliteModel = FileUtil.loadMappedFile(activity, modelPath);
        tflite = new Interpreter(tfliteModel, options);
    }
    
    // 推理结果解析
    private List<Recognition> outputsToPredictions(float[][][] output) {
        // NMS 非极大值抑制
        // 置信度阈值过滤
        // 边界框映射到原图坐标
    }
    
    // 工厂方法
    public static Detector create(Activity activity, Model model) {
        return DetectorFactory.create(activity, model);
    }
}

支持的检测类型

  • 行人检测 (PedestrianDetection)
  • 车牌定位 (PlateDetector)
  • 交通标志识别 (TrafficSignRecognition)
  • 车辆识别 (VehicleRecognizer)

5. TensorFlow 火灾检测

java
public class FireDetection {
    private Interpreter tflite;
    private static final int INPUT_SIZE = 224;
    
    public float detectFire(Bitmap bitmap) {
        // 预处理: 缩放 → 224×224
        Bitmap resized = Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, true);
        
        // 转换: Bitmap → ByteBuffer
        ByteBuffer input = convertBitmapToByteBuffer(resized);
        
        // TFLite 推理
        float[][] output = new float[1][NUM_CLASSES];
        tflite.run(input, output);
        
        // 返回火灾置信度
        return output[0][1]; // fire class probability
    }
}

6. Tesseract OCR 车牌识别

java
public class CarPlate {
    public static void carTesseract(Bitmap pic, Context ctx, ...) {
        // 1. 车牌定位 (OpenCV + 颜色检测)
        PlateDetector.detectPlate(pic);
        
        // 2. 文字识别 (Tesseract)
        TessBaseAPI tess = new TessBaseAPI();
        tess.init(DATA_PATH, "chi_sim+eng");  // 中文 + 英文
        tess.setImage(croppedPlate);
        String plateNumber = tess.getUTF8Text();
    }
}

7. 二维码导航

java
public class QR_Recognition {
    public static String decodeQR(Bitmap bitmap) {
        // ZXing 多码制解码
        RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
        
        Result result = new MultiFormatReader().decode(binaryBitmap);
        return result.getText(); // 返回二维码内容
    }
}

8. 形状与颜色识别

基于 HSV 色彩空间 + 轮廓几何分析:

java
public class PatternRecognition {
    public static ShapeBeen recognize(Bitmap bitmap) {
        Mat mat = Image_processing.bitmap_mat(bitmap);
        Mat hsv = new Mat();
        Imgproc.cvtColor(mat, hsv, Imgproc.COLOR_BGR2HSV);
        
        // 颜色阈值分割
        Core.inRange(hsv, lowerb, upperb, mask);
        
        // 轮廓分析
        List<MatOfPoint> contours = new ArrayList<>();
        Imgproc.findContours(mask, contours, ...);
        
        for (MatOfPoint contour : contours) {
            double area = Imgproc.contourArea(contour);
            MatOfPoint2f approx = new MatOfPoint2f();
            Imgproc.approxPolyDP(contour2f, approx, ...);
            
            // 几何判定
            if (approx.total() == 3) return SHAPE_TRIANGLE;
            if (approx.total() == 4) return SHAPE_RECTANGLE;
            if (approx.total() > 8)  return SHAPE_CIRCLE;
        }
    }
}

硬件接口

传感器数据采集

传感器数据传输方式
超声波距离 (mm)Socket 二进制帧
光照传感器光照强度 (lx)Socket 二进制帧
码盘里程编码器值Socket 二进制帧
红外传感器障碍检测状态Socket 二进制帧
Zigbee无线传感网数据串口
摄像头视频流RTSP/HTTP

控制指令

java
// 摄像头云台控制
cameraConntrol.cameraMiscControlPostHttp(ip, DECODER_CONTROL, 
    "command=31&onestep=0"); // 预设位1

// 接收小车指令触发 AI 识别
if (mByte[2] == 0xA4) {  // 车牌识别指令
    CarPlate.carTesseract(bitmap, context, ...);
}
if (mByte[2] == 0xA3) {  // 交通灯识别指令
    TrafficLightRecognizer.ColorCheck(bitmap, ...);
}

架构设计模式

策略模式

java
// 消息处理策略接口
public interface IMessageHandlerStrategy {
    void handleMessage(MessageContext context);
}

// 策略实现
public class MainCarStrategy implements IMessageHandlerStrategy { ... }
public class MobileRobotStrategy implements IMessageHandlerStrategy { ... }
public class TargetDetectionStrategy implements IMessageHandlerStrategy { ... }

// 策略工厂
public class MessageHandlerFactory {
    public static IMessageHandlerStrategy create(String type) {
        switch (type) {
            case "main": return new MainCarStrategy();
            case "robot": return new MobileRobotStrategy();
            case "detect": return new TargetDetectionStrategy();
        }
    }
}

异步任务模式

所有 AI 推理均在后台线程执行,避免阻塞 UI:

java
// 车牌识别异步任务
new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... params) {
        return CarPlate.recognize(bitmap, context);
    }
    @Override
    protected void onPostExecute(String result) {
        plateTV.setText(result);
    }
}.execute();

AsyncTask 任务列表

任务文件功能
CarPlateTask后台车牌识别
FireDetectionTask后台火灾检测
PersonDetectionTask后台行人检测
TrafficLightRecognizerTask后台交通灯识别
ShapesDetectionTask后台形状颜色识别
QR_resultTask后台二维码识别
PicTextRecognizerTask后台OCR文字识别

项目结构

code
ACar2024/
├── app/src/main/java/car/bkrc/com/car2024/
│   ├── ActivityView/              # 主界面
│   │   ├── FirstActivity.java    # 主Activity
│   │   └── LoginActivity.java    # 登录
│   ├── FragmentView/              # 功能Fragment
│   │   ├── LeftFragment.java     # 摄像头预览
│   │   ├── RightFragment1.java   # 控制面板
│   │   ├── RightInfraredFragment.java  # 红外数据
│   │   └── RightZigbeeFragment.java    # Zigbee数据
│   ├── Strategy/                  # 策略模式
│   │   ├── MainCarStrategy.java  # 主车策略
│   │   ├── MobileRobotStrategy.java    # 机器人策略
│   │   └── TargetDetectionStrategy.java # 目标检测策略
│   ├── AsyncTaskUtils/            # 异步AI任务
│   │   ├── CarPlateTask.java     # 车牌识别
│   │   ├── FireDetectionTask.java # 火灾检测
│   │   ├── PersonDetectionTask.java   # 行人检测
│   │   ├── ShapesDetectionTask.java   # 形状检测
│   │   └── TrafficLightRecognizerTask.java # 交通灯
│   ├── DataProcessingModule/      # Socket通信
│   │   └── ConnectTransport.java
│   ├── opencv/                    # OpenCV处理
│   │   ├── Image_processing.java  # 图像预处理
│   │   └── function_calls.java    # 功能调用
│   ├── Utils/PicDisposeUtils/     # 视觉算法
│   │   ├── yolov5/tflite/         # YOLOv5 TFLite
│   │   ├── qrrecognition/         # 二维码识别
│   │   ├── licenseplaterecognition/ # 车牌识别
│   │   ├── patternrecognition/    # 图案识别
│   │   ├── FaceDetection/         # 人脸口罩检测
│   │   └── Fire/                  # 火灾检测
│   └── Subject/                   # 运动控制
│       └── Commd.java            # 小车指令
├── OpenCV343/                     # OpenCV库
└── build.gradle

技术栈

层级技术
平台Android (Java)
通信TCP Socket + 串口 (Zigbee)
事件总线EventBus
图像处理OpenCV 3.4.3
目标检测YOLOv5 + TensorFlow Lite
火灾检测TensorFlow 自定义模型
OCRTesseract (chi_sim + eng)
二维码ZXing
视频RTSP + VLC
UIFragment + ViewPager + 自定义View

总结

ACar2024 是一个综合性的嵌入式实训平台,核心技术覆盖:

  1. Socket 实时通信:自定义二进制协议,双向数据传输
  2. 多AI模型融合:YOLOv5 + TensorFlow + Tesseract + ZXing
  3. OpenCV 视觉处理:灰度/滤波/阈值/形态学/轮廓分析
  4. HSV 色彩识别:颜色空间转换 + 阈值分割 + 几何判定
  5. 设计模式:策略模式 + 异步任务 + 事件总线
  6. 硬件接口:摄像头云台 + 超声波 + 红外 + 码盘 + Zigbee

适合作为嵌入式、物联网、Android 开发专业的综合实训教学参考。