基于opencv和tkinter的人脸器官检测与界面搭建

课上的一个小作业,拿出来分享一下。

import tkinter
import cv2 as cv
from tkinter import *

def open_camera():
    cap = cv.VideoCapture(0, cv.CAP_DSHOW)
    while cap.isOpened():
        ret, img = cap.read()
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 实例化级联分类器
        face_cas = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
        eye_cas = cv.CascadeClassifier("haarcascade_eye.xml")
        # 加载分类器
        # face_cas.load('haarcascade_frontalface_default.xml')
        # eye_cas.load('haarcascade_eye.xml')
        # 利用各个分类器进行检测
        face_cas_detect_faces = face_cas.detectMultiScale(img, scaleFactor=1.2, minNeighbors=5)
        eye_cas_detect_eye = eye_cas.detectMultiScale(img, scaleFactor=1.3, minNeighbors=5)

        # 在画面中画出检测部位
        draw_face(img, face_cas_detect_faces)
        draw_eyes(img, eye_cas_detect_eye)
        # draw_mouth(img,mouth_cas_detect_mouths)
        cv.imshow("detect_window", img)
        if cv.waitKey(1) == ord("q"):
            break
    cap.release()
    cv.destroyAllWindows()

def draw_face(img,faces):
    for (x, y, w, h) in faces:
        # 画出人脸框,红色(BGR色彩体系)
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 1)

def draw_eyes(img,eyes):
    for (x, y, w, h) in eyes:
        # 画出眼框,绿色(BGR色彩体系)
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)

def draw_mouth(img,mouths):
    for (x, y, w, h) in mouths:
        # 画出嘴框,紫色(BGR色彩体系)
        cv.rectangle(img, (x, y), (x + w, y + h), (128, 0, 128), 1)
#窗口关闭函数
def window_break():
    root.destroy()

#主框架窗口
root=Tk()
root.geometry('800x600')
root.title("人脸识别python程序控制台")
#控制台大标题
label1=Label(root,text='我的人脸识别,张老师指导',font=('华文楷体',20))
label1.place(x=170,y=30)
#校徽图片的加载
photo=tkinter.PhotoImage(file='xiaohui.gif')
label2=Label(root,image=photo)
label2.place(x=210,y=90)
#摄像头打开按钮
btn1=Button(root,text='打开摄像头',command=open_camera)
btn1.place(x=290,y=270,width=80,height=50)
#窗口关闭按钮
btn2=Button(root,text='关闭窗口',command=window_break)
btn2.place(x=400,y=270,width=80,height=50)
#更新日志
txt=Text(root)
txt.place(x=200,y=350,width=370,height=80)
txt.insert('1.0','更新日志:10月8日 完善按钮控件功能\n          10月2日 调整用于检测的级联分类器\n          \
9月26日 项目完善\n          9月20日 项目创建')
root.mainloop()

你可能感兴趣的:(opencv,python,计算机视觉)