拿到Jetson Nano开发板的第一件事就是给它"通电开机"。这块板子虽然只有信用卡大小,但五脏俱全,是典型的边缘计算设备。我用的4GB版本,实测下来性能足够跑Yolov5这类轻量级模型。先说说供电方案,官方推荐三种方式:
第一种是Micro USB供电,适合临时调试。但要注意必须拔掉J48跳线帽,否则可能供电不足导致系统不稳定。我实测用5V/2A的手机充电器能启动,但跑模型时容易崩溃,强烈不建议长期使用。
第二种是DC电源接口供电,需要5V/4A的电源适配器。这是最稳定的方案,记得插上J48跳线帽。我在某宝买的官方推荐型号,连续运行72小时没出过问题。
第三种是GPIO引脚供电,适合有扩展板的场景。不过新手容易接错线烧毁板子,建议等熟悉硬件后再尝试。
烧录系统镜像推荐使用Etcher工具,比官方方法简单得多。下载好JetPack镜像后(目前最新是4.6.1版本),选择SD卡直接烧录。有个坑要注意:SD卡最好用64GB以上的高速卡(U3/V30级别),低速卡会导致系统卡顿。我试过用32GB普通卡,运行apt-get时经常卡死。
首次启动会进入Ubuntu初始化界面,建议选择英文系统语言。不是崇洋媚外,而是中文环境可能遇到路径编码问题,后期配置环境时容易踩坑。时区选Asia/Shanghai,用户名和密码简单好记就行,反正不会拿它当主力机用。
联网方面,有线连接最稳定。如果要用WiFi,建议购买官方认证的无线网卡(如AC8265)。某次我用杂牌网卡,编译时频繁断网,浪费了一整天时间。
Jetson Nano默认的apt源在国外,速度慢得像蜗牛。换成国内源是必操作,我习惯用清华源:
bash复制sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo sed -i "s@http://.*archive.ubuntu.com@https://mirrors.tuna.tsinghua.edu.cn@g" /etc/apt/sources.list
sudo sed -i "s@http://.*security.ubuntu.com@https://mirrors.tuna.tsinghua.edu.cn@g" /etc/apt/sources.list
sudo apt update
CUDA环境变量要特别注意版本匹配。先用ls /usr/local查看CUDA目录名,我这里是cuda-10.2。然后在~/.bashrc末尾添加:
bash复制export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
测试CUDA是否正常:
bash复制cd /usr/src/cudnn_samples_v8/mnistCUDNN
sudo make
./mnistCUDNN
看到"Test passed!"说明GPU加速生效。如果报错,八成是环境变量没配好。
系统自带Python3.6,但pip需要手动升级:
bash复制sudo apt install python3-pip
pip3 install --upgrade pip
安装常用科学计算库时,记得用apt装系统版本,比pip安装更稳定:
bash复制sudo apt install python3-numpy python3-scipy python3-matplotlib
TensorFlow的安装有个大坑:必须用NVIDIA定制版。直接pip install tensorflow会报错。正确姿势是:
bash复制pip3 install --extra-index-url https://developer.download.nvidia.com/compute/redist/jp/v42 tensorflow-gpu==1.13.1+nv19.3
验证TF是否能用GPU:
python复制import tensorflow as tf
tf.test.is_gpu_available() # 应该返回True
首先克隆tensorrtx项目(注意选择与Yolov5匹配的版本):
bash复制git clone -b yolov5-v5.0 https://github.com/wang-xinyu/tensorrtx.git
将训练好的.pt模型转.wts格式:
python复制import torch
model = torch.load('yolov5s.pt')
with open('yolov5s.wts', 'w') as f:
f.write('{}\n'.format(len(model.state_dict().keys())))
for k, v in model.state_dict().items():
vr = v.reshape(-1).cpu().numpy()
f.write('{} {} '.format(k, len(vr)))
for vv in vr:
f.write(' ')
f.write(struct.pack('>f', float(vv)).hex())
f.write('\n')
编译生成推理引擎:
bash复制cd tensorrtx/yolov5
mkdir build && cd build
cmake ..
make
sudo ./yolov5 -s ../yolov5s.wts yolov5s.engine s
这里有几个关键参数:
s表示使用yolov5s模型结构(还有m/l/x等尺寸)生成引擎时可能遇到内存不足的问题。我的解决方法是:
sudo systemctl set-default multi-user.target用OpenCV做视频流推理的示例代码:
python复制import cv2
from trt_infer import YoLov5TRT # 自定义的TRT推理类
trt_model = YoLov5TRT("yolov5s.engine")
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
boxes, scores, classes = trt_model.infer(frame)
for box, score, cls in zip(boxes, scores, classes):
x1, y1, x2, y2 = map(int, box)
cv2.rectangle(frame, (x1,y1), (x2,y2), (0,255,0), 2)
cv2.putText(frame, f"{cls}:{score:.2f}", (x1,y1-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
cv2.imshow("YOLOv5 TRT", frame)
if cv2.waitKey(1) == ord('q'):
break
实测在640x640输入下,4GB版Jetson Nano的推理速度能达到15-20FPS。如果改用384x384输入,帧率可提升到30FPS以上,但精度会有所下降。
Jetson Nano的4GB内存是共享的(GPU+CPU),需要精细管理:
sudo tegrastats监控内存使用cv2.setNumThreads(1)长时间运行会导致CPU降频,我的散热方案组合:
bash复制watch -n 1 "cat /sys/devices/virtual/thermal/thermal_zone*/temp"
如果帧率不达标,可以尝试:
bash复制sudo ./yolov5 -s ../yolov5s.wts yolov5s_fp16.engine s fp16
使用Python的threading模块实现采集+推理双线程:
python复制from threading import Thread
import queue
frame_queue = queue.Queue(maxsize=2)
def capture_thread(cap):
while True:
ret, frame = cap.read()
if not ret: continue
if frame_queue.full():
frame_queue.get()
frame_queue.put(frame)
def infer_thread(model):
while True:
if not frame_queue.empty():
frame = frame_queue.get()
results = model.infer(frame)
# 显示逻辑...
cap = cv2.VideoCapture(0)
Thread(target=capture_thread, args=(cap,)).start()
Thread(target=infer_thread, args=(trt_model,)).start()
这套方案在我的垃圾分类项目中,让FPS从18提升到了25。关键是要控制队列长度,避免内存堆积。