Exemple #1
0
    def DeleteFaces(self, labels):
        foption = FileOption()
        foption.DeleteFaceInfos(labels)
        foption.DeleteEncoding(labels)
        for label in labels:
            index = self.IsIdExist(label)
            if index >= 0:
                del self.dataset[index]

                self.knownsCount -= 1

        self.CvPrint('Deleted ' + str(len(labels)) + ' faces success!')
Exemple #2
0
    def RefreshTable(self, faceInfos=None):

        if None != faceInfos:
            for faceInfo in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(faceInfo.faceId, faceInfo.name,
                                          faceInfo.identity, faceInfo.info))
        else:
            faceInfos = []
            self.fileObject = FileOption()
            self.fileObject.GetFaceAllInfo(faceInfos)
            for item in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(item.faceId, item.name,
                                          item.identity, item.info))
Exemple #3
0
    def AddNewFace(self, faceInfo, encodings):
        #Write to faceinfo file
        foption = FileOption()
        retvalue = foption.WriteFaceInfo(faceInfo)
        if retvalue < 0:
            return retvalue
        #print(faceInfo.info)

        #write to encodings file
        ttuple = (faceInfo.faceId, encodings)
        foption.WriteEncodings(ttuple)

        #Add new face to menory
        datatuple = (faceInfo.faceId, encodings)
        self.dataset.append(datatuple)

        #Synchronization variable value
        self.knownsCount += 1

        return 0
Exemple #4
0
    def FaceInit(self):

        if self.camera is None:
            if os.path.exists(DevicePath0):
                self.camera = 0
            elif os.path.exists(DevicePath1):
                self.camera = 1
            else:
                self.CvPrint('No Camera found')
                return -201

        self.cam = cv2.VideoCapture(self.camera)

        if self.cam.isOpened() is False:
            self.CvPrint('Error: camera open failed!')
            return -202

        self.cam.set(CV_CAP_PROP_FRAME_WIDTH, self.frame_width)  # set Width
        self.cam.set(CV_CAP_PROP_FRAME_HEIGHT, self.frame_height)  # set Height

        # Get all encoded face data
        self.dataset = FileOption().LoadDataset()
        if self.dataset is not None:
            self.knownsCount = len(self.dataset)

        # Define min window size to be recognized as a face
        self.minW = 200
        self.minH = 200
        #self.minW = 0.1*self.cam.get(CV_CAP_PROP_FRAME_WIDTH)
        #self.minH = 0.1*self.cam.get(CV_CAP_PROP_FRAME_HEIGHT)

        self.faceCascade = cv2.CascadeClassifier(cascadesPath)

        string = 'camera ' + str( self.camera ) + ' open success !\n' + \
                'frame width: ' + str( self.cam.get(CV_CAP_PROP_FRAME_WIDTH) ) + '\n'\
                'frame height: ' + str( self.cam.get(CV_CAP_PROP_FRAME_HEIGHT) ) + '\n'\
                'face num: ' + str( self.knownsCount )

        self.CvPrint(string)

        return 0
Exemple #5
0
    def SerchByIdentity(self, content):
        #print(content)
        #clear table
        items = self.table.get_children()
        for item in items:
            self.table.delete(item)
        #refill table
        faceInfos = FileOption().GetFaceListInfo(content)
        if faceInfos is not None:
            for item in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(item.faceId, item.name,
                                          item.identity, item.info))

        return True
Exemple #6
0
 def PermissionVerify(self, event=None):
     permission = self.inputstr.get()
     if 0 == len(permission):
         self.MenuCancel()
         self.facecore.CvPrint('Permission error!')
         #messagebox.showerror(title = 'Error', message = 'Permission error!')
         Popup('Error', 'Permission is null!', 1000, self.wparent)
     else:
         retvalue = FileOption().VerifyPermission(permission)
         if retvalue >= 0:
             self.MenuCancel()
             self.menugui.GuiShow()
         else:
             self.MenuCancel()
             WriteConsole('Permission verify failure')
             #messagebox.showerror(title = Error().GetError(retvalue), message = 'Permission error!')
             Popup(Error().GetError(retvalue), 'Permission error!', 1000,
                   self.wparent)
Exemple #7
0
 def ChangePermission(self, event=None):
     oldp = self.inputTextOld.get()
     newp = self.inputTextNew.get()
     repp = self.inputTextRepeat.get()
     if newp != repp:
         messagebox.showerror(title='Error',
                              message='Repeat permission error',
                              parent=self.topWin)
     else:
         retvalue = FileOption().WritePermission(oldp, newp)
         if retvalue is 0:
             messagebox.showinfo(title='Info',
                                 message='Change permission success!',
                                 parent=self.topWin)
             self.CancelResetPermission()
         elif retvalue < 0:
             messagebox.showerror(title=Error().GetError(retvalue),
                                  message='Old permission error',
                                  parent=self.topWin)
