OpenCV图像处理-人脸检测

1.导言

输入:图片;视频(本地,网络,监控摄像头)

处理:人脸(检测,识别);肢体

输出:软件;硬件

2.读取图片

"""
=============================================
    Time     :
    Auther   :
    File     :
    Function : 读取图片
=============================================
"""

# 导入CV模块
import cv2 as cv
# 读取图片
img = cv.imread(r'F:\30_UndergraduateThesis\04_LearningOpencv\MeiXi.png')
# 显示图片
cv.imshow('read_img', img)
# 等待
cv.waitKey(0)
# 释放内存
cv.destroyAllWindows()

3.灰度转换

"""
=============================================
    Time     :
    Auther   : 
    File     :
    Function : 灰度转换
=============================================
"""

# 导入CV模块
import cv2 as cv
# 读取图片
img = cv.imread(r'F:\30_UndergraduateThesis\04_LearningOpencv\MeiXi.png')
# 灰度转换
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 显示灰度图片
cv.imshow('gray_img', gray_img)
# 保存灰度图片
cv.imwrite('gray_face1.jpg', gray_img)
# 显示图片
cv.imshow('read_img', img)
# 等待
cv.waitKey(0)
# 释放内存
cv.destroyAllWindows()

4.尺寸修改

"""
=============================================
    Time     :
    Auther   : 
    File     :
    Function : 尺寸修改
=============================================
"""

# 导入CV模块
import cv2 as cv
# 读取图片
img = cv.imread(r'F:\30_UndergraduateThesis\04_LearningOpencv\MeiXi.png')
# 修改尺寸
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()

5.绘制矩形

"""
=============================================
    Time     :
    Auther   :
    File     :
    Function : 绘制矩形
=============================================
"""

# 导入CV模块
import cv2 as cv
# 读取图片
img = cv.imread(r'F:\30_UndergraduateThesis\04_LearningOpencv\MeiXi.png')
# 坐标
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()

6.人脸检测

"""
=============================================
    Time     :
    Auther   : 
    File     :
    Function : 人脸检测
=============================================
"""

# 导入CV模块
import cv2 as cv
# 检测函数
def face_detect_demo():
    gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_detect = cv.CascadeClassifier(r'D:\14_Anaconda\envs\pytorch1.8\Lib\site-packages\cv2\data\haarcascade_frontalface_alt2.xml')
    face = face_detect.detectMultiScale(gary, 1.01, 5, 0, (100, 100), (300, 300))
    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(r'F:\30_UndergraduateThesis\04_LearningOpencv\MeiXi.png')
# 检测函数
face_detect_demo()
# 等待
while True:
    if ord('q') == cv.waitKey(0):
        break
# 释放内存
cv.destroyAllWindows()

7.视频检测

"""
=============================================
    Time     :
    Auther   :
    File     :
    Function : 视频检测
=============================================
"""

# 导入CV模块
import cv2 as cv
# 检测函数
def face_detect_demo(img):
    gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_detect = cv.CascadeClassifier(r'D:\14_Anaconda\envs\pytorch1.8\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
    face = face_detect.detectMultiScale(gary)
    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()

8.人脸录入

"""
=============================================
    Time     :
    Auther   :
    File     :
    Function : 信息录入
=============================================
"""

# 导入模块
import cv2
# 摄像头
cap = cv2.VideoCapture(0)

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'): # 保存
        cv2.imwrite("F:/30_UndergraduateThesis/03_SaveVideo/"+str(num)+".name"+".jpg", Vshow)
        print("success to save"+str(num)+".jpg")
        print("-------------")
        num += 1
    elif k == ord(" "): # 退出
        break
# 释放摄像头
cap.release()
# 释放内存
cv2.destroyAllWindows()

9.数据训练

"""
=============================================
    Time     :
    Auther   :
    File     :
    Function : 数据训练
=============================================
"""

import os
import cv2 as cv
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 = cv.CascadeClassifier(r'D:\14_Anaconda\envs\pytorch1.8\Lib\site-packages\cv2\data\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 = r'F:\30_UndergraduateThesis\04_LearningOpencv\data'
    # 获取图像数组和id标签组和姓名
    faces, ids = getImageAndLabels(path)
    # 加载识别器
    recognizer = cv.face.LBPHFaceRecognizer.create()
    # 训练
    recognizer.train(faces, np.array(ids))
    # 保存文件
    recognizer.write(r'F:\30_UndergraduateThesis\04_LearningOpencv\trainer\trainer.yaml')

关于AttributeError: module ‘cv2.face‘ has no attribute ‘createLBPHFaceRecognizer‘的问题:

需要安装 opencv-contrib-python

pip install opencv-contrib-python

你可能感兴趣的:(opencv,图像处理,人工智能)