logo

解决人脸识别门禁系统的问题(检测到人脸才会和图库里面的人对比,成功后控制舵机开门)以下是我的代码,希望有大佬帮忙改正

2022-04-25 21:57
V
torx
import sensor, time, image, pyb
from pyb import Servo

m1 = Servo(1)

sensor.reset() # Initialize the camera sensor.
sensor.set_contrast(3)
sensor.set_gainceiling(16)
sensor.set_framesize(sensor.HQVGA)
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_windowing((92,112))
sensor.skip_frames(10) # Let new settings take affect.
sensor.skip_frames(time = 3000) #等待3s

RED_LED_PIN = 1
face_cascade = image.HaarCascade("frontalface", stages=25)

#SUB = "s1"
NUM_SUBJECTS = 3 #图像库中不同人数,一共3人
NUM_SUBJECTS_IMGS = 20 #每人有20张样本图片

pyb.LED(RED_LED_PIN).on()
sensor.skip_frames(time = 3000)

# 拍摄一张照片
img = sensor.snapshot()

pyb.LED(RED_LED_PIN).off()

# Find objects.
# Note: Lower scale factor scales-down the image more and detects smaller objects.
# Higher threshold results in a higher detection rate, with more false positives.
objects = img.find_features(face_cascade, threshold=0.75, scale=1.35)
#image.find_features(cascade, threshold=0.5, scale=1.5),thresholds越大,
#匹配速度越快,错误率也会上升。scale可以缩放被匹配特征的大小。

#在找到的目标上画框,标记出来
for r in objects:
    img.draw_rectangle(r)

if (objects==1):
    print("get people")
#img = image.Image("singtown/%s/1.pgm"%(SUB))
    
    d0 = img.find_lbp((0, 0, img.width(), img.height()))
    #d0为当前人脸的lbp特征
    img = None
    pmin = 999999
    num=0
    
    def min(pmin, a, s):    
        global num
        if a<pmin:
            pmin=a
            num=s
        return pmin
 
    for s in range(1, NUM_SUBJECTS+1):
        dist = 0
        for i in range(2, NUM_SUBJECTS_IMGS+1):
            img = image.Image("singtown/s%d/%d.pgm"%(s, i))
            d1 = img.find_lbp((0, 0, img.width(), img.height()))
            #d1为第s文件夹中的第i张图片的lbp特征
            dist += image.match_descriptor(d0, d1)#计算d0 d1即样本图像与被检测人脸的特征差异度。
        print("Average dist for subject %d: %d"%(s, dist/NUM_SUBJECTS_IMGS))
        pmin = min(pmin, dist/NUM_SUBJECTS_IMGS, s)#特征差异度越小,被检测人脸与此样本更相似更匹配。
        
        if pmin > 7500:
            print("外来访客")
        else:
            for i in range(1000):
                m1.pulse_width(5000 + i)
                time.sleep_ms(5)
            for i in range(1000):
                m1.pulse_width(1000 - i)
                time.sleep_ms(5)
            print(pmin)
            print(num) # num为当前最匹配的人的编号
            print("欢迎回家")
            print(num) # num为当前最匹配的人的编号。
        time.sleep(3)
else:
    print("no people")
    time.sleep(3)