赞
踩
开始前先导入必要的库,在conda中用 pip install package 指令安装。
- import cv2
- import numpy as np
- import os
- import shutil
- import threading
- import tkinter as tk
- from PIL import Image, ImageTk
注意在运行时可能会出现AttributeError: module ‘cv2‘ has no attribute ‘face‘的报错,需要用
pip install opencv-python
安装一个 opencv-python的包,如果此时还是无法运行,需要重新安装这两个包。
- pip uninstall opencv-python
- pip uninstall opencv-contrib-python
- pip install opencv-python
- pip install opencv-contrib-python
接下来用字典对存储关系键值对,再记录录入共计的人脸。
- id_dict = {}
- Total_face_num = 999
将config文件的信息存入字典中
- def init():
- f = open('config.txt')
- global Total_face_num
- Total_face_num = int(f.readline())
-
- for i in range(int(Total_face_num)):
- line = f.readline()
- id_name = line.split(' ')
- id_dict[int(id_name[0])] = id_name[1]
- f.close()
加载检测器Haar和识别方法LBPH,接下来打开摄像头,并读取照片
- face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
- recognizer = cv2.face.LBPHFaceRecognizer_create()
-
-
- camera = cv2.VideoCapture(0)
- success, img = camera.read()
- W_size = 0.1 * camera.get(3)
- H_size = 0.1 * camera.get(4)
-
- system_state_lock = 0 # 相当于mutex锁,用于线程同步
二、录入人脸
- def Get_new_face():
- filepath = "data"
- if not os.path.exists(filepath):
- os.mkdir(filepath)
- else:
- shutil.rmtree(filepath)
- os.mkdir(filepath)
-
- sample_num = 0
- while True:
- global success
- global img
- success, img = camera.read()
-
- # 转为灰度图片
- if success is True:
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- else:
- break
-
- faces = face_cascade.detectMultiScale(gray, 1.3, 5)
- for (x, y, w, h) in faces:
- cv2.rectangle(img, (x, y), (x + w, y + w), (255, 0, 0))
- sample_num += 1
- T = Total_face_num
- cv2.imwrite("./data/User." + str(T) + '.' + str(sample_num) + '.jpg', gray[y:y + h, x:x + w])
-
- pictur_num = 1000 # 表示摄像头拍摄取样的数量,越多效果越好,但获取以及训练的越慢
-
- cv2.waitKey(1)
- if sample_num > pictur_num:
- break
- else:
- l = int(sample_num / pictur_num * 50)
- r = int((pictur_num - sample_num) / pictur_num * 50)
- print("\r" + "%{:.1f}".format(sample_num / pictur_num * 100) + "=" * l + "->" + "_" * r, end="")
- var.set("%{:.1f}".format(sample_num / pictur_num * 100)) # 控件可视化进度信息
- window.update()
创建一个函数,用于从数据集文件夹中获取训练图片并获取id
- def get_images_and_labels(path):
- image_paths = [os.path.join(path, f) for f in os.listdir(path)]
- face_samples = []
- ids = []
-
- for image_path in image_paths:
-
- img = Image.open(image_path).convert('L')
- img_np = np.array(img, 'uint8')
- if os.path.split(image_path)[-1].split(".")[-1] != 'jpg':
- continue
- id = int(os.path.split(image_path)[-1].split(".")[1]) # 为了获取id,将图片和路径分裂并获取
-
- # 调用熟悉的人脸分类器
- detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
-
- faces = detector.detectMultiScale(img_np)
-
- # 将获取的图片和id添加到list中
- for (x, y, w, h) in faces:
- face_samples.append(img_np[y:y + h, x:x + w])
- ids.append(id)
- return face_samples, ids
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。