安装OpenCV(具体步骤可参考上一篇文章)
常规更新一下
sudo apt-get update
sudo apt-get upgrade
接下来就是漫长的装库过程了
sudo apt-get install build-essential \
cmake \
gfortran \
git \
wget \
curl \
graphicsmagick \
libgraphicsmagick1-dev \
libatlas-base-dev \
libavcodec-dev \
libavformat-dev \
libboost-all-dev \
libgtk2.0-dev \
libjpeg-dev \
liblapack-dev \
libswscale-dev \
libv4l-dev \
pkg-config \
python3-dev \
python3-numpy \
python3-pip \
zip
接下来就是编译过程
首先新建一个文件夹dataset 用于存放人脸图片 创建第一个Python文本,目的是对人脸进行检测和储存
import cv2
import os
cam = cv2.VideoCapture(0)
cam.set(3, 640) # width
cam.set(4, 480) # height
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, enter one numeric face id
face_id = input('\n enter user id end press <return> ==> ')
print("\n Initializing face capture \n Look the camera and wait ...")
count = 0
while(True):
ret, img = cam.read()
#img = cv2.flip(img, -1)
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+h), (255,0,0), 2)
count += 1
# Save the captured image into the dataset folder
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
cv2.imshow('camera', img)
k = cv2.waitKey(100) & 0xff
if k == 27:
break
elif count >= 50: # Take 50 face sample and stop video
break
print("\n Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
这里用到了一个haarcascade_frontalface_default.xml ,我会放在最后的百度网盘里
再新建一个文件夹trainer 用于存放数据 没有PIL 的兄弟们可以用pip安装一下,下面会用到
pip3 install pillow
创建第二个Python文本,目的是将储存的人脸图片转换成数据库
import cv2
import numpy as np
from PIL import Image
import os
# Path for face image database
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def getImagesAndLabels(path):
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') # convert it to grayscale
img_numpy = np.array(PIL_img,'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)
for (x,y,w,h) in faces:
faceSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return faceSamples,ids
print ("\n Training faces \n It will take a few seconds \n Please wait...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# Save the model into 'trainer/trainer.yml'
recognizer.save('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
# Print the numer of faces trained and end program
print("\n {0} faces trained \n Exiting Program".format(len(np.unique(ids))))
创建第三个Python文本,作用是将人脸识别出来
import cv2
import numpy as np
import os
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
#iniciate id counter
id = 0
# names related to ids: example ==> Marcelo: id=1, etc
names = ['zero', 'one', 'two', 'three', 'four', 'five']
cam = cv2.VideoCapture(0)
cam.set(3, 640) # widht
cam.set(4, 480) # height
# Define min window size to be recognized as a face
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
while True:
ret, img =cam.read()
#img = cv2.flip(img, -1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor = 1.2,
minNeighbors = 5,
flags = 0,
minSize = (int(minW), int(minH))
)
for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
# Check if confidence is less them 100 ==> "0" is perfect match
if (confidence < 70):
id = names[id]
confidence = " {0}%".format(round(100 - confidence))
else:
id = "unknown"
confidence = " {0}%".format(round(100 - confidence))
cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)
cv2.imshow('camera',img)
k = cv2.waitKey(10) & 0xff
if k == 27:
break
print("\n Exiting Program and cleanup stuff")
cam.release()
下面是我编译好的代码库,大家可以参考学习 链接:
https://pan.baidu.com/s/1HTfyYWPwifJDaVN5D6ykTQ
提取码:
cv22
|