• 正文
  • 相关推荐
申请入驻 产业图谱

树莓派 CM0 NANO+OpenCV,手把手教你做车牌识别系统,附完整代码和模型!

01/07 09:51
454
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

特别感谢文章作者:无垠的广袤 / 李金磊,辛苦制作的教程,非常适合新人及树莓派爱好者学习使用!

项目介绍

准备工作:OpenCV 安装、Ultralytics 软件包安装、预训练模型下载等;

车牌识别:采用 LPRNet 算法及 ONNX 模型实现车牌识别的板端推理;

为了快速实现图像分类,需完成 OpenCV 部署和 Ultralytics 软件包的安装等操作。

准备工作

包括硬件连接、虚拟环境创建、OpenCV 安装、Ultralytics 库部署等。

硬件连接

连接 WiFi 实现无线网络通信;

使用 Type-C 数据线实现设备供电;

OpenCV 安装

OpenCV 是一个开源计算机视觉库,广泛应用于图像处理、视频分析和机器学习等领域。

为了避免影响系统 Python,采用虚拟环境的方案。

创建并激活虚拟环境

mkdir ~/cv && cd ~/cv    # 创建 cv 文件夹,便于管理python3 -m venv venv     # 创建虚拟环境 venvsource venv/bin/activate # 激活虚拟环境 venv

安装 numpy 和 opencv

pip install -U pip numpy                          # 安装 numpypip install opencv-python opencv-contrib-python   # opencv 主模块及 contrib

验证安装

python3 -c "import cv2,sys,numpy;print('OpenCV:',cv2.__version__,'NumPy:',numpy.__version__)"

输出版本号

字体安装

为了方便显示中文车牌,安装 CJK 字体

sudo apt install fonts-noto-cjkfc-list | grep -i "Noto Sans CJK" | head -3

记录字体所在路径,如 /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc 以便调用。

Ultralytics 部署

Ultralytics 基于多年在计算机视觉和人工智能领域的基础研究,打造 YOLO 模型;具有 速度快、精度高、操作简便 等特点。

在目标检测、跟踪、实例分割、图像分类和姿态估计等任务中表现出色。

安装 ultralytics 软件包

sudo apt install python3-dev python3-pip libopenblas-devsudo pip install python3-torchsudo pip install ultralytics --break-system-packages

验证安装

python3 -c "import ultralytics, sys, torch; print('✅ ultralytics', ultralytics.__version__, '| torch', torch.__version__, '| Python', sys.version.split()[0])"

输出相应版本号

详见:https://github.com/ultralytics/ultralytics

 

车牌识别

车牌识别网络(License Plate Recognition Network,LPRNet)是一种专为车牌识别设计的深度学习模型。

它采用端到端的训练方法,能够直接从原始图像中识别出车牌文本,无需进行传统的字符分割步骤。

这种设计使得 LPRNet 在处理车牌识别任务时更加高效和准确,特别是在面对复杂背景或不同国家的车牌样式时。

详见:https://github.com/sirius-ai/LPRNet_Pytorch

模型

下载所需模型文件;

wget https://github.com/h030162/PlateRecognition/blob/main/ocr_rec.pywget https://github.com/h030162/PlateRecognition/blob/main/license_models/dict.txtwget https://github.com/h030162/PlateRecognition/blob/main/license_models/license_ocr.onnxwget https://github.com/h030162/PlateRecognition/blob/main/license_models/y11n-pose_plate_best.onnx

将文件存放在对应路径

license_plate_recognition   ├── img   │   ├── yue.jpg   ├── lpr_onnx.py   ├── model   │   ├── dict.txt   │   ├── license_ocr.onnx   │   └── y11n-pose_plate_best.onnx   └── ocr_rec.py

流程图

代码

终端执行 touch lpr_onnx.py 新建程序文件,并添加如下代码

#!/usr/bin/env python# -*- coding: utf-8 -*-import numpy as npimport cv2from ocr_rec import TextRecognizer, init_argsfrom PIL import Image, ImageDraw, ImageFontfrom ultralytics import YOLOimport warningswarnings.filterwarnings("ignore")# ========== figure ==========#IMG_FILE = "./img/yue.jpg"args = init_args().parse_args()IMG_FILE = args.image_path or './img/test.jpg'   # image path# 使用方法:python lpr_onnx.py --image_path ./img/jing.jpg# =========== class ===========class PlateRecognizer:    def __init__(self, det_model_path="./model/y11n-pose_plate_best.onnx"):        self.model_det = YOLO(det_model_path)        parser = init_args().parse_args()        self.model_ocr = TextRecognizer(parser)    def recognize(self, img):        plate_objs = []        plates = self.model_det(img, verbose=False)        for plate, conf in zip(plates[0].boxes.xyxy, plates[0].boxes.conf):            x1, y1, x2, y2 = map(int, plate.cpu())            plate_img = img[y1:y2, x1:x2]            try:                rec_res, _ = self.model_ocr([plate_img])            except Exception as E:                print(E)                continue            if len(rec_res[0]) > 0:                plate_objs.append({                    'text': rec_res[0][0],                    'score_text': rec_res[0][1],                    'bbox': [x1, y1, x2, y2],                    'score_bbox': conf.cpu().numpy().item()                })        return plate_objsdef DrawPlateNum(img, plate_num, x1, y1):    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    img_pil = Image.fromarray(img_rgb)    draw = ImageDraw.Draw(img_pil)    font = ImageFont.truetype("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 40) # 系统字体    # -------- 优化标签显示,增加填充背景,兼容新版 Pillow ----------------    left, top, right, bottom = draw.textbbox((0, 0), plate_num, font=font)    tw, th = right - left, bottom - top    # 蓝色填充条    draw.rectangle([(x1, y1 - th - 8), (x1 + tw, y1)], fill=(0, 0, 255))   # BGR 蓝色    # 绿色文字    draw.text((x1, y1 - th - 16), plate_num, font=font, fill=(0, 255, 0))   # BGR 绿色    return cv2.cvtColor(np.array(img_pil, dtype=np.uint8), cv2.COLOR_RGB2BGR)# ========== 主程序 ==========def main():    img = cv2.imread(IMG_FILE)    if img is None:        print(f"未找到图片:{IMG_FILE}")        cv2.waitKey(0)        return    recognizer = PlateRecognizer()    plates = recognizer.recognize(img)    for p in plates:        x1, y1, x2, y2 = p['bbox']        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)        img = DrawPlateNum(img, p['text'], x1, y1)        print(f"车牌: {p['text']}  置信度: {p['score_text']:.4f}  框置信度: {p['score_bbox']:.4f}")    cv2.imshow("LPR", img)    cv2.waitKey(0)    cv2.destroyAllWindows()if __name__ == "__main__":    main()

保存代码。

效果

终端执行 python lpr_onnx.py --image_path ./img/yue.jpg 指令,对目标车牌进行识别

终端打印识别到的车牌号、置信度等信息

弹窗显示识别结果

更多测试效果

总结

本文介绍了工业树莓派 CM0 NANO 单板计算机结合 LPRNet 算法和 Ultralytics 库实现车牌识别的项目设计,包括环境搭建、预训练模型、工程代码和效果演示等,为相关产品在边缘 AI 领域的快速开发和应用设计提供了参考。可以通过官方网站下载教程 pdf 完整文件,请关注我们,我们会定期更新教程。edatec.cn/zh/cm0

 

官方网站:https://edatec.cn/zh/cm0

淘宝店铺:https://edatec.taobao.com/

相关推荐