1.环境参数
运行环境:windows、Linux以及macOS
python版本:Python 3.11.3
依赖库:opencv-python
如果未安装该库的小伙伴,请在方法开始前安装:
在命令终端中键入
pip install opencv-python
等待安装完成即可!
2.实现方法(代码部分)
import cv2
import sys
import tkinter
from tkinter import END, filedialog
# 获取人脸识别分类器
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
def detect_faces():
# 读取图像
image = cv2.imread(entry.get())
if image is None:
print("Sorry, the system did not find your face.")
sys.exit()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# 在人脸周围画矩形框
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow("Faces found", image)
cv2.waitKey(0)
# ‘选择文件’按钮点击之后的执行逻辑
def select_file():
file_path = filedialog.askopenfilename()
entry.delete(0, END)
entry.insert(0, file_path)
# 创建主窗口
window = tkinter.Tk()
window.title('Please put your face up')
window.geometry('400x100')
# 创建输入框和按钮
label = tkinter.Label(window, fg='red', text="在输入框键入请使用文件的绝对路径!!!")
label.pack()
entry = tkinter.Entry(window)
entry.pack(side='left')
select_button = tkinter.Button(window, text="选择文件", command=select_file)
select_button.pack(side='left')
button = tkinter.Button(window, text="开始识别", fg='red', command=detect_faces)
button.pack(side='left')
# 运行主循环
window.mainloop()
3.什么话这是?
当你停止尝试时,就是失败的时候。