Java教程

人脸识别项目实战

本文主要是介绍人脸识别项目实战,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、对于视频、图像基本操作

1.1、img_show(img)用于对于图像进行可视化操作

1.2、img_gray(filepath) 对于图像进行灰度处理,图像处理任务中基本都是转化成灰度图处理,由于灰度图通道数为1,易于处理。

1.3、img_size(filepath):对于图像进行放大、缩小操作;

1.4、img_draw(filepath):用于在图像上绘制矩形框和圆形框,主要用于对于识别的目标进行标示;

# -*— coding:utf-8 -*-
# @time   :2021/11/17 10:27
# @Author :zhangzhoubin
'''
人脸识别
'''
import cv2
import os

#图片可视化展示
def img_show(img):
    cv2.imshow('new_img',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

#图像转化成灰度图、图像的保存
def img_gray(filepath):
    data=cv2.imread(filepath,cv2.IMREAD_GRAYSCALE) #转化成灰度图
    img_show(data)
    cv2.imwrite('1_hd.jpg',data)  #将处理后的灰度图进行保存
    print(data)

#图像的缩小、放大
def img_size(filepath):
    data2=cv2.imread(filepath)
    size_img=cv2.resize(data2,dsize=(200,200))
    img_show(data2)
    img_show(size_img)

#图像上绘制矩形和圆形,用于对于所需标注的地方进行标注
def img_draw(filepath):
    data3=cv2.imread(filepath)
    x,y,w,h=0,0,100,100
    data4=cv2.rectangle(data3,(x,y),(x+100,y+100),color=(0,0,255),thickness=2)  #图片上绘制矩形
    data4 = cv2.circle(data4, center=(x+50,y+50), radius=50, color=(0, 255, 0), thickness=2)  # 图片上绘制矩形
    cv2.imshow('zzb',data4)
    while  True:  #判断当按下q键时候关闭图像,释放计算资源
        if ord('q')==cv2.waitKey(0):
            break
    cv2.destroyAllWindows()

#图像人脸检测器,其中cv2.CascadeClassifier为级联分类器,里面加载的文件是安装opencv后,里面封装的人脸识别模型,face_cas.detectMultiScale为多目标识别器,导入含有人脸的图像数据,将自动识别输出来人脸坐标,默认是矩形框的坐标,其中坐标涉及左上角的x,y,然后矩形的宽度和长度w、h,通过这4个值送入矩形框函数 cv2.rectangle,对于识别到的人脸框出来,完成人脸的识别
def img_face2(data5):
    # data5=cv2.imread(filepath,cv2.IMREAD_GRAYSCALE)
    face_cas=cv2.CascadeClassifier('D:\opencv_python\opencv\sources\data\haarcascades\haarcascade_frontalface_alt2.xml')   
    faces = face_cas.detectMultiScale(data5)   #里面涉及几个可以调节的参数,
    for x,y,w,h in faces:
        print(x,y,w,h)
        cv2.rectangle(data5,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)
    img_show(data5)

def img_face1():
    list = os.listdir(r'C:\Users\lenovo\Desktop\image_learning\Image_identifition\data')
    for i in list:
        filepath = '../data/{}'.format(i)
        print(filepath)
        img=cv2.imread(filepath,cv2.IMREAD_GRAYSCALE)
        img_face2(img)


#视频人脸检测器,
def video_img_face(data5):
    face_cas=cv2.CascadeClassifier('D:\opencv_python\opencv\sources\data\haarcascades\haarcascade_frontalface_alt2.xml')
    faces = face_cas.detectMultiScale(data5)   #里面涉及几个可以调节的参数,
    for x,y,w,h in faces:
        print(x,y,w,h)
        cv2.rectangle(data5,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)
    cv2.imshow('zzb',data5)


#视频中人脸检测,视频的读取,是采用循环的方式一帧一帧进行读取,也是一帧一帧的处理。
def video_face():
    file2='1.mp4'
    vc=cv2.VideoCapture(file2)  #读取视频文件
    if vc.isOpened():  # 判断视频是否打开
        open, frame = vc.read()  # 读取第一帧
    else:
        open = False
    while open:  #循环
        ret, frame = vc.read()
        # print(ret)
        # print(frame)
        if frame is None: #等图像帧为空时退出
            break
        if ret == True:  #当读取的图像不为空继续读取
            gray = cv2.cvtColor(frame,  cv2.COLOR_BGR2GRAY)   #将图像转化为灰度图
            video_img_face(gray)   #可视化展示
            if cv2.waitKey(1) & 0xFF == 27:
                break
    vc.release()  # 释放视频
    cv2.destroyAllWindows()  # 关闭现在视频窗口

#视频拍照保存
def video_photograh():
    num = 9
    vc=cv2.VideoCapture(0) #视频的读取,当里面是0的时候默认捕捉当前电脑的摄像头
    if vc.isOpened():
        open_state,frame=vc.read()
    else:
        open_state=False
    while open_state: #循环

        open_state,frame=vc.read()
        if frame is None:
            break
        if open_state==True:
            gray = cv2.cvtColor(frame,  cv2.COLOR_BGR2GRAY)
            cv2.imshow('zzb',gray)
            if cv2.waitKey(1) & 0xFF==ord('q'):
                cv2.imwrite('../data'+str(num)+'.jpg',frame)
                print("拍照完成")
                num+=1
            elif cv2.waitKey(1) & 0xFF==ord('e'):
                break
    vc.release()
    cv2.destroyAllWindows()


#重构拍照保存
def video_photo():
    num=0
    vc=cv2.VideoCapture(0) #捕捉视频操作
    while(vc.isOpened()):
        open_state,frame=vc.read()
        cv2.imshow('臭宝',frame)
        k=cv2.waitKey(1)
        if k & 0xFF==ord('q'):
            print("第"+str(num)+"次"+"拍照完成")
            cv2.imwrite('../data/'+str(num)+"_test"+'.jpg',frame)
            num+=1
        elif k & 0xFF==ord('e'):
            break
    vc.release()
    cv2.destroyAllWindows()


if __name__=='__main__':
    filepath = '../data/6.jpg'

    #图像转化成灰度图、图像的读取
    # img_gray(filepath)

    # 图像的缩小
    # img_size(filepath)

    # 图像上绘制矩形和圆形
    # img_draw(filepath)

    #图像人脸识别
    # img_face1()

    #视频人脸识别
    # video_face()

    #视频拍照保存
    # video_photograh()
    # 重构视频拍照保存
    # video_photo()
    

2、实现人脸识别项目

'''
目标:实现人脸的录入,人脸的识别
'''
'''
实现人脸的录入功能开发
'''
import os
import cv2
import pandas as pd
import numpy as np

from PIL import Image, ImageDraw, ImageFont

#用于创建人员字典,该字典用于后期人员信息采集
# def  mkdir_name_list(img):
#     name_list = os.listdir(img)
#     name_num = [int(i.split('.')[0]) for i in name_list]
#     # 获取新员工的编号
#     name=['董明珠','郭晶晶','黄晓明','黄轩','马云','俞敏洪']
#     data=pd.DataFrame({
#         'id':name_num,
#         'name':name
#     })
#     print(data)
#     data.to_csv('name.csv',index = False)



#新员工姓名录入
def face_name(img):
    #获取新员工的姓名
    new_peple=input("请输入新员工姓名:")
    name_list=os.listdir(img)
    name_num=[int(i.split('.')[0]) for i in name_list]
    #获取新员工的编号
    new_name=max(name_num)+1
    # 加入新员工的姓名
    namelist=pd.read_csv('name.csv',encoding='utf-8')
    name_list=namelist.append({'id':new_name,'name':new_peple},ignore_index=True)
    name_list.to_csv('name.csv',index = False)
    print("新员工姓名录入成功!")
    return new_name

#人脸手动采集
def face_optimize(img):
    new_name=face_name(img)
    content=cv2.VideoCapture(0) #捕捉摄像头
    while content.isOpened():
        open_state,frame=content.read()     #视频读取
        cv2.imshow('result',frame)
        k=cv2.waitKey(1)
        if k & 0xFF ==ord('q'):
            cv2.imwrite('../data/'+str(new_name)+'.jpg',frame)
            print("人脸录入成功!")
        elif k & 0xFF ==ord('e'):
            break
    content.release()
    cv2.destroyAllWindows()

#基于现有图片数据,进行人脸模型训练
def face_recognition(img):
    faceimages=[]
    ids=[]
    #定义级联分类器
    face_detector=cv2.CascadeClassifier('D:\opencv_python\opencv\sources\data\haarcascades\haarcascade_frontalface_alt2.xml')
    imglist=[img+'/'+i for i in os.listdir(img)]
    for  i in imglist:

        image=cv2.imread(i ,cv2.IMREAD_GRAYSCALE)
        #利用多目标分类器提取人脸特征,输出人脸的左上角坐标和长、宽
        face=face_detector.detectMultiScale(image)
        id=i.split('/')[2].split('.')[0]
        for x,y,w,h in face:
            cv2.rectangle(image,(x,y),(x+w,y+h),color=[0,255,0],thickness=2)
            faceimages.append(image[y:y+h,x:x+w])
            ids.append(int(id))
            print(ids)
            print(faceimages)

            recognizer = cv2.face.LBPHFaceRecognizer_create()
            recognizer.train(faceimages, np.array(ids))
            recognizer.write('face_model.yml')
            # 加载人脸预测模型
            recognizer.read('face_model.yml')
    return faceimages,ids
#人脸识别模块
def face_detector(img):
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    #加载人脸预测模型
    recognizer.read('face_model.yml')

    #人脸检测模块
    face_detector=cv2.CascadeClassifier('D:\opencv_python\opencv\sources\data\haarcascades\haarcascade_frontalface_alt2.xml')
    imglist=[img+'/'+i for i in os.listdir(img)]
    for img in imglist:
        image=cv2.imread(img,cv2.IMREAD_GRAYSCALE)
        face=face_detector.detectMultiScale(image)
        for x,y,w,h in face:
            cv2.rectangle(image,(x,y),(x+w,y+h),color=[255,0,0],thickness=2)
            ids, confidence = recognizer.predict(image[y:y + h, x:x + w])
            if confidence <20:
                print("标签:"+str(ids) +'置信度:'+str(confidence))
                data=pd.read_csv('name.csv')
                for index,rows in data.iterrows():
                    if rows['id']==ids:
                        text=rows['name']
                        cv2charimg=img_ksh(image, text, x, y)
                        cv2.imshow('zzb', cv2charimg)
                        cv2.waitKey(0)
                        cv2.destroyAllWindows()
            else:
                cv2charimg = img_ksh(image, '陌生人', x, y)
                cv2.imshow('zzb', cv2charimg)
                cv2.waitKey(0)
                cv2.destroyAllWindows()


def img_ksh(image,text,x,y):
    # cv2读取图片
    cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # cv2和PIL中颜色的hex码的储存顺序不同
    pilimg = Image.fromarray(cv2img)
    if not isinstance(text, str):
        text = text.decode('utf-8')
    # PIL图片上打印汉字
    draw = ImageDraw.Draw(pilimg)  # 图片上打印
    font = ImageFont.truetype("./simhei.ttf", 20, encoding="utf-8")  # 参数1:字体文件路径,参数2:字体大小
    draw.text((x+50, y-25), text, (255, 0, 0), font=font)  # 参数1:打印坐标,参数2:文本,参数3:字体颜色,参数4:字体
    # PIL图片转cv2 图片
    cv2charimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
    # cv2.imshow("图片", cv2charimg) # 汉字窗口标题显示乱码
    return  cv2charimg


if __name__=='__main__':
    img='../data'
    # mkdir_name_list(img)
    #人脸手动采集
    # face_optimize(img)
    # # 基于现有图片数据,进行人脸模型训练
    # face_recognition(img)
    #人脸识别模块
    face_detector(img)

这篇关于人脸识别项目实战的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!