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

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()

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Python和OpenCV的人脸识别代码,可以实现对人脸的性别和年龄识别: ```python import cv2 import math # 加载Haar特征分类器 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') # 定义性别和年龄标签 gender_list = ['Male', 'Female'] age_list = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)'] # 初始化摄像头 cap = cv2.VideoCapture(0) while True: # 读取摄像头捕获的帧 ret, frame = cap.read() # 转换成灰度图像 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 检测人脸 faces = face_cascade.detectMultiScale(gray, 1.3, 5) # 绘制人脸矩形框,并进行性别和年龄识别 for (x, y, w, h) in faces: # 绘制人脸矩形框 cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) # 根据人脸大小调整图像大小 face = cv2.resize(gray[y:y + h, x:x + w], (227, 227)) # 进行性别识别 gender_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False) gender_net.setInput(gender_blob) gender_preds = gender_net.forward() gender = gender_list[gender_preds[0].argmax()] # 进行年龄识别 age_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False) age_net.setInput(age_blob) age_preds = age_net.forward() age = age_list[age_preds[0].argmax()] # 在人脸矩形框下方绘制性别和年龄信息 cv2.putText(frame, "Gender: " + gender, (x, y + h + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) cv2.putText(frame, "Age: " + age, (x, y + h + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) # 显示帧 cv2.imshow('frame', frame) # 按'q'键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头并关闭所有窗口 cap.release() cv2.destroyAllWindows() ``` 其中,`deploy_gender.prototxt`和`gender_net.caffemodel`是用于性别识别的深度学习模型文件;`deploy_age.prototxt`和`age_net.caffemodel`是用于年龄识别的深度学习模型文件。在代码中,我们使用`cv2.dnn.readNetFromCaffe()`函数读取模型文件,并使用`cv2.dnn.blobFromImage()`函数将人脸图像转换成网络所需的格式。最后,根据网络输出的预测结果,确定性别和年龄标签,并在图像上显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值