人脸识别系统代码--预测性别

1.导入包

cv2是OpenCV库,numpy用于数值计算,tkinter是Python的标准GUI库,subprocess用于运行其他Python脚本,face_recognition用于人脸识别,PIL(Pillow)用于处理图像

import cv2
import numpy as np
import tkinter as tk
import subprocess
from tkinter import filedialog, Label, Button
import face_recognition
from PIL import Image, ImageTk

2.加载预训练的人脸检测模型

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# 加载预训练的性别和年龄识别模型
gender_net = cv2.dnn.readNetFromCaffe('deploy_gender.prototxt', 'gender_net.caffemodel')
age_net = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel')

3.定义性别标签列表

gender_list = ['Male', 'Female']
age_list = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']

4.设置窗口

root = tk.Tk()
root.title("预测性别")
root.geometry("750x600")

5.设置背景

用filedialog模块打开文件选择对话框,并读取用户选择的图片。

image = Image.open("16.gif")
image = image.resize((750, 600))  # 调整背景图片大小
photo1 = ImageTk.PhotoImage(image)
# 创建Label并将背景图片设置为背景
canvas = tk.Label(root, image=photo1)
canvas.pack()

6.定义函数select_image

创建一个按钮,用于触发select_image函数。

def select_image():
    file_path = filedialog.askopenfilename()
    if file_path:
        img = cv2.imread(file_path)
        if img is not None:
            display_image(file_path)

7.定义函数display_image

定义显示图片的函数display_image,它将读取的图片显示在窗口中。

def display_image(file_path):
    # 确保 img 变量已经定义
    global img
    img = cv2.imread(file_path)
    if img is not None:
        # 调整图像大小到相等的大小
        img = cv2.resize(img, (300, 300))  # 假设您想要将图像调整到 227x227 的大小

        # 将 OpenCV 图像转换为 PIL 图像
        pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

        # 在这里调整图像到固定大小
        pil_image = pil_image.resize((300, 400))  # 调整图像到300x400像素

        # 将 PIL 图像转换为 tkinter 支持的格式
        image_tk = ImageTk.PhotoImage(pil_image)

        # 在 root 窗口中创建一个标签来显示图像
        label = tk.Label(root, image=image_tk)
        label.image = image_tk  # 保持引用,否则图像在重新绘制时会丢失
        label.place(x=30, y=100)

8.定义函数predict_gender

 创建预测性别的函数predict_gender,它使用OpenCV的人脸检测模型检测人脸,并使用性别识别模型预测性别。

def predict_gender():
    # 确保 img 变量已经定义
    global img
    if img is not None:
        # 转换为灰度图像
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # 检测人脸
        faces = face_cascade.detectMultiScale(gray, 1.1, 4)

        # 遍历检测到的人脸
        for (x, y, w, h) in faces:
            # 从原始图像中裁剪人脸区域
            face_img = img[y:y + h, x:x + w].copy()

            # 预处理人脸图像以适应神经网络输入
            blob = cv2.dnn.blobFromImage(face_img, 1, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)

            # 预测性别
            gender_net.setInput(blob)
            gender_preds = gender_net.forward()
            gender = gender_list[gender_preds[0].argmax()]

            # 在人脸周围画框并显示性别
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
            cv2.putText(img, f'{gender}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2, cv2.LINE_AA)


            # 将 OpenCV 图像转换为 PIL 图像
            pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

            # 在这里调整图像到固定大小
            pil_image = pil_image.resize((300, 400))  # 调整图像到300x400像素

            # 将 PIL 图像转换为 tkinter 支持的格式
            image_tk = ImageTk.PhotoImage(pil_image)


            # 在 root 窗口中创建一个标签来显示图像
            label = tk.Label(root, image=image_tk)
            label.image = image_tk  # 保持引用,否则图像在重新绘制时会丢失
            label.place(x=360, y=100)


            # 将 OpenCV 图像转换为 PIL 图像
            pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

            # 在这里调整图像到固定大小
            pil_image = pil_image.resize((300, 400))  # 调整图像到300x400像素

            # 将 PIL 图像转换为 tkinter 支持的格式
            image_tk = ImageTk.PhotoImage(pil_image)

9.定义函数close

def close():
    subprocess.Popen(["python","属性判断.py"])
    root.destroy()

10.定义按钮

# 创建一个按钮,用于打开文件选择对话框
image = Image.open("A.gif")  # 加载一张图片
photo2 = ImageTk.PhotoImage(image)
open_image_btn = tk.Button(root, image=photo2, width=198, height=31,command=select_image)
open_image_btn.place(x=30,y=30)

# 创建预测性别的按钮
image = Image.open("F16.gif")  # 加载一张图片
photo3 = ImageTk.PhotoImage(image)
predict_gender_btn = tk.Button(root, image=photo3, command=predict_gender)
predict_gender_btn.place(x=275,y=30)

image = Image.open("B.gif")  # 加载一张图片
photo4 = ImageTk.PhotoImage(image)
bt3 = tk.Button(image=photo4, width=198, height=32,command=close)
bt3.place(x=520, y=30)

11.退出窗口

root.mainloop()

在Python中,使用人脸识别技术并结合性别识别通常涉及到深度学习库,如OpenCV、Dlib、Face_recognition和TensorFlow等。以下是一个简单的示例,展示如何使用dlib库进行人脸检测,并使用性别预测模型(例如基于机器学习的模型)来预测性别: ```python # 导入必要的库 import cv2 import dlib from PIL import Image import numpy as np # 下载并加载预训练的人脸检测模型(Haar级联分类器) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # 下载并加载预训练的性别预测模型(假设是一个sklearn模型,例如使用Iris数据集中的特征和性别作为标签) # 这里只是一个假设,实际可能需要使用更复杂的模型,如face_recognition中的卷积神经网络模型 gender_model = load_gender_model() # 假设函数load_gender_model()已经定义好了模型加载 def detect_face_and_predict_gender(image_path): # 加载图像 img = cv2.imread(image_path) # 转换为灰度图像以便于人脸检测 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 检测人脸 faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) for (x, y, w, h) in faces: # 提取人脸区域 face_roi = img[y:y+h, x:x+w] # 将图像转换为PIL格式,因为dlib需要这种格式 pil_image = Image.fromarray(face_roi) # 将PIL图像调整为模型所需的尺寸 resized_image = pil_image.resize((48, 48)) # 假设你的模型需要48x48像素的输入 # 将numpy数组转换回图像 face_array = np.array(resized_image) # 预测性别 gender_pred = gender_model.predict([face_array]) # 在原始图像上标注性别预测结果 cv2.putText(img, f"Gender: {gender_pred}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) # 显示结果 cv2.imshow("Gender Detection", img) cv2.waitKey(0) # 使用方法 detect_face_and_predict_gender('path_to_your_image.jpg') ``` 请注意,这个示例是简化版本,实际应用中你可能需要更复杂的数据预处理和模型优化。此外,对于精确的性别识别,面部关键点的位置和角度对结果有很大影响,因此人脸对齐预处理也是必要的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值