Python 人脸识别实现(三种方式)

这篇具有很好参考价值的文章主要介绍了Python 人脸识别实现(三种方式)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

所有涉及的配置文件(xml,dat)存储在这里:
https://jhc001.lanzoub.com/iyaeo0w8jkgb
密码:JDBC

所有 sdk 包下内容均为自定义,跑不了直接自己改输入就行

代码功能描述:
识别图像中的人面部位置,并将面部裁切下来,存储到excel里(excel里最多存储8张,按照从左到右顺序存储)文章来源地址https://www.toymoban.com/news/detail-595050.html

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : v_jiaohaicheng@baidu.com
@des     :基于opencv实现

"""
import os
import cv2
import xlsxwriter
from io import BytesIO


class CVFaceCheck():

    def get_img_name(self,imgfile):
        return os.path.split(imgfile)[0],os.path.split(imgfile)[-1].split(".")[0]

    def get_img_date(self,img_file):
        image_file = open(img_file, 'rb')
        image_data = BytesIO(image_file.read())
        image_file.close()
        return image_data

    def read_img(self,imgfile):
        return cv2.imread(imgfile)

    def tran_gray(self,img):
        return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    def get_face_opt(self,gray):
        # face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        # Detect faces
        faces = face_cascade.detectMultiScale(gray, 1.1, 4)
        # Draw rectangle around the faces and crop the faces
        for (x, y, w, h) in faces:
            yield x, y, w, h

    def cut_face(self,gray,img,imgfile):
        map = {}
        for index,value in enumerate(self.get_face_opt(gray)):
            x, y, w, h = value
            faces = img[y:y + h,x:x + w]
            save_face_name = os.path.join(self.get_img_name(imgfile)[0],'face_{}.jpg'.format(index))

            cv2.imwrite(save_face_name, cv2.resize(faces,[100,100]))
            map[x] = {
                "img_name":save_face_name,
                "face_opt":[y,y + h, x,x + w],
            }
        return map

    def remove_face_cut(self,res_sort):
        for _,value in res_sort.items():
            img_name = value["img_name"]
            os.remove(img_name)

    def write_excel(self,imgfile,face_map,save_path = "./",sheet="Sheet1"):
        save_excel_file = os.path.join(save_path,self.get_img_name(imgfile)[-1])+".xlsx"
        workbook = xlsxwriter.Workbook(save_excel_file)
        worksheet = workbook.add_worksheet(sheet)
        lis = ["人物ID","0","1","2","3","4","5","6","7"]
        style = {
                'font_name': '微软雅黑',
                'font_size': 15,
                'color':"red",
                'bold': True,
                'border': 0,
                'align': 'center',
                'valign': 'vcenter',
                'text_wrap': False,
        }
        cell_format = workbook.add_format(style)
        worksheet.merge_range(0,0,0,9,"人物关系矩阵",cell_format=cell_format)
        for col,value in enumerate(lis):
            worksheet.write_string(
                row=1,
                col=col+1,
                string=str(value),
            )

        for row,value in enumerate(lis):
            worksheet.write_string(
                row=row+2,
                col=0,
                string=str(value),
            )
        worksheet.write_string(
            row=2,
            col=1,
            string="人物图片",
        )
        num = 0
        for _,val in face_map.items():
            num += 1
            img_file = val["img_name"]
            image_data = self.get_img_date(img_file)
            if num <= 8:
                worksheet.insert_image(
                    row = 2,
                    col = num+1,
                    filename = img_file,
                    options={"image_data":image_data},
                )

                worksheet.insert_image(
                    row=num+2,
                    col=1,
                    filename=img_file,
                    options={"image_data": image_data},
                )
                worksheet.set_column(1, num + 1, 14)
                worksheet.set_row(2, 100)
                worksheet.set_row(num+2, 100)

        workbook.close()


    def process(self,imgfile,out_path):
        # Read the input image
        img = self.read_img(imgfile)
        # cv2.imshow("test",img)
        # cv2.waitKey(0)
        # Convert into grayscale
        gray = self.tran_gray(img)

        res = self.cut_face(gray,img,imgfile)
        res_sort = dict(sorted(res.items(),key=lambda x:x[0]))
        print(res_sort)
        self.write_excel(imgfile,res_sort,save_path=out_path)
        # self.remove_face_cut(res_sort)

if __name__ == '__main__':
    # file = input("输入图片位置:")
    # out_path = input("输入excel存储路径:(默认为当前路径下)")
    # if out_path == "":
    #     out_path = "./"
    cfc = CVFaceCheck()
    # file = R"D:\PythonDevelopmentTools\tests\cv_test\face_check_cut\npw1.jpg"
    # out_file = R"D:\PythonDevelopmentTools\tests\cv_test\face_check_cut\res"
	
    from sdk.utils.util_folder import FolderPath

    out_path = R"D:\Desktop\res"
    os.makedirs(out_path, exist_ok=True)
    for file in FolderPath.get_absfiles(R"D:\Desktop\111111"):
        # os.makedirs(out_path,exist_ok=True)
        _file = file["filepath"]
        print(_file)
        cfc.process(_file,out_path)
        input("回车继续")

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : v_jiaohaicheng@baidu.com
@des     :基于dblib实现

"""
import os
import cv2
import dlib
import numpy as np
import xlsxwriter
from io import BytesIO


