python机器学习——实现简单的人脸识别

import cv2


cap=cv2.VideoCapture(0) #使用摄像头

#设置人脸分类器  haarcasecades
classfier=cv2.CascadeClassifier('D:\\python+selenium\\anaconda3\\pkgs\\libopencv-3.4.2-h20b85fd_0\\Library\\etc\\haarcascades\\haarcascade_frontalface_alt.xml')

count=0
while cap.isOpened():
    # print('摄像头开启成功')
    ret,frame=cap.read() #读取一帧数据
    if not ret:
        exit(-1)

    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #转化为灰度图片

    #人脸检测
    faceRects=classfier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32,32))
    # fps=1/time.time()-time_start
    if len(faceRects)>0:
        for faceRect in faceRects:
            x, y, w, h = faceRect
            count+=1
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)  # 在图片上画框
            
            #识别到的人脸保存在data文件夹中
            cv2.imwrite('data/'+str(count)+'.jpg',gray[y:y+h,x:x+w])


    cv2.putText(frame,'123456',(10,10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2) #文本显示
    # cv2.rectangle(frame, (x, y), (x+h, y+w), (255, 0, 0), 2)  # 在图片上画框
    cv2.imshow('cam',frame) #图像在窗口显示

    key=cv2.waitKey(30)&0xff #等待事件
    if key==27: #ESC键,循环结束
        exit(0)
  
print('error')

cap.release()
cv2.destroyWindow()

你可能感兴趣的:(python,python,人脸识别,opencv)