Arduino + OpenCV 实时人脸追踪云台系统
组件与物料
| 组件 | 数量 |
|---|---|
| Arduino UNO | 1 |
| USB 摄像头 | 1 |
| 微型舵机 | 2 |
| 云台套件 | 1 |
| 面包板 | 1 |
软件环境
- Python 2.7 (或 3.x 需微调)
- OpenCV (cv2)
- pyserial
- numpy
- Haarcascade 前脸分类器 XML
项目原理
Python + OpenCV 采集摄像头画面,Haarcascade 检测人脸,计算人脸中心坐标,经串口发送给 Arduino,Arduino 驱动两个舵机控制云台水平/垂直旋转,实现人脸自动跟随。
Python 端关键步骤
- 初始化串口 (
serial.Serial('COM5', 9600)) - 加载
haarcascade_frontalface_default.xml - 循环读取帧 → 灰度化 →
detectMultiScale检测人脸 - 取最大人脸,计算中心点
(x+w/2, y+h/2) - 发送协议:
X{center_x}Y{center_y}Z
Python 完整代码
import numpy as np
import serial, time, sys, cv2
arduino = serial.Serial('COM5', 9600)
time.sleep(2)
print("Connected to arduino...")
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
cv2.resizeWindow('img', 500, 500)
# 绘制十字准星
cv2.line(img, (500,250), (0,250), (0,255,0), 1)
cv2.line(img, (250,0), (250,500), (0,255,0), 1)
cv2.circle(img, (250,250), 5, (255,255,255), -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 5)
# 人脸中心
xx = int(x + w/2)
yy = int(y + h/2)
center = (xx, yy)
print("Center of Rectangle is:", center)
data = "X{0:d}Y{1:d}Z".format(xx, yy)
arduino.write(data.encode())
cv2.imshow('img', img)
if cv2.waitKey(30) & 0xff == 27: break
cap.release()
cv2.destroyAllWindows()
Arduino 端代码
#include <Servo.h>
Servo servoVer, servoHor;
int x, y, prevX, prevY;
void setup() {
Serial.begin(9600);
servoVer.attach(5); // 垂直舵机
servoHor.attach(6); // 水平舵机
servoVer.write(90);
servoHor.write(90);
}
void Pos() {
if (prevX != x || prevY != y) {
int servoX = map(x, 600, 0, 70, 179);
int servoY = map(y, 450, 0, 179, 95);
servoX = constrain(servoX, 70, 179);
servoY = constrain(servoY, 95, 179);
servoHor.write(servoX);
servoVer.write(servoY);
}
}
void loop() {
if (Serial.available() > 0) {
if (Serial.read() == 'X') {
x = Serial.parseInt();
if (Serial.read() == 'Y') {
y = Serial.parseInt();
Pos();
}
}
while (Serial.available() > 0) Serial.read(); // 清空缓冲
}
}
接线与调试
- 垂直舵机 → D5,水平舵机 → D6,电源 5V/GND
- 上传 Arduino 代码后关闭 IDE 释放串口
- 运行 Python 脚本,摄像头窗口出现,人脸移动云台跟随
- 将摄像头固定在云台上实现“眼睛”跟随
原理图

制造工艺
- 树莓派与 Python 构建远程温度传感器:分步实战指南
- 树莓派实时人脸识别全流程指南:从硬件到模型训练
- 树莓派 OpenCV 自动视觉跟踪:云台舵机实时锁定彩色目标
- 仅用 Arduino 构建 DTMF 解码器 – 无需额外 IC
- 用 Arduino 打造绚丽显示器 Ambilight 系统
- 基于 Arduino 与 Python 的可靠 RFID 考勤系统
- 用 Arduino 制作超声波悬浮装置:分步指南
- Arduino 与智能手机打造智能电压表——简单易做的 DIY 项目
- 基于 Arduino 与 MAX30100 的实时物联网心率监测系统
- Arduino Uno WiFi 网页服务器:通过浏览器控制 LED 开关
- 用 Python 构建 IoT 温度计:Zerynth 完整指南
- Arduino 自动化 Chrome 恐龙游戏 - LDR 光敏电阻 + Python 实现全自动跳跃