class DlibFaceCheck():
    def read_img(self,imgfile):
        return cv2.imread(imgfile)

    def get_img_name(self,imgfile):
        return os.path.split(imgfile)[0],os.path.split(imgfile)[-1].split(".")[0]

    def get_img_date(self,img_file):
        image_file = open(img_file, 'rb')
        image_data = BytesIO(image_file.read())
        image_file.close()
        return image_data

    def get_face_opt(self,img):
        predictor_path = 'shape_predictor_68_face_landmarks.dat'
        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor(predictor_path)

        faces = detector(img, 0)
        if len(faces):
            print('==> Found %d face in this image.' % len(faces))
            for i in range(len(faces)):
                landmarks = np.matrix([[p.x, p.y] for p in predictor(img, faces[i]).parts()])
                lis = landmarks.tolist()
                opt1 = (min([i[0] for i in lis]), min([i[1] for i in lis]))
                opt2 = (max([i[0] for i in lis]), max([i[1] for i in lis]))
                # print(opt1,opt2)
                yield opt1,opt2
        else:
            print('Face not found!')

    def get_map(self,imgfile,save_path):
        map = {}
        img = self.read_img(imgfile)
        for index, value in enumerate(self.get_face_opt(img)):
            opt1, opt2 = value
            faces = img[opt1[-1]:opt2[-1], opt1[0]:opt2[0]]
            save_img_file = os.path.join(save_path,"res_{}.jpg".format(index))
            cv2.imwrite(save_img_file, cv2.resize(faces,(100,100)))
            map[index] = {
                "img_name": save_img_file,
                "face_opt": [[opt1[0], opt1[-1]], [opt2[-1], opt2[0]]]
            }
        return map


    def write_excel(self,imgfile,face_map,save_path = "./",sheet="Sheet1"):
        save_excel_file = os.path.join(save_path,self.get_img_name(imgfile)[-1])+".xlsx"
        workbook = xlsxwriter.Workbook(save_excel_file)
        worksheet = workbook.add_worksheet(sheet)
        lis = ["人物ID","0","1","2","3","4","5","6","7"]
        style = {
                'font_name': '微软雅黑',
                'font_size': 15,
                'color':"red",
                'bold': True,
                'border': 0,
                'align': 'center',
                'valign': 'vcenter',
                'text_wrap': False,
        }
        cell_format = workbook.add_format(style)
        worksheet.merge_range(0,0,0,9,"人物关系矩阵",cell_format=cell_format)
        for col,value in enumerate(lis):
            worksheet.write_string(
                row=1,
                col=col+1,
                string=str(value),
            )

        for row,value in enumerate(lis):
            worksheet.write_string(
                row=row+2,
                col=0,
                string=str(value),
            )
        worksheet.write_string(
            row=2,
            col=1,
            string="人物图片",
        )
        num = 0
        for _,val in face_map.items():
            num += 1
            img_file = val["img_name"]
            image_data = self.get_img_date(img_file)
            if num <= 8:
                worksheet.insert_image(
                    row = 2,
                    col = num+1,
                    filename = img_file,
                    options={"image_data":image_data},
                )

                worksheet.insert_image(
                    row=num+2,
                    col=1,
                    filename=img_file,
                    options={"image_data": image_data},
                )
                worksheet.set_column(1, num + 1, 14)
                worksheet.set_row(2, 100)
                worksheet.set_row(num+2, 100)

        workbook.close()

    def remove_face_cut(self,res_sort):
        for _,value in res_sort.items():
            img_name = value["img_name"]
            os.remove(img_name)


    def process(self,imgfile,save_path):
        map = self.get_map(imgfile,save_path)
        sort_map = dict(sorted(map.items(),key=lambda x:x[0]))
        self.write_excel(imgfile, sort_map, save_path=save_path)
        self.remove_face_cut(sort_map)



if __name__ == '__main__':
    file = input("输入图片位置:")
    out_path = input("输入excel存储路径:(默认为当前路径下)")
    if out_path == "":
        out_path = "./"
    else:
        os.makedirs(out_path,exist_ok=True)

    dfc = DlibFaceCheck()
    dfc.process(file,out_path)
    

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : v_jiaohaicheng@baidu.com
@des     :基于百度api实现