Exemple #8
0
class FaceCore(object):

    # devNum is usb camera device
    def __init__(self, devNum=None, frameWidth=640, frameHeight=480):
        # Define camera farame size
        self.camera = devNum
        self.frame_width = frameWidth
        self.frame_height = frameHeight

        self.cam = None

        self.threadNum = 4

        self.dataset = None
        self.knownsCount = 0

        self.recogResults = []

        self.capImages = None
        self.capSwitch = False

    def FaceInit(self):

        if self.camera is None:
            if os.path.exists(DevicePath0):
                self.camera = 0
            elif os.path.exists(DevicePath1):
                self.camera = 1
            else:
                self.CvPrint('No Camera found')
                return -201

        self.cam = cv2.VideoCapture(self.camera)

        if self.cam.isOpened() is False:
            self.CvPrint('Error: camera open failed!')
            return -202

        self.cam.set(CV_CAP_PROP_FRAME_WIDTH, self.frame_width)  # set Width
        self.cam.set(CV_CAP_PROP_FRAME_HEIGHT, self.frame_height)  # set Height

        # Get all encoded face data
        self.dataset = FileOption().LoadDataset()
        if self.dataset is not None:
            self.knownsCount = len(self.dataset)

        # Define min window size to be recognized as a face
        self.minW = 200
        self.minH = 200
        #self.minW = 0.1*self.cam.get(CV_CAP_PROP_FRAME_WIDTH)
        #self.minH = 0.1*self.cam.get(CV_CAP_PROP_FRAME_HEIGHT)

        self.faceCascade = cv2.CascadeClassifier(cascadesPath)

        string = 'camera ' + str( self.camera ) + ' open success !\n' + \
                'frame width: ' + str( self.cam.get(CV_CAP_PROP_FRAME_WIDTH) ) + '\n'\
                'frame height: ' + str( self.cam.get(CV_CAP_PROP_FRAME_HEIGHT) ) + '\n'\
                'face num: ' + str( self.knownsCount )

        self.CvPrint(string)

        return 0

    def Detection(self):
        ret, img = self.cam.read()

        #img = cv2.flip(img, 0)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        faces = self.faceCascade.detectMultiScale(gray,
                                                  scaleFactor=1.1,
                                                  minNeighbors=5,
                                                  minSize=(int(self.minW),
                                                           int(self.minH)))
        if self.capSwitch and len(faces) > 0:
            retvalue = self.capImages.Put(rgb, faces)
            if retvalue < 0:
                self.capSwitch = False
        return rgb, faces

    def DrawRectangle(self, img, faces):
        for (x, y, w, h) in faces:
            #cv2.imwrite("dataset/User." + str(1) + '.' + str(1) + ".jpg", gray[y:y+h,x:x+w])
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    def DetectionFromImage(self, img):

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        faces = self.faceCascade.detectMultiScale(gray,
                                                  scaleFactor=1.1,
                                                  minNeighbors=5,
                                                  minSize=(100, 100))
        return rgb, faces

    def GetImageDirs(self, dirname, imagedirs):

        listfiles = os.listdir(dirname)
        if len(listfiles) == 0:
            self.CvPrint('null dir')
            return -205
        for file in listfiles:
            fpath = os.path.join(dirname, file)

            if os.path.isdir(fpath):
                self.GetImageDirs(fpath, imagedirs)
            else:
                if os.path.splitext(file)[1] == '.jpg':
                    imagedirs.append((fpath, file))
        return 0

    def TrainFromFile(self, dirname, progressbar):
        faillist = []
        faceInfos = []
        imagedirs = []
        box = None
        retvalue = self.GetImageDirs(dirname, imagedirs)
        if retvalue < 0:
            return retvalue, [], []
        progressbar.SetProgressBarValue(0, len(imagedirs))

        for i, item in enumerate(imagedirs):
            imagepath = item[0]
            fname = item[1]
            infos = fname.split('_')
            #print(infos)
            if len(infos) == 3:
                img = cv2.imread(imagepath)

                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                faces = self.faceCascade.detectMultiScale(gray,
                                                          scaleFactor=1.1,
                                                          minNeighbors=5,
                                                          minSize=(100, 100))

                if len(faces) is 0:
                    progressbar.Update(i + 1)
                    faillist.append(fname)
                    continue
                else:
                    for (x, y, w, h) in faces:
                        box = (y, x + w, y + h, x)

                faceSamples = []
                knownEncodings = []
                boxes = []
                for j in range(samplingtimes):
                    faceSamples.append(rgb)
                    boxes.append(box)

                for k, face in enumerate(faceSamples):
                    # compute the facial embedding for the face
                    encoding = face_recognition.face_encodings(
                        face, [boxes[k]])
                    knownEncodings.append(encoding[0])

                while True:
                    faceId = random.getrandbits(31)
                    retvalue = self.IsIdExist(str(faceId))
                    if retvalue < 0:
                        break

                name = infos[0].replace('-', ' ')
                identity = infos[1]
                note = infos[2].split('.')[0].replace('-', ' ')
                faceInfo = FaceInfo(faceId, name, identity, note)
                retvalue = self.AddNewFace(faceInfo, knownEncodings)
                if retvalue < 0:
                    faillist.append(fname)
                else:
                    faceInfos.append(faceInfo)

            else:
                faillist.append(fname)
            progressbar.Update(i + 1)
        progressbar.Release()
        return 0, faceInfos, faillist

    def TrainFromCamera(self, faceInfo):
        if self.cam.isOpened is False:
            self.CvPrint('Error: camera is not open')
            #self.Message(2, 'Error', 'camera is not open')
            return -202

        count = 0
        faceSamples = []
        knownEncodings = []
        boxes = []

        string = "\n [INFO] Initializing face capture."
        #self.Message(0, 'info', string)
        self.CvPrint(string)

        while True:
            faceId = random.getrandbits(31)
            retvalue = self.IsIdExist(str(faceId))
            if retvalue < 0:
                break

        self.capSwitch = True
        self.capImages = DetImages(samplingtimes)
        while self.capSwitch:
            time.sleep(0.2)

        while True:
            rgb, faces = self.capImages.Get()
            if faces is None:
                break
            for (x, y, w, h) in faces:
                # OpenCV returns bounding box coordinates in (x, y, w, h) order
                # but we need them in (top, right, bottom, left) order, so we
                # need to do a bit of reordering
                #boxes = [(y, x + w, y + h, x) for (x, y, w, h) in faces]
                box = (y, x + w, y + h, x)
                count += 1
                faceSamples.append(rgb)
                boxes.append(box)
                break

            if count >= samplingtimes:
                break

        if len(faceSamples) is 0:
            string = "\n [INFO] No faces deteched, Training faces failed!"
            #self.Message(0, 'info', string)
            self.CvPrint(string)
            return -203

        for i, face in enumerate(faceSamples):
            # compute the facial embedding for the face
            encoding = face_recognition.face_encodings(face, [boxes[i]])
            knownEncodings.append(encoding[0])

        faceInfo.faceId = faceId
        retvalue = self.AddNewFace(faceInfo, knownEncodings)
        if retvalue < 0:
            return retvalue

        # Print the numer of faces trained and end program
        string = "\n [INFO] 1 faces trained."
        #self.Message(0, 'info', string)
        self.CvPrint(string)

        return 0

    def FaceRecognition(self, result):
        if self.cam.isOpened is False:
            self.CvPrint('Error: camera is not open')
            #self.Message(2, 'Error', 'camera is not open')
            return -202

        self.recogResults.clear()  #empty the result list

        #print(self.tempRecognizerCount)
        if 0 >= self.knownsCount:
            self.errorMessage = 'No face model exist'
            self.CvPrint('Error: No face model exist')
            return -204

        self.capSwitch = True
        self.capImages = DetImages(1)

        while self.capSwitch:
            time.sleep(0.1)

        encoding = None
        rgb, faces = self.capImages.Get()

        for (x, y, w, h) in faces:
            box = (y, x + w, y + h, x)
            encoding = face_recognition.face_encodings(rgb, [box])

        threads = []

        if self.knownsCount < 4 * 2:
            self.threadNum = 1
            taskNum = self.knownsCount
        else:
            taskNum = int(self.knownsCount / 4)

        for i in range(self.threadNum):
            start = i * taskNum
            end = (i + 1) * taskNum
            if (i + 1) == self.threadNum and end < self.knownsCount:
                end = self.knownsCount
            thread = MyThread(self.Recognition, encoding[0], start, end)
            thread.start()
            threads.append(thread)

        for th in threads:
            th.join()

        if len(self.recogResults) > 0:
            self.recogResults.sort(key=lambda k: k[0])  #sort by value
            final = self.recogResults[0]

            label = final[1]
            distance = final[0]
            faceInfo = FileOption().GetFaceInfo(label)
        else:
            distance = 1.0
            faceInfo = FileOption().UnkownFaceInfo()

        string2 = faceInfo.eToString() + '\nDistance: ' + str(distance)
        self.CvPrint(string2)
        result.update({'faceinfo': faceInfo, 'distance': str(distance)})

        return 0

        #cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
        #cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)

    def Recognition(self, encoding, start, end):
        for i in range(start, end):
            distances = face_recognition.face_distance(self.dataset[i][1],
                                                       encoding)
            distance = (distances[0] + distances[1] +
                        distances[2]) / samplingtimes
            #print(self.dataset[i][0] + ' ' + str(distance))
            if distance < Unkown:
                result = (distance, self.dataset[i][0])
                self.recogResults.append(result)
            #print(threading.currentThread().ident)

    def Message(self, priority, title, content):
        if 2 == priority:
            messagebox.showerror(title=title,
                                 message=content,
                                 parent=self.parentWidget)
        else:
            messagebox.showinfo(title=title,
                                message=content,
                                parent=self.parentWidget)

    def CvPrint(self, content):
        gui.WriteConsole(content)
        print(content)

    def AddNewFace(self, faceInfo, encodings):
        #Write to faceinfo file
        foption = FileOption()
        retvalue = foption.WriteFaceInfo(faceInfo)
        if retvalue < 0:
            return retvalue
        #print(faceInfo.info)

        #write to encodings file
        ttuple = (faceInfo.faceId, encodings)
        foption.WriteEncodings(ttuple)

        #Add new face to menory
        datatuple = (faceInfo.faceId, encodings)
        self.dataset.append(datatuple)

        #Synchronization variable value
        self.knownsCount += 1

        return 0

    def IsIdExist(self, label):  # label type is str
        if self.dataset is not None:
            for i, item in enumerate(self.dataset):
                #print(str(label) + ' ' + str(item))
                if str(label) == str(item[0]):
                    return i
        return -1

    def DeleteFaces(self, labels):
        foption = FileOption()
        foption.DeleteFaceInfos(labels)
        foption.DeleteEncoding(labels)
        for label in labels:
            index = self.IsIdExist(label)
            if index >= 0:
                del self.dataset[index]

                self.knownsCount -= 1

        self.CvPrint('Deleted ' + str(len(labels)) + ' faces success!')

    def __del__(self):
        print('destroy object CvCore')
        if None != self.cam:
            if self.cam.isOpened():
                self.cam.release()
