接下来使用pip命令安装两个库
pip install opencv-python
pip install opencv-contrib-python
如果出现问题:
#若之前添加过,先卸载
pip uninstall opencv-python
pip uninstall opencv-contrib-python
#安装
pip install opencv-python==4.6.0.66
pip install opencv-contrib-python==4.6.0.66
import cv2
# 摄像头开启
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
# cap = cv2.VideoCapture('picture/arti.mp4')
flag = 1
num = 1
while cap.isOpened(): # 检测是否在开启状态
ret_flag, Vshow = cap.read() # 得到每帧图像
cv2.imshow("Capture_Test", Vshow) # 显示图像
k = cv2.waitKey(1) & 0xFF # 按键判断
if k == ord('s'): # 按s键保存
# 图片保存路径可自己设定,取名方式也可以自己拟定
cv2.imwrite("C:/Users/86183/Desktop/Test/" + str(num) + ".arti" + ".jpg", Vshow)
print("success to save" + str(num) + ".jpg")
print("---------------")
num += 1
elif k == ord(' '): # 按空格键退出
break
# 释放摄像头
cap.release()
# 释放内容
cv2.destroyAllWindows()
3.** 写一个数据训练的py小程序,创建一个文件夹并在文件夹内创建一个.yml文件**
import os.path
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)]
# 加载分类器,需要到前面安装的opencv的库里面去查找对应的xml文件
face_detector = cv2.CascadeClassifier('E:/opencv/opencv-4.6.0/data/haarcascades/haarcascade_frontalface_alt2.xml')
# 遍历列表中的图片
for imagePath in imagePaths:
# 打开图片,灰度变化 PIL 有九种不同的模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F.
PIL_img = Image.open(imagePath).convert('L')
# 将图片转换成数组,以黑白深浅
img_numpy = np.array(PIL_img, 'uint8')
# 获取图片人脸特征
faces = face_detector.detectMultiScale(img_numpy)
# 获取每张图片的id和姓名
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])
# 打印脸部特征和id
print('id:', id)
print('fs:', facesSamples)
return facesSamples, ids
if __name__ == '__main__':
# 要提取特征的图片路径
path = 'C:/Users/86183/Desktop/Test/'
# 获取图片数组和id标签数组和姓名
faces, ids = getImageAndLabels(path)
# 加载识别器
recognizer = cv2.face.LBPHFaceRecognizer_create()
# 训练
recognizer.train(faces, np.array(ids))
# 保存文件
recognizer.write('trainer/trainer.yml')
import cv2
import numpy as np
import os
# coding=utf-8
import urllib
import urllib.request
import hashlib
# 加载训练数据集文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/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) # 转换为灰度
# 加载分类器,需要到前面安装的opencv的库里面去查找对应的xml文件
face_detector = cv2.CascadeClassifier('E:/opencv/opencv-4.6.0/data/haarcascades/haarcascade_frontalface_alt2.xml')
face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300))
# face=face_detector.detectMultiScale(gray)
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])
# print('标签id:',ids,'置信评分:', confidence)
if confidence > 80:
global warningtime
warningtime += 1
if warningtime > 100:
warning()
warningtime = 0
cv2.putText(img, 'unkonw', (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)
# print('bug:',ids)
def name():
# 读取识别人物名称【最好是英文,中文可能出现乱码】
path = 'data/test'
# names = []
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('picture/hcx.mp4')
name()
while True:
flag, frame = cap.read()
if not flag:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(1):
break
cv2.destroyAllWindows()
cap.release()
# print(names)
流程为:配置环境,安装好需要的包——>保存图片——>进行数据训练提取人物特征,将数据保存到.yml文件中——>根据提取出来的人物特征进行视频分析识别人物