"""
import requests
# 自己注册后填在这
APP_ID = ""
API_KEY = ""
SECRET_KEY= ""


class ApiFaceCheck():

    def get_access_token(self,ak,sk):
        url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}".format(
                  ak,sk
              )
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        payload = ""
        response = requests.request("POST", url, headers=headers, data=payload)
        return response.json()["access_token"]

    def get_face_opt(self,up_url,ak=API_KEY,sk=SECRET_KEY):
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        params = {
                    "image":"{}".format(up_url),
                    "image_type":"URL",
                    "max_face_num":8,
                    "face_type":"LIVE"
                  }
        access_token = self.get_access_token(ak,sk)
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers)
        return response.json()

到了这里,关于Python 人脸识别实现(三种方式)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 计算机设计大赛 深度学习人脸表情识别算法 - opencv python 机器视觉

    🔥 优质竞赛项目系列,今天要分享的是 🚩 深度学习人脸表情识别系统 该项目较为新颖,适合作为竞赛课题方向,学长非常推荐! 🥇学长这里给一个题目综合评分(每项满分5分) 难度系数:3分 工作量:3分 创新点:4分 🧿 更多资料, 项目分享: https://gitee.com/dancheng-senior/

    2024年02月21日
    浏览(81)
  • python人脸识别考勤系统 dlib+OpenCV和Pyqt5、数据库sqlite 人脸识别系统 计算机 毕业设计 源码

    Python语言、dlib、OpenCV、Pyqt5界面设计、sqlite3数据库 本系统使用dlib作为人脸识别工具,dlib提供一个方法可将人脸图片数据映射到128维度的空间向量,如果两张图片来源于同一个人,那么两个图片所映射的空间向量距离就很近,否则就会很远。因此,可以通过提取图片并映射到

    2024年02月08日
    浏览(41)
  • 计算机毕业设计:基于python人脸识别考勤系统 OpenCV+Dlib(包含文档+源码+部署教程)

    [毕业设计]2023-2024年最新最全计算机专业毕设选题推荐汇总 感兴趣的可以先收藏起来,还有大家在毕设选题,项目以及论文编写等相关问题都可以给我留言咨询,希望帮助更多的人 。 Python语言、dlib、OpenCV、Pyqt5界面设计、sqlite3数据库 方法实现、实现步骤 1、实例化人脸检测

    2024年02月04日
    浏览(55)
  • 人工智能-OpenCV+Python实现人脸识别(人脸检测)

    在OpenCV中使用Haar特征检测人脸,那么需要使用OpenCV提供的xml文件(级联表)在haarcascades目录下。这张级联表有一个训练好的AdaBoost训练集。首先要采用样本的Haar特征训练分类器,从而得到一个级联的AdaBoost分类器。Haar特征值反映了图像的灰度变化情况。例如:脸部的一些特征

    2024年02月06日
    浏览(86)
  • OpenCV-Python:简单实现人脸识别

    core 核心功能模块。该模块主要包含 OpenCV库的基础结构以及基本操作,例如OpenCV基础数据结构、绘图函数、数组操作相关函数、动态数据结构等calib3d: 这个模块名称是有 calibration(校准)和 3D 两个术语的缩写组合而成。包含了相机标定与立体视觉等功能,例如物体位姿估计

    2024年02月09日
    浏览(35)
  • 【opencv】python实现人脸检测和识别训练

    OpenCV 中的人脸识别通常基于哈尔特征分类器(Haar Cascade Classifier)进行。以下是 OpenCV 人脸识别的基本原理: Haar Cascade Classifier : 特征分类器 :Haar 特征是一种基于矩形区域的特征,可以用于图像中的对象检测。这些特征可以表示边缘、线和区域的变化等。 级联分类器 :

    2024年01月17日
    浏览(42)
  • Python+OpenCV 简单实现人脸检测多个和人脸识别 2(附代码)

    如果dilb和face_recognition第三方包安装失败,请移步到Python 解决dilb和face_recognition第三方包安装失败_水w的博客-CSDN博客 上篇请移步到Python+dilb 简单实现人脸检测(附代码)_水w的博客-CSDN博客 本篇是在上篇的工作基础上进行的。 目录 6 人脸检测多个 7 视频检测 8 拍照保存 9 训练

    2024年01月16日
    浏览(45)
  • Python - OpenCV实现摄像头人脸识别(亲测版)

    要使用Python 3和OpenCV进行摄像头人脸识别,您可以按照以下步骤进行操作: 0.安装OpenCV软件 去官网直接下载安装即可,如果是C++使用OpenCV,需要使用编译源码并配置环境变量。 1.安装OpenCV库 在命令行中输入以下命令: 2.准备人脸检测器 使用OpenCV的人脸检测器可以检测出图像中

    2024年02月15日
    浏览(36)
  • Python+OpenCV 调用手机摄像头并实现人脸识别

    文章内容 : 1、windows 环境下安装 OpenCV 机器视觉环境搭建; 2、基于通过 Python+OpenCV 调用 手机摄像头 并实现人脸检测识别。 操作环境:Windows 10 64位 开发 IDE:Spyder 4.2.5 Python:3.8 OpenCV:OpenCv-Python 4.5.3 硬件需要:PC(win10)、手机 主要介绍使用 pip 安装 OpenCV(使用.whl文件安装

    2024年02月09日
    浏览(46)
  • 基于opencv和python的人脸识别签到系统设计与实现

    收藏和点赞,您的关注是我创作的动力   人脸识别广泛的应用于各个领域。一般来说,人脸具有人类基因、指纹等独特的生物学特性,因此可以作为生物特征识别,从而方便、快速、准确地识别被摄体,可见人脸识别是一种有效的身份识别工具。该技术可以应用于任何需要

    2024年02月04日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包