小帽人脸识别
一、环境配置
- Python + Pycharm + opencv
- pip install opencv-python
二、实操
1. 读取图片
import cv2 as cv
img = cv.imread('lq.jpg')
cv.imshow('read_img', img)
cv.waitKey(0)
cv.destroyAllWindows()
2. 灰度转换
import cv2 as cv
img = cv.imread('lq.jpg')
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('gray', gray_img)
cv.imwrite('gray_face.jpg', gray_img)
cv.waitKey(0)
cv.destroyAllWindows()
3. 修改尺寸
import cv2 as cv
img = cv.imread('lq.jpg')
resize_img = cv.resize(img, dsize=(200, 200))
cv.imshow('img', img)
cv.imshow('resize_img', resize_img)
print('未修改:', img.shape)
print('修改后:', resize_img.shape)
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
4. 绘制矩形
import cv2 as cv
img = cv.imread('lq.jpg')
x,y,w,h = 100,100,100,100
cv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=1)
cv.circle(img,center=(x+w,y+h),radius=100,color=(255,0,0),thickness=2)
cv.imshow('re_img', img)
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
5. 人脸检测
import cv2 as cv
def face_detect_demo():
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_alt2.xml')
face = face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img, (x,y), (x+w, y+h), color=(0,0,255), thickness=2)
cv.imshow('result', img)
img = cv.imread('lq.jpg')
face_detect_demo()
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
6. 检测多个
import cv2 as cv
def face_detect_demo():
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_default.xml')
face = face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img, (x,y), (x+w, y+h), color=(0,0,255), thickness=2)
cv.imshow('result', img)
img = cv.imread('multi_face.jpeg')
face_detect_demo()
while True:
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
7. 视频检测
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_default.xml')
face = face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img, (x,y), (x+w, y+h), color=(0,0,255), thickness=2)
cv.imshow('result', img)
cap = cv.VideoCapture(0)
while True:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
cap.release()
8. 拍照保存(信息录入)
import cv2 as cv
def face_detect_demo(img):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detect = cv.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_default.xml')
face = face_detect.detectMultiScale(gray)
for x,y,w,h in face:
cv.rectangle(img, (x,y), (x+w, y+h), color=(0,0,255), thickness=2)
cv.imshow('result', img)
cap = cv.VideoCapture(0)
while True:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord('q') == cv.waitKey(0):
break
cv.destroyAllWindows()
cap.release()
9. 数据训练
import os
import cv2
from PIL import Image
import numpy as np
def getImageAndLabels(path):
facesSamples = []
ids = []
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
face_detector = cv2.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_alt2.xml')
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L')
img_numpy = np.array(PIL_img, 'uint8')
faces = face_detector.detectMultiScale(img_numpy)
id = int(os.path.split(imagePath)[1].split('.')[0])
for x,y,w,h in faces:
ids.append(id)
facesSamples.append(img_numpy[y:y+h,x:x+w])
print('id:', id)
print('fs:', facesSamples)
return facesSamples, ids
if __name__ == '__main__':
path='../data/'
faces, ids = getImageAndLabels(path)
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(faces,np.array(ids))
recognizer.write('trainer.yml')
10. 人脸识别
import cv2
import numpy as np
import os
import urllib
import urllib.request
import hashlib
recogizer=cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer.yml')
names=[]
warningtime = 0
def md5(str):
import hashlib
m = hashlib.md5()
m.update(str.encode("utf8"))
return m.hexdigest()
statusStr = {
'0': '短信发送成功',
'-1': '参数不全',
'-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间',
'30': '密码错误',
'40': '账号不存在',
'41': '余额不足',
'42': '账户已过期',
'43': 'IP地址限制',
'50': '内容含有敏感词'
}
def warning():
smsapi = "http://api.smsbao.com/"
user = '13******10'
password = md5('*******')
content = '【报警】\n原因:检测到未知人员\n地点:xxx'
phone = '*******'
data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})
send_url = smsapi + 'sms?' + data
response = urllib.request.urlopen(send_url)
the_page = response.read().decode('utf-8')
print(statusStr[the_page])
def face_detect_demo(img):
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_detector=cv2.CascadeClassifier('../opencv-4.5.5/data/haarcascades/haarcascade_frontalface_alt2.xml')
face=face_detector.detectMultiScale(gray,1.1,5,cv2.CASCADE_SCALE_IMAGE,(100,100),(300,300))
for x,y,w,h in face:
cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
if confidence > 80:
global warningtime
warningtime += 1
if warningtime > 100:
warning()
warningtime = 0
cv2.putText(img, 'unknown', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
cv2.putText(img,str(names[ids-1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
cv2.imshow('result',img)
def name():
path = '../data/'
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
for imagePath in imagePaths:
name = str(os.path.split(imagePath)[1].split('.',2)[1])
names.append(name)
cap=cv2.VideoCapture(0)
name()
while True:
flag,frame=cap.read()
if not flag:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(10):
break
cv2.destroyAllWindows()
cap.release()