Beispiel #1
0
    def _register(self, frame, gray, username):
        """Detects faces in frames and uses them to train a face recognition algorithm.
            Face data is associated with the given username.
            :param frame: an 8 bit, 3-channel UMat object
            :param gray: an 8-bit, 1-channel ndarray
            :param username: name of registering user
        """
        if self.samples < self.sample_size:

            # Find all faces and store only the location of the largest (closest to the camera)
            faces = self._findFaces(frame)
            max_area = 0
            x = 0
            y = 0
            w = 0
            h = 0
            for (startX, startY, endX, endY) in faces:
                c_w = endX - startX
                c_h = endY - startY
                if c_w * c_h > max_area:
                    x = startX
                    y = startY
                    w = c_w
                    h = c_h
                    maxArea = w * h

            # Resize and add face image to list for training
            if faces:
                self.samples += 1
                gray = cv2.UMat(gray, [y, y + h], [x, x + w])
                gray = cv2.resize(gray, (100, 100))
                self.sample_images.append(gray)

        else:
            # Finished collecting face data
            # Associate registering user id with training data
            db = DBHelper()
            user_id = db.getIDByUsername(username)
            id_array = [user_id] * self.sample_size

            for i in range(self.sample_size):
                self.sample_images[i] = cv2.UMat.get(self.sample_images[i])

# Update or create new face recognizer
            if Path('./training_data/recognizer.yml').is_file():
                self.recognizer.update(self.sample_images, np.array(id_array))
            else:
                self.recognizer.train(self.sample_images, np.array(id_array))
            self.recognizer.write('./training_data/recognizer.yml')

            # registration complete
            self.reg_complete = True
            self.rec_trained = True

            # reset variables before detection begins
            self._reset()

        return frame