Exemple #9
0
    def FaceRecognition(self, result):
        if self.cam.isOpened is False:
            self.CvPrint('Error: camera is not open')
            #self.Message(2, 'Error', 'camera is not open')
            return -202

        self.recogResults.clear()  #empty the result list

        #print(self.tempRecognizerCount)
        if 0 >= self.knownsCount:
            self.errorMessage = 'No face model exist'
            self.CvPrint('Error: No face model exist')
            return -204

        self.capSwitch = True
        self.capImages = DetImages(1)

        while self.capSwitch:
            time.sleep(0.1)

        encoding = None
        rgb, faces = self.capImages.Get()

        for (x, y, w, h) in faces:
            box = (y, x + w, y + h, x)
            encoding = face_recognition.face_encodings(rgb, [box])

        threads = []

        if self.knownsCount < 4 * 2:
            self.threadNum = 1
            taskNum = self.knownsCount
        else:
            taskNum = int(self.knownsCount / 4)

        for i in range(self.threadNum):
            start = i * taskNum
            end = (i + 1) * taskNum
            if (i + 1) == self.threadNum and end < self.knownsCount:
                end = self.knownsCount
            thread = MyThread(self.Recognition, encoding[0], start, end)
            thread.start()
            threads.append(thread)

        for th in threads:
            th.join()

        if len(self.recogResults) > 0:
            self.recogResults.sort(key=lambda k: k[0])  #sort by value
            final = self.recogResults[0]

            label = final[1]
            distance = final[0]
            faceInfo = FileOption().GetFaceInfo(label)
        else:
            distance = 1.0
            faceInfo = FileOption().UnkownFaceInfo()

        string2 = faceInfo.eToString() + '\nDistance: ' + str(distance)
        self.CvPrint(string2)
        result.update({'faceinfo': faceInfo, 'distance': str(distance)})

        return 0
