MaixCam二维云台检测人脸项目
思路
1maixcampro检测人脸(这个可以用开源的或者AI试试)返回人脸的坐标能够跟踪
2用stm32接收到maixcampro通过串口发送的数据,然后控制双云台舵机转向
演示
人脸跟踪-CSDN直播
源代码:
maixcampro
.py
from maix import camera, display, image,nn,uart,time# 初始化串口通信,波特率常用 115200
uart = uart.UART("/dev/serial0", 115200)# 初始化摄像头和显示
cam = camera.Camera(320, 240, format=image.Format.FMT_RGB888) # 使用RGB888格式,模型可能需要特定格式
dis = display.Display()# 加载内置的人脸检测模型
# 请根据MaixCAM Pro实际内置的模型路径进行调整,例如可能是 "/root/models/face_detector.mud"
# 以下使用一个假设的模型路径,您需要确认或替换为正确的模型路径
face_detector = nn.YOLOv8(model="/root/models/yolov8n_face.mud", dual_buff = True) # 请替换为实际模型路径# 如果没有现成的模型,可能需要从MaixHub下载并加载
# 例如: face_detector = nn.load("/sd/face_model.kmodel") 如果模型在SD卡上# 主循环
while True:img = cam.read() # 读取一帧图像# 进行人脸检测# 模型的输入输出格式需根据具体模型确定,这里假设使用常见的yolov8-face或类似模型faces = face_detector.detect(img, conf_th=0.5, iou_th=0.45) # 置信度阈值和IOU阈值可根据需要调整# 处理检测到的人脸for face in faces:# 获取人脸框坐标x, y, w, h = face.x, face.y, face.w, face.h# 在图像上绘制矩形框框出人脸img.draw_rect(x, y, w, h, image.COLOR_RED, thickness=2)# 计算人脸中心点坐标center_x = x + w // 2center_y = y + h // 2# 在中心点绘制一个小圆点img.draw_circle(center_x, center_y, 3, image.COLOR_RED, thickness=-1)# 通过串口发送中心点坐标数据# 格式可以自定义,例如: "x,y"uart_data = f"@{center_x},{center_y}$"print(uart_data)uart.write(uart_data.encode())# 显示图像dis.show(img)# 短暂延时,控制循环频率time.sleep_ms(80) # 可根据实际帧率需求调整# 释放资源 (通常不会执行到这里,因为循环是无限的)
face_detector.close()
uart.close()
stm32中
main.c
这里比较麻烦的就是解析串口发过来的人脸坐标数据
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Serial.h"
#include "Servo.h"
uint16_t angle;
uint8_t First_time;
void test()
{uint8_t x= 0;while(x!=180){Servo_SetAngle_2(x);x+=10;Delay_ms(200);}
}
int main(void)
{Key_Init();OLED_Init();Serial_Init();Servo_init();OLED_ShowString(1,1,"RxData:");Servo_SetAngle_1(90);Servo_SetAngle_2(90);while (1){if(Serial_GetRxFlag()==1){//处理字符串数据uint16_t x = 0;uint16_t y = 0;uint8_t i = 0;char tmp[10];while(Serial_RxPacket[i]!=','){tmp[i]=Serial_RxPacket[i];i++;}if(i==1){x = tmp[0]-'0';}else if(i==2){x = (tmp[0]-'0')*10 + (tmp[1]-'0');}else if(i==3){x = (tmp[0]-'0')*100 + (tmp[1]-'0')*10+(tmp[2]-'0');}i++;uint8_t m = 0;while(Serial_RxPacket[i+m]!='\0'){tmp[m]=Serial_RxPacket[i+m];m++;}if(m==1){y = tmp[0]-'0';}else if(m==2){y = (tmp[0]-'0')*10 + (tmp[1]-'0');}else if(m==3){y = (tmp[0]-'0')*100 + (tmp[1]-'0')*10+(tmp[2]-'0');}OLED_ShowNum(3,1,x,3);OLED_ShowNum(3,5,y,3);if(First_time==1){Face_Tracking_Control(x,y);}if(First_time==0){Delay_ms(1000);First_time = 1;}}}
}
Servo.c
这里面通过PID来调整舵机的转动
注意这个比例系数需要从小开始一步一步调整,要不然人脸刚刚移动一点,这个舵机直接就转到底部了
#include "PWM.h"
#include "stdlib.h"
void Servo_init()
{PWM_Init();
}
void Servo_SetAngle_1(float Angle)
{PWM_SetCompare1(Angle / 180.0 * 2000 + 500); //设置占空比//将角度线性变换,对应到舵机要求的占空比范围上
}
void Servo_SetAngle_2(float Angle)
{PWM_SetCompare2(Angle / 180.0 * 2000 + 500); //设置占空比//将角度线性变换,对应到舵机要求的占空比范围上
}// 全局变量存储当前舵机角度
float current_pan_angle = 90.0f; // 水平舵机初始90度 (正前方)
float current_tilt_angle = 90.0f; // 垂直舵机初始90度 (正前方)// 比例系数,需要根据实际效果调试
const float Kp_pan = 0.08f; // 水平方向比例系数
const float Kp_tilt = 0.08f; // 垂直方向比例系数// 图像中心坐标 (320x240)
#define IMAGE_CENTER_X 160
#define IMAGE_CENTER_Y 120// 死区阈值,小于此值的误差忽略,防止微小抖动
#define ERROR_DEAD_ZONE 15/*** @brief 人脸追踪控制函数* @param face_x: 人脸中心X坐标* @param face_y: 人脸中心Y坐标* @retval 无*/
void Face_Tracking_Control(int face_x, int face_y) {int error_x, error_y;float delta_pan, delta_tilt;// 1. 计算误差error_x = face_x - IMAGE_CENTER_X;error_y = face_y - IMAGE_CENTER_Y;// 2. 死区处理if (abs(error_x) < ERROR_DEAD_ZONE) error_x = 0;if (abs(error_y) < ERROR_DEAD_ZONE) error_y = 0;// 3. P控制计算角度增量delta_pan = -Kp_pan * error_x; // 注意正负号,取决于舵机安装方向delta_tilt = Kp_tilt * error_y;// 4. 更新角度current_pan_angle += delta_pan;current_tilt_angle += delta_tilt;// 5. 限幅,确保角度在0-180度范围内current_pan_angle = (current_pan_angle > 180.0f) ? 180.0f : (current_pan_angle < 0.0f) ? 0.0f : current_pan_angle;current_tilt_angle = (current_tilt_angle > 180.0f) ? 180.0f : (current_tilt_angle < 0.0f) ? 0.0f : current_tilt_angle;// 6. 设置舵机角度Servo_SetAngle_1(current_pan_angle); // 水平舵机Servo_SetAngle_2(current_tilt_angle); // 垂直舵机
}
PWM.c
#include "stm32f10x.h" // Device headervoid PWM_Init(void)
{//开启时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//初始化GPIOGPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);//配置时钟源TIM_InternalClockConfig(TIM2);//配置时基单元TIM_TimeBaseInitTypeDef TIM_TimBaseInitStructure;TIM_TimBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimBaseInitStructure.TIM_Period = 20000-1;//20ms的周期,那么频率为50hzTIM_TimBaseInitStructure.TIM_Prescaler = 72-1;TIM_TimBaseInitStructure.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM2,&TIM_TimBaseInitStructure);//初始化输出比较单元TIM_OCInitTypeDef TIM_OCInitStructure;TIM_OCStructInit(&TIM_OCInitStructure);TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;TIM_OCInitStructure.TIM_Pulse = 0;TIM_OC1Init(TIM2,&TIM_OCInitStructure);TIM_OC2Init(TIM2,&TIM_OCInitStructure);TIM_OC1PreloadConfig(TIM2,TIM_OCPreload_Enable);TIM_OC2PreloadConfig(TIM2,TIM_OCPreload_Enable);TIM_Cmd(TIM2,ENABLE);}
//1是控制下层舵机,2是控制上层舵机,但是舵机的输入应为20-180(上层没有那么大的角度)
void PWM_SetCompare1(uint16_t compare)
{TIM_SetCompare1(TIM2,compare);
}
void PWM_SetCompare2(uint16_t compare)
{TIM_SetCompare2(TIM2,compare);
}
Serial.c
#include "stm32f10x.h" // Device header
#include <stdio.h>
#include <stdarg.h>
#include "string.h"uint8_t Serial_RxFlag;
char Serial_RxPacket[20];/*** 函 数:串口初始化* 参 数:无* 返 回 值:无*/
void Serial_Init(void)
{/*开启时钟*/RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); //开启USART1的时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //开启GPIOA的时钟/*GPIO初始化*/GPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIO_InitStructure); //将PA9引脚初始化为复用推挽输出GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIO_InitStructure); //将PA10引脚初始化为上拉输入/*USART初始化*/USART_InitTypeDef USART_InitStructure; //定义结构体变量USART_InitStructure.USART_BaudRate = 115200; //波特率USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //硬件流控制,不需要USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; //模式,发送模式和接收模式均选择USART_InitStructure.USART_Parity = USART_Parity_No; //奇偶校验,不需要USART_InitStructure.USART_StopBits = USART_StopBits_1; //停止位,选择1位USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长,选择8位USART_Init(USART1, &USART_InitStructure); //将结构体变量交给USART_Init,配置USART1/*中断输出配置*/USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //开启串口接收数据的中断/*NVIC中断分组*/NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //配置NVIC为分组2/*NVIC配置*/NVIC_InitTypeDef NVIC_InitStructure; //定义结构体变量NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //选择配置NVIC的USART1线NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //指定NVIC线路使能NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //指定NVIC线路的抢占优先级为1NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //指定NVIC线路的响应优先级为1NVIC_Init(&NVIC_InitStructure); //将结构体变量交给NVIC_Init,配置NVIC外设/*USART使能*/USART_Cmd(USART1, ENABLE); //使能USART1,串口开始运行
}/*** 函 数:串口发送一个字节* 参 数:Byte 要发送的一个字节* 返 回 值:无*/
void Serial_SendByte(uint8_t Byte)
{USART_SendData(USART1, Byte); //将字节数据写入数据寄存器,写入后USART自动生成时序波形while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); //等待发送完成/*下次写入数据寄存器会自动清除发送完成标志位,故此循环后,无需清除标志位*/
}/*** 函 数:串口发送一个数组* 参 数:Array 要发送数组的首地址* 参 数:Length 要发送数组的长度* 返 回 值:无*/
void Serial_SendArray(uint8_t *Array, uint16_t Length)
{uint16_t i;for (i = 0; i < Length; i ++) //遍历数组{Serial_SendByte(Array[i]); //依次调用Serial_SendByte发送每个字节数据}
}/*** 函 数:串口发送一个字符串* 参 数:String 要发送字符串的首地址* 返 回 值:无*/
void Serial_SendString(char *String)
{uint8_t i;for (i = 0; String[i] != '\0'; i ++)//遍历字符数组(字符串),遇到字符串结束标志位后停止{Serial_SendByte(String[i]); //依次调用Serial_SendByte发送每个字节数据}
}/*** 函 数:次方函数(内部使用)* 返 回 值:返回值等于X的Y次方*/
uint32_t Serial_Pow(uint32_t X, uint32_t Y)
{uint32_t Result = 1; //设置结果初值为1while (Y --) //执行Y次{Result *= X; //将X累乘到结果}return Result;
}/*** 函 数:串口发送数字* 参 数:Number 要发送的数字,范围:0~4294967295* 参 数:Length 要发送数字的长度,范围:0~10* 返 回 值:无*/
void Serial_SendNumber(uint32_t Number, uint8_t Length)
{uint8_t i;for (i = 0; i < Length; i ++) //根据数字长度遍历数字的每一位{Serial_SendByte(Number / Serial_Pow(10, Length - i - 1) % 10 + '0'); //依次调用Serial_SendByte发送每位数字}
}/*** 函 数:使用printf需要重定向的底层函数* 参 数:保持原始格式即可,无需变动* 返 回 值:保持原始格式即可,无需变动*/
int fputc(int ch, FILE *f)
{Serial_SendByte(ch); //将printf的底层重定向到自己的发送字节函数return ch;
}/*** 函 数:自己封装的prinf函数* 参 数:format 格式化字符串* 参 数:... 可变的参数列表* 返 回 值:无*/
void Serial_Printf(char *format, ...)
{char String[100]; //定义字符数组va_list arg; //定义可变参数列表数据类型的变量argva_start(arg, format); //从format开始,接收参数列表到arg变量vsprintf(String, format, arg); //使用vsprintf打印格式化字符串和参数列表到字符数组中va_end(arg); //结束变量argSerial_SendString(String); //串口发送字符数组(字符串)
}/*** 函 数:获取串口接收数据包标志位* 参 数:无* 返 回 值:串口接收数据包标志位,范围:0~1,接收到数据包后,标志位置1,读取后标志位自动清零*/
uint8_t Serial_GetRxFlag(void)
{if (Serial_RxFlag == 1) //如果标志位为1{Serial_RxFlag = 0;return 1; //则返回1,并自动清零标志位}return 0; //如果标志位为0,则返回0
}/*** 函 数:USART1中断函数* 参 数:无* 返 回 值:无* 注意事项:此函数为中断函数,无需调用,中断触发后自动执行* 函数名为预留的指定名称,可以从启动文件复制* 请确保函数名正确,不能有任何差异,否则中断函数将不能进入*/
void USART1_IRQHandler(void)
{static uint8_t RxState = 0;static uint8_t pRxPacket = 0;if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET){uint8_t RxData = USART_ReceiveData(USART1);if(RxState == 0)//这里可能会有这个数组里面存在两次的数据(搞混了, 太快导致){if(RxData == '@' && Serial_RxFlag == 0){RxState = 1;pRxPacket = 0;}}else if(RxState == 1 && RxData!='$'){Serial_RxPacket[pRxPacket] = RxData;pRxPacket++;}else if(RxState == 1 && RxData=='$'){Serial_RxPacket[pRxPacket]='\0';Serial_RxFlag = 1;RxState = 0;pRxPacket = 0;}}
}