系统分析与设计HW3

python+opencv+tkinter button实现人脸检测

众所周知,opencv和dlib是人脸识别比较好用的工具。之前做实验想要实现一个能够实时识别人脸的程序,但是发现opencv的交互不友好,在退出捕捉视频行为的时候,网上常用的教程是

   cap=cv2.VideoCapture(0)
    if key == ord('q'):
        break

需要手动输入字母q才能退出程序,这样一点也不方便。自己想用button来控制程序开始和停止。使用button控件就需要用到tkinter库,并且要把opencv捕捉的视频流用tkinter的Label控件实时的显示出来,下面是具体实现:
opencv和dlib的安装方法可自行搜索(* ̄︶ ̄)

import os
import numpy as np
from PIL import Image
import tensorflow as tf
import math
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import time
import dlib
from skimage import io
import cv2
import glob

if __name__ == "__main__":

        predictor_path = "shape_predictor_68_face_landmarks.dat"
        predictor = dlib.shape_predictor(predictor_path)
        detector = dlib.get_frontal_face_detector()
        window = Tk()  #Makes main window
        window.wm_title("Digital Microscope")
        window.config(background="#FFFFFF")

        #Graphics window
        imageFrame = Frame(window, width=640, height=480)
        imageFrame.grid(row=0, column=0, padx=10, pady=2)
        def show_real():
            _, frame = cap1.read()
            frame = cv2.flip(frame, 1)
            if frame is not None:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                dets = detector(img,0)
                #print("Number of faces detected: {}".format(len(dets)))
                for i,d in enumerate(dets):#人脸识别
                    #print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
                           # i, d.left(), d.top(), d.right(), d.bottom()))
                    shape = predictor(img, d)
                        #shapes.append(shape)
                    for p in shape.parts():
                        cv2.circle(frame,(p.x,p.y),2,(0,0,0),-1)#将捕捉到的landmark点用opencv画上去
                img = Image.fromarray(frame)
                imgtk = ImageTk.PhotoImage(image=img)
                lmain.imgtk = imgtk
                lmain.configure(image=imgtk)
                lmain.after(10,show_real) #不断更新实现实时的效果           
        def realtime_start():
            global lmain
            lmain = Label(imageFrame)
            lmain.grid(row=0, column=0)
            global cap1#设置捕捉摄像头
            cap1 = cv2.VideoCapture(0)
            show_real()
            print("start")
        def realtime_stop():
            global cap1
            cap1.release()
            cv2.destroyAllWindows()
            print("stop")
        #button控件使用    
        e = Button(window,text='realtime_start',command=realtime_start)
        e.grid(row =1,column=0)  
        f = Button(window,text='realtime_stop',command=realtime_stop)
        f.grid(row =2,column=0)              
        window.mainloop() 

最后实现用button控件来控制识别开始和结束啦
这里写图片描述

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页