Exemple #10
0
class MenuGui:
    def __init__(self, wparent, facecore):
        self.topWin = None
        self.wparent = wparent
        self.facecore = facecore
        self.isTraning = False

    def GuiShow(self):

        self.topWin = tk.Toplevel()
        self.topWin.title('Menu')
        width = 640
        height = 500

        dx = self.wparent.winfo_x()
        dy = self.wparent.winfo_y()
        self.topWin.geometry("%dx%d+%d+%d" % (width, height, dx, dy))
        self.topWin.minsize(width, height)
        self.topWin.maxsize(width, height)
        #self.topWin.wm_attributes('-type', 'splash')

        self.topWin.protocol('WM_DELETE_WINDOW',
                             lambda: self.CallBack(self.topWin))

        frame = tk.Frame(self.topWin)
        frame.pack(fill=tk.BOTH, expand=True)

        #-------------------------- topWin ----------------------------

        frame_left1 = tk.Frame(frame, highlightthickness = 1, highlightbackground = 'gray'\
                               , bg = 'white', width = 150)
        frame_left1.pack(side=tk.LEFT, fill=tk.BOTH, padx=5, pady=5)
        frame_left1.propagate(
            False
        )  #Setting to True means that the geometry of the parent component is determined by the child component (the default) and vice versa

        frame_left2 = tk.Frame(frame, highlightthickness = 1, highlightbackground = 'gray'\
                               , highlightcolor = 'gray', bg = 'white', )
        frame_left2.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, pady=5)

        #-------------------------- frame_left1 ( function menu )----------------------------

        self.labels = []
        options = [' Management', ' New face', ' Change permission']
        for item in options:
            label_left = tk.Label(frame_left1,
                                  text=item,
                                  bg='white',
                                  anchor=tk.W)
            label_left.pack(fill=tk.X)
            label_left.bind(
                '<Button-1>',
                self.handlerAdaptor(self.lbChangeBackGround,
                                    index=options.index(item)))
            self.labels.append(label_left)
        self.labels[0].config(bg='deepskyblue')

        #-------------------------- frame_left2 ----------------------------

        self.listFrames = []

        frame_left2_1 = tk.Frame(frame_left2, bg='white', padx=5, pady=5)
        frame_left2_1.propagate(False)
        frame_left2_1.pack(fill=tk.BOTH, expand=True)
        self.listFrames.append(frame_left2_1)

        frame_left2_2 = tk.Frame(frame_left2, bg='white', padx=5, pady=5)
        frame_left2_2.propagate(False)
        self.listFrames.append(frame_left2_2)

        frame_left2_3 = tk.Frame(frame_left2, bg='white', padx=5, pady=5)
        frame_left2_3.propagate(False)
        self.listFrames.append(frame_left2_3)

        #-------------------------- frame_left2_1 ( face list )----------------------------
        frame_left2_1_1 = tk.Frame(frame_left2_1)
        frame_left2_1_1.pack(fill=tk.BOTH, expand=True)
        s = ttk.Style()
        s.configure('Treeview', rowheight=25)

        self.table = ttk.Treeview(frame_left2_1_1,
                                  show='headings',
                                  selectmode='extended')
        self.table.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.table.config(columns=('label', 'name', 'identity', 'note'))
        self.table.heading('label', text='label')
        self.table.column('label', width='20')
        self.table.heading('name', text='name')
        self.table.column('name', width='10')
        self.table.heading('identity', text='identity')
        self.table.column('identity', width='20')
        self.table.heading('note', text='note')
        self.table.column('note', width='30')
        #self.table['show'] = 'headings'
        #self.table.column("#0", width = 0)

        scrollbar = ttk.Scrollbar(frame_left2_1_1)
        scrollbar.pack(side=tk.LEFT, fill=tk.Y)
        scrollbar.config(command=self.table.yview)
        self.table.config(yscrollcommand=scrollbar.set)

        serch_frame = tk.Frame(frame_left2_1, bg='white')
        serch_frame.pack(fill=tk.X)
        serch_frame.config(pady=5)
        serchlabel = tk.Label(serch_frame,
                              text='Serch: ',
                              anchor=tk.E,
                              bg='white')
        serchlabel.pack(side=tk.LEFT)
        vcmd = self.topWin.register(self.SerchByIdentity)
        serchentry = tk.Entry(serch_frame,
                              validate="key",
                              validatecommand=(vcmd, '%P'),
                              highlightcolor='deepskyblue')
        serchentry.pack(side=tk.RIGHT, fill=tk.X, expand=True)



        button_frame = tk.Frame(frame_left2_1, height = 40, bg = 'white', pady = 2\
                                , highlightthickness = 1, highlightbackground = 'gray')
        #button_frame.propagate(False)
        button_frame.pack(fill=tk.X)

        button_f1 = tk.Button(button_frame,
                              text='Cancel',
                              command=self.UnSelectTable)
        button_f1.pack(side=tk.RIGHT, padx=2)
        button_f2 = tk.Button(button_frame,
                              text='Delete',
                              command=self.DeleteTableItems)
        button_f2.pack(side=tk.RIGHT, padx=2)
        button_f3 = tk.Button(button_frame,
                              text='Delete all',
                              command=lambda: self.DeleteTableItems(True))
        button_f3.pack(side=tk.RIGHT, padx=2)

        #fill the table
        self.RefreshTable()

        #-------------------------- frame_left2_2 ( new face )----------------------------

        fram_2_2_base1 = tk.Frame(frame_left2_2, bg = 'white'\
                                   ,highlightthickness = 1, highlightbackground = 'gray', highlightcolor = 'gray')
        fram_2_2_base1.propagate(False)
        fram_2_2_base1.pack(fill=tk.BOTH, expand=True)
        frame_2_2_base = tk.Frame(fram_2_2_base1, bg = 'white', width = 350, height = 400, pady = 20\
                                  ,padx = 50)
        frame_2_2_base.propagate(False)
        frame_2_2_base.pack()

        frame_2_2_1 = tk.Frame(frame_2_2_base, bg='white')
        #frame_2_2_1.propagate(False)
        frame_2_2_1.pack(fill=tk.X, pady=10)
        self.inputText1 = tk.Entry(frame_2_2_1, highlightcolor='deepskyblue')
        self.inputText1.pack(side=tk.RIGHT)
        labelText1 = tk.Label(frame_2_2_1,
                              bg='white',
                              text='Name: ',
                              anchor=tk.E)
        labelText1.pack(side=tk.RIGHT)

        frame_2_2_1 = tk.Frame(frame_2_2_base, bg='white')
        #frame_2_2_1.propagate(False)
        frame_2_2_1.pack(fill=tk.X, pady=10)
        self.inputText2 = tk.Entry(frame_2_2_1, highlightcolor='deepskyblue')
        self.inputText2.pack(side=tk.RIGHT)
        labelText2 = tk.Label(frame_2_2_1,
                              bg='white',
                              text='Identity: ',
                              anchor=tk.E)
        labelText2.pack(side=tk.RIGHT)

        frame_2_2_2 = tk.Frame(frame_2_2_base, bg='white')
        #frame_2_2_2.propagate(False)
        frame_2_2_2.pack(fill=tk.X, pady=10)
        self.inputText3 = tk.Text(frame_2_2_2,
                                  width=20,
                                  height=5,
                                  wrap=tk.WORD,
                                  highlightcolor='deepskyblue')
        self.inputText3.pack(side=tk.RIGHT)
        labelText3 = tk.Label(frame_2_2_2,
                              bg='white',
                              text='Note: ',
                              anchor=tk.NE)
        labelText3.pack(side=tk.RIGHT, fill=tk.Y)

        frame_2_2_base2 = tk.Frame(frame_left2_2, bg = 'white', pady = 2\
                                   ,highlightthickness = 1, highlightbackground = 'gray')
        #frame_2_2_4.propagate(False)
        frame_2_2_base2.pack(side=tk.BOTTOM, fill=tk.X, pady=5)
        button_f21 = tk.Button(frame_2_2_base2,
                               text='Clear',
                               command=self.ClearFaceInput)
        button_f21.pack(side=tk.RIGHT, padx=2)
        # =============================================================================
        #
        #         button_f22 = tk.Button(frame_2_2_base2, text = 'Train', width = 5, command = lambda:MyThread(self.CreateNewFaceTest).start() )
        # =============================================================================
        button_f22 = tk.Button(
            frame_2_2_base2,
            text='Train',
            width=5,
            command=lambda: MyThread(self.CreateNewFace).start())
        button_f22.pack(side=tk.RIGHT, padx=2)
        # =============================================================================
        #         button_f22 = tk.Button(frame_2_2_base2, text = 'Train', width = 5, command = self.CreateNewFace)
        #         button_f22.pack(side = tk.RIGHT, padx = 2)
        # =============================================================================
        button_f23 = tk.Button(frame_2_2_base2,
                               text='Trainfromfile',
                               width=10,
                               command=self.CreatNewFaceFromFile)
        button_f23.pack(side=tk.LEFT, padx=2)

        #-------------------------- frame_left2_3 (change permission)----------------------------

        frame_2_3_base1 = tk.Frame(frame_left2_3, bg = 'white'\
                                   ,highlightthickness = 1, highlightbackground = 'gray', highlightcolor = 'gray')
        frame_2_3_base1.propagate(False)
        frame_2_3_base1.pack(fill=tk.BOTH, expand=True)
        frame_2_3_base = tk.Frame(frame_2_3_base1,
                                  bg='white',
                                  width=300,
                                  height=400,
                                  pady=20)
        frame_2_3_base.propagate(False)
        frame_2_3_base.pack()

        frame_2_3_1 = tk.Frame(frame_2_3_base, bg='white')
        #frame_2_3_1.propagate(False)
        frame_2_3_1.pack(fill=tk.X, pady=10)
        self.inputTextOld = tk.Entry(frame_2_3_1,
                                     show='*',
                                     highlightcolor='deepskyblue')
        self.inputTextOld.pack(side=tk.RIGHT)
        labelText1 = tk.Label(frame_2_3_1,
                              bg='white',
                              text='old permission: ',
                              anchor=tk.E)
        labelText1.pack(side=tk.RIGHT)

        frame_2_3_2 = tk.Frame(frame_2_3_base, bg='white')
        #frame_2_3_2.propagate(False)
        frame_2_3_2.pack(fill=tk.X, pady=10)
        self.inputTextNew = tk.Entry(frame_2_3_2,
                                     show='*',
                                     highlightcolor='deepskyblue')
        self.inputTextNew.pack(side=tk.RIGHT)
        labelText1 = tk.Label(frame_2_3_2,
                              bg='white',
                              text='new permission: ',
                              anchor=tk.E)
        labelText1.pack(side=tk.RIGHT)

        frame_2_3_3 = tk.Frame(frame_2_3_base, bg='white')
        #frame_2_3_3.propagate(False)
        frame_2_3_3.pack(fill=tk.X, pady=10)
        self.inputTextRepeat = tk.Entry(frame_2_3_3,
                                        show='*',
                                        highlightcolor='deepskyblue')
        self.inputTextRepeat.pack(side=tk.RIGHT)
        labelText1 = tk.Label(frame_2_3_3,
                              bg='white',
                              text='repeat: ',
                              anchor=tk.E)
        labelText1.pack(side=tk.RIGHT)


        frame_2_3_base2 = tk.Frame(frame_left2_3, bg = 'white', pady = 2\
                                   ,highlightthickness = 1, highlightbackground = 'gray')
        #frame_2_2_4.propagate(False)
        frame_2_3_base2.pack(side=tk.BOTTOM, fill=tk.X, pady=5)
        button_f21 = tk.Button(frame_2_3_base2,
                               text='Cancel',
                               command=self.CancelResetPermission)
        button_f21.pack(side=tk.RIGHT, padx=2)
        button_f22 = tk.Button(frame_2_3_base2,
                               text='Change',
                               width=5,
                               command=self.ChangePermission)
        button_f22.pack(side=tk.RIGHT, padx=2)

    def CallBack(self, win):
        if threadCount is 0:
            win.destroy()

    def handlerAdaptor(self, fun, **kwds):
        return lambda event, fun=fun, kwds=kwds: fun(event, **kwds)

    def lbChangeBackGround(self, event, index):
        for i, item in enumerate(self.labels):
            if index == i:
                item.config(bg='deepskyblue')
                self.listFrames[i].pack(fill=tk.BOTH, expand=True)
                if i == 1:
                    self.inputText1.focus_set()
                elif i == 2:
                    self.inputTextOld.focus_set()
            else:
                item.config(bg='white')
                self.listFrames[i].pack_forget()

    def CreateNewFace(self, event=None):
        if self.isTraning:
            return
        self.isTraning = True
        global threadCount
        threadCount += 1

        name = self.inputText1.get()
        if 0 == len(name):
            name = 'unspecified'

        identity = self.inputText2.get()
        if 0 == len(identity):
            identity = 'unspecified'

        note = self.inputText3.get(0.0, tk.END)
        if 0 == len(note):
            note = 'unspecified'
        note = note.replace('\n', ' ')

        faceInfo = FaceInfo('unspecified', name, identity, note)
        messagebox.showinfo(title='INFO',
                            message='Look the camera and wait ...',
                            parent=self.topWin)
        retvalue = self.facecore.TrainFromCamera(faceInfo)
        faceInfo = [faceInfo]
        if retvalue >= 0:
            Popup('Info', '1 faces trained', 1000, self.topWin)
            #messagebox.showinfo(title = 'INFO', message = '1 faces trained.', parent = self.topWin)
            self.RefreshTable(faceInfo)
        else:
            Popup(Error().GetError(retvalue), 'Add new face failure!', 1500,
                  self.topWin)
        #messagebox.showerror(title = Error().GetError(retvalue), message = 'Add new face failure!'\
        #                  , parent = self.topWin)
        threadCount -= 1
        self.isTraning = False

    def CreatNewFaceFromFile(self):
        dirname = filedialog.askdirectory(initialdir="/home/linjie/Desktop",
                                          title="Select one filedir")
        #dirname = filedialog.askopenfilename()
        if len(dirname) <= 2:
            return
        print(dirname)

        progressbar = Progressbar(self.topWin)
        retvalue, faceInfos, faillist = self.facecore.TrainFromFile(
            dirname, progressbar)
        if retvalue < 0:
            progressbar.Release()
            Popup(Error().GetError(retvalue), 'Not find image!', 1500,
                  self.topWin)
        else:
            add = len(faceInfos)
            fail = len(faillist)
            self.RefreshTable(faceInfos)
            for info in faillist:
                WriteConsole(info)
            info = str(add) + ' faces added successfully,' + str(
                fail) + ' faces added  failed,view console'
            messagebox.showinfo(title='Info', message=info, parent=self.topWin)

    def CreateNewFaceTest(self, event=None):
        count = 2019001
        for i in range(500):
            count += i
            print(count)
            faceInfo = FaceInfo('unspecified', 'linjie', str(count), 'test')
            self.facecore.TrainFromCamera(faceInfo)
            self.RefreshTable(faceInfo)

    def ClearFaceInput(self):
        self.inputText1.delete(0, tk.END)
        self.inputText2.delete(0, tk.END)
        self.inputText3.delete(0.0, tk.END)

    def RefreshTable(self, faceInfos=None):

        if None != faceInfos:
            for faceInfo in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(faceInfo.faceId, faceInfo.name,
                                          faceInfo.identity, faceInfo.info))
        else:
            faceInfos = []
            self.fileObject = FileOption()
            self.fileObject.GetFaceAllInfo(faceInfos)
            for item in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(item.faceId, item.name,
                                          item.identity, item.info))

    def DeleteTableItems(self, deleteAll=False):
        faceIds = []
        obids = []
        if deleteAll is False:
            for item in self.table.selection():
                values = self.table.item(item, 'values')
                faceIds.append(values[0])
                obids.append(item)
                #self.table.delete(item)
                #print(values[0])
        else:
            items = self.table.get_children()
            for item in items:
                values = self.table.item(item, 'values')
                faceIds.append(values[0])
                obids.append(item)
                #self.table.delete(item)
                #print(values[0])
        if len(faceIds) == 0:
            return
        retvalue = messagebox.askokcancel(title = 'Info', message = 'Whether to delete the selected '\
                                          +str( len(faceIds) )+' faces', parent = self.topWin)
        if retvalue:
            for item in obids:
                self.table.delete(item)
            self.facecore.DeleteFaces(faceIds)
            Popup('Info',
                  str(len(faceIds)) + ' faces deleted successfully', 1000,
                  self.topWin)

    def SerchByIdentity(self, content):
        #print(content)
        #clear table
        items = self.table.get_children()
        for item in items:
            self.table.delete(item)
        #refill table
        faceInfos = FileOption().GetFaceListInfo(content)
        if faceInfos is not None:
            for item in faceInfos:
                self.table.insert('',
                                  tk.END,
                                  values=(item.faceId, item.name,
                                          item.identity, item.info))

        return True

    def UnSelectTable(self):
        self.table.selection_remove(self.table.selection())

    def ChangePermission(self, event=None):
        oldp = self.inputTextOld.get()
        newp = self.inputTextNew.get()
        repp = self.inputTextRepeat.get()
        if newp != repp:
            messagebox.showerror(title='Error',
                                 message='Repeat permission error',
                                 parent=self.topWin)
        else:
            retvalue = FileOption().WritePermission(oldp, newp)
            if retvalue is 0:
                messagebox.showinfo(title='Info',
                                    message='Change permission success!',
                                    parent=self.topWin)
                self.CancelResetPermission()
            elif retvalue < 0:
                messagebox.showerror(title=Error().GetError(retvalue),
                                     message='Old permission error',
                                     parent=self.topWin)

    def CancelResetPermission(self):
        self.inputTextOld.delete(0, tk.END)
        self.inputTextNew.delete(0, tk.END)
        self.inputTextRepeat.delete(0, tk.END)

    def __del__(self):
        print('destroy object MenuGui')