使用Python-opencv3制作简单的人脸识别系统

分享一下自己做这个小程序的笔记!

使用工具:PyCharm,python版本3.7,opencv3
使用的包:
import
原理和功能
使用opencv3调用摄像头,获取图像保存,对保存的图片进行OPENCVLBHP算法训练,利用训练集和分类器实现人脸识别。使用语音模块进行人机交互,使用数据库相关操作保存和读取数据库!

详细设计
由于保存人脸信息和训练集需要文件夹,这里先进行检测环境,如果没有就进行创建。

def makeDir(engine,x):
    if not os.path.exists("face_trainer"):
        print("创建预训练环境")
        engine.say('检测到第一次启动,正在创建预训练环境')
        os.mkdir("face_trainer")
        engine.say('创建成功')
        engine.runAndWait()
        x=2
    if not os.path.exists("Facedata"):
        print("创建训练环境")
        engine.say('正在创建训练环境')
        os.mkdir("Facedata")
        engine.say('创建成功')
        engine.runAndWait()
        x=2
    return x

通过摄像头采集人脸信息

def getFace(cap,face_id):
    face_detector = cv2.CascadeClassifier('./lib/haarcascade_frontalface_default.xml')
    print('\n Initializing face capture. Look at the camera and wait ...')
    count = 0
    while True:
        sucess, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x+w, y+w), (255, 0, 0))
            count += 1
            cv2.imwrite("Facedata/User." + str(face_id) + '.' + str(count) + '.jpg', gray[y: y + h, x: x + w])
            cv2.imshow('image', img)
        # 保持画面的持续。
        k = cv2.waitKey(1)
        if k == 27:   # 通过esc键退出摄像
            break
        elif count >= 1000:  # 得到1000个样本后退出摄像
            break
    cv2.destroyAllWindows()

cv2.CascadeClassifier中加载分类器,使用官方给定的xml分类器进行识别。

接着后面会用到路径有关的读取函数实现如下:

def getImagesAndLabels(path,detector):
        imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
        faceSamples = []
        ids = []
        for imagePath in imagePaths:
            PIL_img = Image.open(imagePath).convert('L')
            img_numpy = np.array(PIL_img, 'uint8'
  • 7
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,以下是一个简单人脸识别系统的操作界面示例,使用Python和Tkinter GUI库: ```python import tkinter as tk from tkinter import filedialog from tkinter import messagebox import cv2 import numpy as np class FaceRecognitionApp: def __init__(self, master): self.master = master self.master.title("人脸识别系统") self.master.geometry("400x300") self.master.resizable(False, False) # 创建控件 self.btn_open_image = tk.Button(self.master, text="打开图像", command=self.open_image) self.btn_detect_face = tk.Button(self.master, text="检测人脸", command=self.detect_face) self.btn_train_model = tk.Button(self.master, text="训练模型", command=self.train_model) self.btn_recognize_face = tk.Button(self.master, text="识别人脸", command=self.recognize_face) self.lbl_image = tk.Label(self.master) self.lbl_status = tk.Label(self.master, text="等待操作...") # 布局控件 self.btn_open_image.pack(pady=10) self.btn_detect_face.pack(pady=10) self.btn_train_model.pack(pady=10) self.btn_recognize_face.pack(pady=10) self.lbl_image.pack(pady=10) self.lbl_status.pack(pady=10) # 初始化变量 self.image_file = None self.image = None self.detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") self.recognizer = cv2.face.LBPHFaceRecognizer_create() def open_image(self): # 打开图像文件 self.image_file = filedialog.askopenfilename(filetypes=[("图像文件", "*.jpg;*.jpeg;*.png")]) if self.image_file: # 显示图像 self.image = cv2.imread(self.image_file) self.show_image(self.image) def detect_face(self): if self.image is None: messagebox.showerror("错误", "请先打开图像!") return # 检测人脸 gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) faces = self.detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) if len(faces) == 0: messagebox.showwarning("警告", "未检测到人脸!") return # 画出人脸框 for (x, y, w, h) in faces: cv2.rectangle(self.image, (x, y), (x + w, y + h), (0, 255, 0), 2) # 显示检测结果 self.show_image(self.image) self.lbl_status.config(text="检测到 %d 个人脸" % len(faces)) def train_model(self): # TODO: 实现训练模型的功能 pass def recognize_face(self): if self.image is None: messagebox.showerror("错误", "请先打开图像!") return if not self.recognizer: messagebox.showerror("错误", "请先训练模型!") return # TODO: 实现识别人脸的功能 pass def show_image(self, image): # 将OpenCV图像格式转换为Tkinter图像格式 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = np.swapaxes(image, 0, 1) image = tk.PhotoImage(master=self.master, data=image.tostring(), width=image.shape[1], height=image.shape[0]) # 显示图像 self.lbl_image.config(image=image) self.lbl_image.image = image def run(self): self.master.mainloop() if __name__ == "__main__": root = tk.Tk() app = FaceRecognitionApp(root) app.run() ``` 这个界面包含四个按钮和两个标签: - 打开图像按钮:用于打开本地的图像文件。 - 检测人脸按钮:用于在打开的图像中检测人脸。 - 训练模型按钮:用于训练人脸识别模型。 - 识别人脸按钮:用于在打开的图像中识别人脸。 - 图像标签:用于显示打开的图像和检测或识别的结果。 - 状态标签:用于显示当前操作的状态信息。 你需要根据自己的需求进一步修改和完善这个界面代码,比如实现训练和识别功能、添加菜单栏和工具栏、美化界面等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值