iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python 人脸识别实现(三种方式)
  • 893
分享到

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

pythonopencv计算机视觉 2023-10-18 18:10:02 893人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

所有涉及的配置文件(xml,dat)存储在这里: https://jhc001.lanzoub.com/iyaeo0w8jkgb 密码:JDBC 所有 sdk 包下内容均为自定义,跑不了直接自己改输入

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

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

代码功能描述:
识别图像中的人面部位置,并将面部裁切下来,存储到excel里(excel里最多存储8张,按照从左到右顺序存储)

# !/usr/bin/env python3# -*- coding: UTF-8 -*-"""@author  : v_jiaohaicheng@baidu.com@des     :基于OpenCV实现"""import osimport cv2import xlsxwriterfrom io import BytesIOclass 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 osimport cv2import dlibimport numpy as npimport xlsxwriterfrom io import BytesIOclass 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()

来源地址:https://blog.csdn.net/CXY00000/article/details/130684381

--结束END--

本文标题: Python 人脸识别实现(三种方式)

本文链接: https://www.lsjlt.com/news/431614.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python 人脸识别实现(三种方式)
    所有涉及的配置文件(xml,dat)存储在这里: https://jhc001.lanzoub.com/iyaeo0w8jkgb 密码:JDBC 所有 sdk 包下内容均为自定义,跑不了直接自己改输入...
    99+
    2023-10-18
    python opencv 计算机视觉
  • Python实现人脸识别
    使用到的库: dlib+Opencv python版本: 3.8 编译环境: Jupyter Notebook (Anaconda3) 0.Dlib人脸特征检测原理 提取特征点:首选...
    99+
    2024-04-02
  • SpringBoot实现人脸识别等多种登录方式
    目录1.前端界面实现2.手机验证码登录3.人脸识别登录(百度人脸识别)1.前端界面实现 ①背景闪烁效果: <!-- 背景星星闪烁效果 --> <script&g...
    99+
    2024-04-02
  • 人脸识别实战之Opencv+SVM实现人脸识别
    目录前言项目结构编码训练人脸识别模型识别图像中的人脸摄像头识别人脸前言 在本文中,您将学习如何使用 OpenCV 进行人脸识别。文章分三部分介绍: 第一,将首先执行人脸检测,使用深度...
    99+
    2024-04-02
  • 怎么用Python实现人脸识别
    这篇文章主要讲解了“怎么用Python实现人脸识别”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用Python实现人脸识别”吧!安装最好是使用 Linux 或 Mac 环境来安装,Win...
    99+
    2023-06-02
  • Python 人脸识别 OpenCV (
    ■环境Python 3.6.0Pycharm 2017.1.3 ■库、库的版本OpenCV 3.4.1 (cp36) ■haarcascades下载https://github.com/opencv/opencv/tree/master/d...
    99+
    2023-01-31
    Python OpenCV
  • 人脸识别java方法怎么实现
    人脸识别是一项复杂的技术,需要使用专业的算法和工具来实现。以下是一些实现人脸识别的Java方法:1. 使用OpenCV库:OpenC...
    99+
    2023-06-11
    人脸识别java java
  • 人脸识别4:Android InsightFace实现人脸识别Face Recognition(含源码)
    人脸识别4:Android InsightFace实现人脸识别Face Recognition(含源码) 目录 人脸识别4:Android InsightFace实现人脸识别Face Recognition(含源码) 1. 前言 2. 项目...
    99+
    2023-08-31
    android 人脸识别 人脸检测 android人脸识别
  • Python如何实现人脸识别系统
    小编给大家分享一下Python如何实现人脸识别系统,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!基本原理人脸识别和目标检测这些还不太一样,比如大家传统的训练一个目...
    99+
    2023-06-26
  • 怎么用Python代码实现人脸识别
    这篇文章主要介绍“怎么用Python代码实现人脸识别”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么用Python代码实现人脸识别”文章能帮助大家解决问题。正文:环境要求:Ubuntu17.10P...
    99+
    2023-06-29
  • Python怎么实现AI智能人脸识别
    本篇文章为大家展示了Python怎么实现AI智能人脸识别,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。前言现在人脸识别这东西层出不穷,基本上很多东西都用到,比如现在火车站都是用人脸识别来过关卡,确实...
    99+
    2023-06-02
  • Python调用API接口实现人脸识别
    目录准备工作代码流程在开始之前,先问问大家: 什么是百度Aip模块? 百度AI平台提供了很多的API接口供开发者快速的调用运用在项目中本文写的是使用百度AI的**在线接口SDK模块(...
    99+
    2023-02-13
    Python调用API接口 Python 人脸识别
  • java+opencv实现人脸识别功能
    背景:最近需要用到人脸识别,但又不花钱使用现有的第三方人脸识别接口,为此使用opencv结合java进行人脸识别(ps:opencv是开源的,使用它来做人脸识别存在一定的误差,效果一...
    99+
    2024-04-02
  • 【ROS】OpenCV+ROS 实现人脸识别(Ubantu16.04)
    目录   前言 一、环境配置   1.安装ROS  2.摄像头调用 3.导入OpenCV 二、创建工作空间和功能包 1.创建工作空间 2.创建功能包 三、人脸识别检测相关代码 1.python文件 2.lanuch文件  3.CvBridg...
    99+
    2023-08-31
    opencv linux 人工智能 python 学习
  • Python三十行代码实现简单人脸识别的示例代码
    一、库介绍 opencv,face_recognition,numpy,以及dlib 注意: 安装opencv速度可能过慢,需要更换国内镜像源,参考:https://www.jb...
    99+
    2024-04-02
  • Opencv+SVM怎样实现人脸识别
    Opencv+SVM怎样实现人脸识别,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。前言如何使用 OpenCV 进行人脸识别。第一,将首先执行人脸检测,使用深度学习从每个人脸...
    99+
    2023-06-22
  • Python几行代码即可实现人脸识别
    摘要:一行代码实现人脸识别 首先你需要提供一个文件夹,里面是所有你希望系统认识的人的图片。其中每个人一张图片,图片以人的名字命名。 接下来,你需要准备另一个文件夹,...
    99+
    2024-04-02
  • Python中基于Opencv怎么实现人脸识别
    这篇文章主要讲解了“Python中基于Opencv怎么实现人脸识别”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python中基于Opencv怎么实现人脸识别”吧!检测人脸。这应该是最基本的...
    99+
    2023-06-02
  • Python PyQt5 人脸识别软件
    # !/usr/bin/python3# -*- coding:utf-8 -*-"""@author: JHC000abc@gmail.com@file: untitled_ctrl.py@tim...
    99+
    2023-08-31
    python qt 开发语言
  • Python怎么实现人脸识别微笑检测
    这篇文章主要介绍“Python怎么实现人脸识别微笑检测”,在日常操作中,相信很多人在Python怎么实现人脸识别微笑检测问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python怎么实现人脸识别微笑检测”的疑...
    99+
    2023-06-21
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作