import sensor
import time
import image
重置传感器
sensor.reset()
传感器设置优化
sensor.set_contrast(1) # 对比度设置
sensor.set_gainceiling(16) # 增益上限
sensor.set_framesize(sensor.HQVGA) # 320x240分辨率
sensor.set_pixformat(sensor.GRAYSCALE) # 灰度图像
加载内置Haar级联
face_cascade = image.HaarCascade("/rom/haarcascade_frontalface.cascade", stages=25)
eyes_cascade = image.HaarCascade("/rom/haarcascade_eye.cascade", stages=24)
print("使用内置级联器:", eyes_cascade)
FPS时钟
clock = time.clock()
参数调试变量
current_eye_threshold = 0.2 # 眼睛检测阈值
current_eye_scale = 1.1 # 眼睛检测缩放因子
current_face_threshold = 0.1 # 人脸检测阈值
current_face_scale = 1.5 # 人脸检测缩放因子
while True:
clock.tick()
img = sensor.snapshot()
# 图像预处理 - 增强眼睛特征
# 1. 自适应直方图均衡化 - 增强对比度
img = img.histeq(adaptive=True, clip_limit=2.0)
# 2. 高斯模糊 - 减少噪声
img = img.gaussian(1)
# 人脸检测
faces = img.find_features(
face_cascade,
threshold=current_face_threshold,
scale_factor=current_face_scale
)
detected_eyes = 0
for face in faces:
img.draw_rectangle(face)
# 优化眼睛检测区域 - 适应眼镜情况
eye_roi = (
face[0] + int(face[2]*0.1), # 左右各留10%边界
face[1] + int(face[3]*0.25), # 从顶部25%开始(避开眼镜上框)
int(face[2]*0.8), # 宽度减少20%
int(face[3]*0.35) # 高度为面部的35%(聚焦眼睛区域)
)
# 绘制眼睛ROI区域(调试用)
img.draw_rectangle(eye_roi, color=(0, 255, 0))
# 眼睛检测参数优化
eyes = img.find_features(
eyes_cascade,
threshold=current_eye_threshold,
scale_factor=current_eye_scale,
roi=eye_roi,
#step_size=1, # 更精细的搜索
# min_size=(10, 10) # 最小眼睛尺寸
)
# 绘制眼睛并添加标签
for e in eyes:
img.draw_rectangle(e, color=(255, 0, 0))
img.draw_string(e[0], e[1]-10, "Eye", color=(255,0,0))
detected_eyes += 1
# 显示调试信息
img.draw_string(0, 0, "FPS:%.1f" % clock.fps(), color=(255,0,0))
img.draw_string(0, 15, "EyeTh:%.2f EyeSc:%.2f" % (current_eye_threshold, current_eye_scale), color=(255,0,0))
img.draw_string(0, 30, "FaceTh:%.2f FaceSc:%.2f" % (current_face_threshold, current_face_scale), color=(255,0,0))
img.draw_string(0, 45, "Eyes:%d" % detected_eyes, color=(255,0,0))